如何使用 JavaScript 实现一个简单的图形验证码系统? - 项越资源网-html css js 用法分享社区-开发交流-项越资源网

如何使用 JavaScript 实现一个简单的图形验证码系统?

实现图形验证码的步骤

  1. 首先,需要创建一个 canvas 画布:
const canvas = document.createElement("canvas");
  1. 然后,可以使用函数 setCanvasSize 设置 canvas 画布的宽度和高度:
function setCanvasSize(width, height) {
    canvas.width = width;
    canvas.height = height;
}
  1. 接着,可以使用函数 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);
    }
    //产生15条干扰线
    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();
    }
    //产生30个干扰点
    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();
    }
}
  1. 最后,可以使用函数 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;
}
请登录后发表评论

    没有回复内容