话不多说,直接上源码,内部有注释,字体旋转地方会比较复杂,在下方有图像解释
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<canvas id="canvas" width="120px" height="40px"></canvas>
<script>
let canvas = document.getElementById('canvas');
let context = canvas.getContext('2d');
draw();
//绘制图形
function draw() {
//每次绘画前,清空画板
context.clearRect(0, 0, 120, 40);
//顶个边框
context.strokeRect(0, 0, 120, 40);
//设置随机数选项
let aCode = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g'];
//画出随机数
for (let i = 0; i < 4; i++) {
let x = 20 + 20 * i;
let y = 20 + 10 * Math.random();
let index = Math.floor(Math.random() * aCode.length);
let txt = aCode[index];
context.font = 'bold 20px 微软雅黑';
context.fillStyle = getColor();
//从此步开始,为字母旋转
context.translate(x, y);
let deg = Math.random() * 70 * Math.PI / 180;
context.rotate(deg);
context.fillText(txt, 0, 0);
context.rotate(-deg);
context.translate(-x, -y);
}
//设置干扰线 8条
for (let i = 0; i < 8; i++) {
context.beginPath();
context.moveTo(Math.random() * 120, Math.random() * 40);
context.lineTo(Math.random() * 120, Math.random() * 40);
context.strokeStyle = getColor();
context.stroke();
}
//设置干扰点 20 个
for (let i = 0; i < 20; i++) {
context.beginPath();
let x = Math.random() * 120;
let y = Math.random() * 40;
context.moveTo(x, y);
context.lineTo(x + 1, y + 1);
context.strokeStyle = getColor();
context.stroke();
}
}
//获取随机颜色
function getColor() {
let r = Math.floor(Math.random() * 256);
let g = Math.floor(Math.random() * 256);
let b = Math.floor(Math.random() * 256);
return `rgb(${r}, ${g}, ${b})`
}
//点击刷新
canvas.onclick = function () {
draw();
}
</script>
</body>
</html>
复制上面的代码即可实现前端验证码的生成,字体旋转原理如下图:
1、首先执行步骤一,将画布移动至目标字体位置,然后进行旋转(注意:旋转为弧度,不为角度)
2、旋转完成后,写入文字,此时写入文字应在旋转完成后的左上角
3、然后执行步骤二,将画布还原至原来的位置