前端完成图形验证码
样式:
html:
<div
class="canvas"
@click="verificationCodeHandle"
>
<canvas id="canvas" />
</div>
mounted() {
this.verificationCodeHandle(); //初始化时调用
},
methods: {
verificationCodeHandle() {
this.getCanvasHandle(); //调用生成验证码的方法
this.imgCode = ''; //点击图形验证码区域,输入的验证码置空,图形验证码更新
}
}
js:
生成图形验证码的方法:
getCanvasHandle() {
const showNum = []; // 生成验证码的存储值
const canvas_width = 71; //设置验证码的宽度
const canvas_height = 34; //设置验证码的高度
const canvas = document.getElementById('canvas'); //获取画布
const context = canvas.getContext('2d'); 2d
canvas.width = canvas_width;
canvas.height = canvas_height;
const sCode = //设置验证码显示内容
'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,1,2,3,4,5,6,7,8,9,0';
const aCode = sCode.split(','); // 转化为数组
const aLength = aCode.length;
for (let i = 0; i <= 3; i++) {
const j = Math.floor(Math.random() * aLength);
const deg = (Math.random() * 30 * Math.PI) / 180;
const txt = aCode[j];
showNum[i] = txt.toLowerCase();
const x = 3 + i * 15; // 文字在canvas上的x坐标
const y = 20 + Math.random() * 8; // 文字在canvas上的y坐标
context.font = 'bold 23px 微软雅黑';
context.translate(x, y);
context.rotate(deg);
context.fillStyle = this.randomColor();
context.fillText(txt, 0, 0);
context.rotate(-deg);
context.translate(-x, -y);
}
for (let i = 0; i <= 3; i++) {
// 验证码上显示线条
context.strokeStyle = this.randomColor();
context.beginPath();
context.moveTo(
Math.random() * canvas_width,
Math.random() * canvas_height
);
context.lineTo(
Math.random() * canvas_width,
Math.random() * canvas_height
);
context.stroke();
}
for (let i = 0; i <= 30; i++) {
// 验证码上显示小点
context.strokeStyle = this.randomColor();
context.beginPath();
const x = Math.random() * canvas_width;
const y = Math.random() * canvas_height;
context.moveTo(x, y);
context.lineTo(x + 1, y + 1);
context.stroke();
}
this.showNum = showNum;
},
randomColor() {
// 得到随机的颜色值
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
return 'rgb(' + r + ',' + g + ',' + b + ')';
},
获取验证码的值的方法:
imgCodeHandle (val) {
const content = this.showNum.join('');
if (val.length === 4 && content === val.toLowerCase()) {
this.codeShow = false;
}else {
this.codeShow = true;
}
},