HTML代码:
<Input v-model="yanzhengma" style="width:200px;"></Input>
<!-- 画布用于展示验证码 -->
<canvas class="codeCanvas" ref="checkCode" @click="getCode"></canvas>
<Button @click="checkMe">下一步</Button>
参数和变量:
inputCode: '', // 输入的值
checkCode: '', // 图片验证码的值
// canvas各种设置
cvs: {
w: 100, // 给出默认宽度 宽度会在图片绘制时根据长度更改
h: 40, // 高 与input保持一致
fontSize: 24, // 字体大小
// 字符串生成范围
str: '1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM',
len: 4, // 字符串长度
line: 3 // 噪音线个数
}
js函数和方法:
mounted(){
this.getCode();
},
methods:{
onClick(name){
this.status = name
},
getCode(){
// vue的话可直接用$refs取值,不用vue的话可绑定id然后通过document处理
let domCvs = this.$refs.checkCode;
this.drawCode(domCvs);
},
// 随机整数生成器,范围[0, max)
rInt(max) {
return Math.floor(Math.random() * 100000 % max);
},
// 生成随机字符串
rCode() {
let code = '';
let len = this.cvs.len;
let strLen = this.cvs.str.length;
for(let i = 0; i < len; i ++) {
code += this.cvs.str.charAt(this.rInt(strLen));
}
this.checkCode = code;
return code;
},
// 生成随机颜色 rgba格式
rColor() {
let a = ((Math.random()*5 + 5) / 10).toFixed(2);
return `rgba(${this.rInt(256)}, ${this.rInt(256)}, ${this.rInt(256)}, ${a})`
},
// 验证码图片绘制
drawCode(domCvs) {
let _this = this;
// 随机字符串
let checkCode = this.rCode();
// 宽设置
this.cvs.w = 10 + this.cvs.fontSize * this.cvs.len;
// 判断是否支持canvas
if(domCvs !== null && domCvs.getContext && domCvs.getContext('2d')){
// 设置显示区域大小
domCvs.style.width = _this.cvs.w;
// 设置画板宽高
domCvs.setAttribute('width', _this.cvs.w);
domCvs.setAttribute('height', _this.cvs.h);
// 画笔
let pen = domCvs.getContext('2d');
// 背景: 颜色 区域
pen.fillStyle = '#eee';
pen.fillRect(0, 0, _this.cvs.w, _this.cvs.h);
// 水平线位置
pen.textBaseline = 'middle'; // top middle bottom
// 内容
for(let i = 0; i < _this.cvs.len; i ++) {
pen.fillStyle = _this.rColor(); // 随机颜色
pen.font = `bold ${_this.cvs.fontSize}px 微软雅黑`; // 字体设置
// 字符绘制: (字符, X坐标, Y坐标)
pen.fillText(checkCode.charAt(i), 10 + _this.cvs.fontSize * i, 17 + _this.rInt(10));
}
// 噪音线
for(let i = 0; i < _this.cvs.line; i ++) {
// 起点
pen.moveTo(_this.rInt(_this.cvs.w) / 2, _this.rInt(_this.cvs.h));
// 终点
pen.lineTo(_this.rInt(_this.cvs.w), _this.rInt(_this.cvs.h));
// 颜色
pen.strokeStyle = _this.rColor();
// 粗细
pen.lineWidth = '2';
// 绘制
pen.stroke();
}
} else {
this.$message.error('不支持验证码格式,请升级或更换浏览器重试');
}
},
}
最后效果如下: 点击验证码时就自动刷新。