实现图形验证码的步骤
- 首先,需要创建一个 canvas 画布:
const canvas = document.createElement("canvas");
- 然后,可以使用函数 setCanvasSize 设置 canvas 画布的宽度和高度:
function setCanvasSize(width, height) {
canvas.width = width;
canvas.height = height;
}
- 接着,可以使用函数 drawCode 把图形验证码绘制在画布上:
function drawCode() {
ctx.beginPath();
ctx.fillStyle = " #f00";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = " #000";
ctx.font = fontSize + "px Arial";
let charArr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, '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'];
for (let i = 0; i < codeLen; i++) {
let index = Math.floor(Math.random() * 36);
let rotation = Math.random() * 90 * Math.PI / 180;
let x = 13 + i * 20;
let y = 25;
ctx.rotate(rotation);
ctx.fillText(charArr[index], x, y);
ctx.rotate(-rotation);
}
for (let i = 0; i < 15; i++) {
ctx.strokeStyle = getRandomColor();
ctx.beginPath();
ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
ctx.stroke();
}
for (let i = 0; i < 30; i++) {
ctx.strokeStyle = getRandomColor();
ctx.beginPath();
let x = Math.random() * canvas.width;
let y = Math.random() * canvas.height;
ctx.moveTo(x, y);
ctx.arc(x, y, 1, 0, 2*Math.PI);
ctx.fillstyle = getRandomColor();
ctx.fill();
}
}
- 最后,可以使用函数 getCode 获得图形验证码:
function getCode() {
setCanvasSize(80, 40);
drawCode();
let code = "";
for (let i = 0; i < codeLen; i++) {
code += charArr[Math.floor(Math.random() * 36)];
}
return code;
}
没有回复内容