Vue实现随机验证码功能
  • 作者:admin
  • 发表时间:2020-12-31 07:50
  • 来源:未知

这篇文章主要为大家唐山企业网站详细介绍了Vue实现随机验证码功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了Vue实现随机验证码功能的具体代码,供大家参考,具体内容如下

步骤1: 创建一个名为identify.vue的子组件

<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: 120
},
// 画布高度
contentHeight: {
type: Number,
default: 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 + ')'
},
drawPic() {
let canvas = document.getElementById('s-canvas')
let ctx = canvas.getContext('2d')
ctx.textBaseline = 'bottom'
// 绘制背景
ctx.fillStyle = this.randomColor(this.backgroundColorMin, this.backgroundColorMax)
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)