效果图:
大致思路:
1.在<canvas>画布里写出几个字符;
2.给字符一个随机的角度和颜色;
3.给字符上画出一些干扰线和干扰点。
<canvas width="100" height="30" id="canvasRef" @click="handleDrawCode"></canvas>
/** 生成并渲染出验证码图形 */
handleDrawCode () {
const CanvasRef = document.getElementById('canvasRef');
this.showCode = '';
const canvasWidth = CanvasRef.width;
const canvasHeight = CanvasRef.height;
const context = CanvasRef.getContext('2d'); // 获取到canvas画图的环境
context.clearRect(0, 0, canvasWidth, canvasHeight);
const sCode = 'A,B,C,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,m,n,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; // 获取到数组的长度
// 这里获取4位验证码
for (let i = 0; i < 4; i++) {
const j = Math.floor(Math.random() * aLength); // 获取到随机的索引值
const deg = Math.random() - 0.5; // 产生一个随机弧度
const txt = aCode[j]; // 得到随机的一个内容
this.showCode += txt.toLowerCase(); // 转小写
const x = 10 + i * 20; // 文字在canvas上的x坐标
const y = 20 + Math.random() * 8; // 文字在canvas上的y坐标
context.font = '0.5rem 微软雅黑';
context.translate(x, y);
context.rotate(deg);
context.fillStyle = this.getColor();
context.fillText(txt, 0, 0);
context.rotate(-deg);
context.translate(-x, -y);
}
// 验证码上显示5根线条
for (let i = 0; i <= 5; i++) {
context.strokeStyle = this.getColor();
context.beginPath();
context.moveTo(Math.random() * canvasWidth, Math.random() * canvasHeight);
context.lineTo(Math.random() * canvasWidth, Math.random() * canvasHeight);
context.stroke();
}
// 验证码上添加20个小点
for (let i = 0; i <= 20; i++) {
context.strokeStyle = this.getColor(); // 随机生成
context.beginPath();
const x = Math.random() * canvasWidth;
const y = Math.random() * canvasHeight;
context.moveTo(x, y);
context.lineTo(x + 1, y + 1);
context.stroke();
}
},
/** 得到随机的颜色值 */
getColor () {
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 + ')';
},
canvas {
margin-left: 2rem;
vertical-align: middle;
/*vertical-align属性设置一个元素的垂直对齐。*/
box-sizing: border-box;
border: 1px solid #ddd;
cursor: pointer;
background-color: #eee;
}
本文参考 vue/js图形校验码验证 - 简书 来写,原文直接放来我的项目里有些问题,做了一些改动,作为学习笔记供有需要的人参考。