vue2实现登录页验证码(随机数生成)

326 阅读3分钟

登录页面

1700634087978.jpg

思路:

1 整体上是使用了 canvas画布,绘制线段moveTo,lineTo,起点在 canvas宽度范围内随机 ,终点在 canvas高度范围的

2 干扰点arc而且圆心在 canvas宽高范围内随机

3 因为验证码是随机的,所以验证码由外部传入,组件内部监听这个属性的改变,以便重绘验证码fillText,translate位置随机,rotate旋转角度随机

4 既然封装组件了,做了更多的自定义操作,比如字体颜色,大小,验证码背景色,线的的颜色等等都可以作为属性传进来,也就是用户自定义配置,当然也都设置了默认值

5 颜色也都是随机色

逻辑分析:

通过identifyCode属性传参把随机生成的验证码传给验证码组件

1 identifyCodes定义了随机验证码能在哪些字符内产生

2 randomNum 生成 在随机验证码范围内的随机数

3 refreshCode 点击验证码重新在生成新的验证码

4 makeCode 生成新的验证码 位数可指定

实现代码

生成图片代码
<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: '1234'
      },
      fontSizeMin: {
        type: Number,
        default: 35
      },
      fontSizeMax: {
        type: Number,
        default: 35
      },
      backgroundColorMin: {
        type: Number,
        default: 180
      },
      backgroundColorMax: {
        type: Number,
        default: 240
      },
      colorMin: {
        type: Number,
        default: 50
      },
      colorMax: {
        type: Number,
        default: 160
      },
      lineColorMin: {
        type: Number,
        default: 100
      },
      lineColorMax: {
        type: Number,
        default: 200
      },
      dotColorMin: {
        type: Number,
        default: 0
      },
      dotColorMax: {
        type: Number,
        default: 255
      },
      contentWidth: {
        type: Number,
        default: 160
      },
      contentHeight: {
        type: Number,
        default: 40
      }
    },
    watch: {
      identifyCode() {
        this.drawPic()
      }
    },
    mounted() {
      this.drawPic()
    },
    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 + ')'
      },
      transparent() {
        return 'rgb(255,255,255)'
      },
      drawPic() {
        let canvas = document.getElementById('s-canvas')
        let ctx = canvas.getContext('2d')
        ctx.textBaseline = 'bottom'
        // 绘制背景
        ctx.fillStyle = this.randomColor(this.backgroundColorMin, this.backgroundColorMax)
        ctx.fillStyle = this.transparent()
        ctx.fillRect(0, 0, this.contentWidth, this.contentHeight)
        // 绘制文字
        for (let i = 0; i < this.identifyCode.length; i++) {
          this.drawText(ctx, this.identifyCode[i], i)
        }
        // 绘制背景
        this.drawLine(ctx)
        this.drawDot(ctx)
      },
      drawText(ctx, txt, i) {
        ctx.fillStyle = this.randomColor(this.colorMin, this.colorMax)
        ctx.font = this.randomNum(this.fontSizeMin, this.fontSizeMax) + 'px SimHei'
        let x = (i + 1) * (this.contentWidth / (this.identifyCode.length + 1))
        let y = this.randomNum(this.fontSizeMax, this.contentHeight - 5)
        var deg = this.randomNum(-10, 10)
        // 修改坐标原点和旋转角度
        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)
      },
      drawLine(ctx) {
        // 绘制干扰线
        for (let i = 0; i < 8; i++) {
          ctx.strokeStyle = this.randomColor(this.lineColorMin, this.lineColorMax)
          ctx.beginPath()
          ctx.moveTo(this.randomNum(0, this.contentWidth), this.randomNum(0, this.contentHeight))
          ctx.lineTo(this.randomNum(0, this.contentWidth), this.randomNum(0, this.contentHeight))
          ctx.stroke()
        }
      },
      drawDot(ctx) {
        // 绘制干扰点
        for (let i = 0; i < 100; i++) {
          ctx.fillStyle = this.randomColor(0, 255)
          ctx.beginPath()
          ctx.arc(
            this.randomNum(0, this.contentWidth),
            this.randomNum(0, this.contentHeight),
            1,
            0,
            2 * Math.PI
          )
          ctx.fill()
        }
      }
    }
  }
  </script>
登录页面引用代码
<template>
<el-form   label-position="left"  :rules="checkRules" ref="checkForm" :model="model"  @submit.native.prevent="checkAuth">
     <el-form-item prop="username">
       <el-input
         v-model="model.username"
         placeholder="用户名"
         clearable
       ></el-input>
     </el-form-item>
     <el-form-item prop="password">
       <el-input
         type="password"
         v-model="model.password"
         placeholder="密码"
         clearable
       ></el-input>
     </el-form-item>
     <el-form-item prop="captcha">
         <div class="vPicBox">
            <el-input
           v-model="model.captcha"
           placeholder="请输入验证码"
           style="width: 60%"
           />
             <div class="vPic">
             <div class="code" @click="refreshCode">
                   <s-identify :identify-code="identifyCode"></s-identify>
             </div>
             </div>
         </div>
       </el-form-item>
       <el-form-item>
         <el-button type="primary"  size="large" style="width: 100%; margin-left: 0%" native-type="submit">登录</el-button>
       </el-form-item>
     </el-form>
</template>
<script>

import SIdentify from '@/views/SIdentify.vue'
export default {
components: {
 SIdentify,
},
data() {
 var validCode = (rule, value, callback) => {
   if (this.identifyCode !=value) {
     this.refreshCode()
     callback(new Error("请输入正确的验证码"));
   }else {
     callback();
   }
 };
 return {
   model: {
     username:'',
     password:'',
     captcha:''
   },
   identifyCode: "",// 验证码
   identifyCodes: '1234567890',//验证码随机范围
   checkRules:{
     username:[
       { required: true, message: '请输入用户名', trigger: 'blur' }
     ],
     password:[
       { required: true, message: '请输入密码', trigger: 'blur' }
     ],
     captcha:[
     { required: true, message: '请输入验证码', trigger: 'blur' },
     {required: true,validator: validCode, trigger: 'blur' },

     ]
   }
 };
},
mounted() {
    //组件挂载完毕刷新验证码
     this.refreshCode()
 },
methods: {
 // 验证码点击刷新方法
 refreshCode() {
         this.identifyCode = ''
// 4位验证码可以根据自己需要来定义验证码位数
         this.makeCode(this.identifyCodes, 6)
     }, 
// 随机数
     randomNum(min, max) {
         max = max + 1
         return Math.floor(Math.random() * (max - min) + min)
     },
     // 随机生成验证码字符串
     makeCode(data, len) {
         for (let i = 0; i < len; i++) {
             this.identifyCode += data[this.randomNum(0, data.length - 1)]
         }
         console.log("随机验证码:",this.identifyCode)
     },
}
}
</script>

参考链接:www.jianshu.com/p/19c1d990d…