canvas验证码

<template>
  <div class="s-canvas">
    <canvas
      id="s-canvas"
      :width="contentWidth"
      :height="contentHeight"
    ></canvas>
  </div>
</template>
<script>
export default {
  name: "SIdentify",
  props: {
    identifyCode: {
      type: String,
      default: "asdf",
    },
  },
  data() {
    return {
      canvas:"",
      contentWidth: "100",
      contentHeight: "60",
      fontSize: 40,
    };
  },
  methods: {
    // 生成一个随机数
    randomNum(min, max) {
      return Math.floor(Math.random() * (max - min) + min);
    },
    // 生成一个随机的颜色
    randomColor(min, max) {
      let r = this.randomNum(min, max);
      let g = this.randomNum(min, max);
      let b = this.randomNum(min, max);
      return "rgb(" + r + "," + g + "," + b + ")";
    },
    // 绘制code图片
    drawPic() {
      let canvas=this.canvas;
      let ctx = canvas.getContext("2d");
    ctx.clearRect(0,0,canvas.width,canvas.height); 
      // 绘制文字
      for (let i = 0; i < this.identifyCode.length; i++) {
        this.drawText(ctx, this.identifyCode[i], i);
      }
    },
    //绘制文字
    drawText(ctx, txt, i) {
      ctx.fillStyle = this.randomColor(50, 160);
      ctx.font =
        "normal bold " +
        this.randomNum(this.fontSize, this.fontSize) +
        "px SimHei "; //字体大小
      ctx.textBaseline = "alphabetic"; //基线对齐
      let x =
        (i + 1) * ((this.contentWidth - 10) / (this.identifyCode.length + 1));
      let y = this.randomNum(this.fontSize, this.contentHeight - 5);
      var deg = this.randomNum(-45, 45);
      // 修改坐标原点和旋转角度
      ctx.translate(x, y); //移动不同位置  参数偏移量
      ctx.rotate((deg * Math.PI) / 180); //旋转 参数角度
      ctx.fillText(txt, 0, 0);
      // 恢复坐标原点和旋转角度
      ctx.rotate((-deg * Math.PI) / 180);
      ctx.translate(-x, -y);
    },
  },
  watch: {
    identifyCode() {
      this.drawPic();
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.canvas = document.getElementById("s-canvas");
      this.drawPic();
    });
  },
};
</script>

生成4位雅正吗

 // 获取验证码
    getCode(){
       var strArr = [0,1,2,3,4,5,6,7,8,9];
        for(var i=0;i<26;i++) {
            strArr.push(String.fromCharCode(97+i)); // String.fromCharCode()方法
            strArr.push(String.fromCharCode(65+i)); //fromCharCode() 可接受一个指定的 Unicode 值,然后返回一个字符串。
        }
         var newArr = [];
        for(var j = 0;j < 4; j++){
            var a = Math.floor(Math.random()*strArr.length);
            newArr.push(strArr[a]);
        }
        this.imgCode=newArr.join("");
    },
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值