用原生Js实现简单验证码功能

首先定义一个用来显示验证码的 canvas

<canvas width="95" height="30"></canvas>

生成JS的业务逻辑

// 获取canvas
let canvas = document.querySelector("canvas")
let context = canvas.getContext("2d");
    
// 定义初始化验证码内容
let nums = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", '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', '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'];
 
drawCode()
 
// 绘制验证码
function drawCode() {
    context.beginPath()
 
    / 绘制背景色 /
    context.fillStyle = "cornflowerblue";
    context.fillRect(0, 0, canvas.width, canvas.height)
 
    / 绘制验证码 /
    context.fillStyle = "white";
    context.font = "25px Arial";
 
    let rand = [], x = [], y = []
    for (let i = 0; i < 5; i++) {
        rand[i] = nums[Math.floor(Math.random() * nums.length)]
        x[i] = i * 16 + 10;
        y[i] = Math.random() * 20 + 20;
        context.fillText(rand[i], x[i], y[i]);
    }
    
    / rand就是生成后的结果, 后面用来判断验证码输入框是否与该值相等 /
    console.log(rand);
 
    //画3条随机线
    for (let i = 0; i < 3; i++) {
        drawline(canvas, context);
    }
 
    // 画30个随机点
    for (let i = 0; i < 30; i++) {
        drawDot(canvas, context);
    }
}
 
// 随机线
function drawline(canvas, context) {
    //随机线的起点x坐标是画布x坐标0位置,y坐标是画布高度的随机数
    context.moveTo(Math.floor(Math.random()  canvas.width), Math.floor(Math.random()  canvas.height)); 
    //随机线的终点x坐标是画布宽度,y坐标是画布高度的随机数
    context.lineTo(Math.floor(Math.random()  canvas.width), Math.floor(Math.random()  canvas.height));
    context.lineWidth = 0.5;
    context.strokeStyle = 'rgba(50,50,50,0.3)';
    context.stroke();   
}
 
// 随机点
function drawDot(canvas, context) {
    let px = Math.floor(Math.random() * canvas.width);
    let py = Math.floor(Math.random() * canvas.height);
    context.moveTo(px, py);
    context.lineTo(px + 1, py + 1);
    context.lineWidth = 0.2;
    context.stroke();
}

完成,上音乐

打赏