vue实现简约风格验证码

在这里插入图片描述
组件代码如下:

<template>
  <div style="cursor: pointer;" @click="changeCode">
    <canvas id="identify" :width="width" :height="height"></canvas>
  </div>
</template>
<script>
  export default {
    name: 'SIdentify',
    props: {
      // 字体最小值
      fontSizeMin: {
        type: Number,
        default: 20
      },
      // 字体最大值
      fontSizeMax: {
        type: Number,
        default: 20
      },
      //容器宽度
      width: {
        type: Number,
        default: 100
      },
      //容器高度
      height: {
        type: Number,
        default: 28
      }
    },
    data() {
      return {
        code: ""
      }
    },
    methods: {
      randomCode(length) {
        let str = ''
        const arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
          'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E',
          'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
        ]
        for (let i = 0; i < length; i++) {
          let pos = Math.round(Math.random() * (arr.length - 1))
          str += arr[pos]
        }
        this.code = str;
      },
      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 + ')'
      },
      drawImg() {
        let canvas = document.getElementById('identify')
        let ctx = canvas.getContext('2d')
        ctx.textBaseline = 'bottom'
        ctx.fillStyle = "rgb(255,255,255)";
        ctx.strokeStyle = "#FFFFFF";
        ctx.fillRect(0, 0, this.width, this.height);
        this.randomCode(4);
        for (let i = 0; i < this.code.length; i++) {
          this.drawFont(ctx, this.code[i], i)
        }
      },
      drawFont(ctx, txt, i) {
        ctx.fillStyle = this.randomColor(50, 160);
        ctx.font = this.randomNum(this.fontSizeMin, this.fontSizeMax) + 'px SimHei';
        let x = (i + 1) * (this.width / (this.code.length + 1));
        let y = this.randomNum(this.fontSizeMax, this.height - 5);
        var deg = this.randomNum(-30, 30);
        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)
      },
      changeCode() {
        this.drawImg();
        this.$emit('changeCode', this.code);
      }
    },
    mounted() {
      this.drawImg()
    }
  }
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值