原生JS实现一个验证码功能

HaoOuBa
2021-02-20 / 6 评论 / 661 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2021年02月20日,已超过1252天没有更新,若内容或图片失效,请留言反馈。

定义一个用于显示验证码的canvas

<canvas width="100" height="40"></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();
}
6

评论 (6)

取消
  1. 头像
    rsgrd
    Windows 10 · Google Chrome

    fgffdgd

    回复
  2. 头像
    你婆婆
    Android · Google Chrome

    hxjdjsjjs

    回复
  3. 头像
    213
    Windows 10 · Google Chrome

    画图

    回复
    1. 头像
      ss
      Windows 10 · Google Chrome
      @ 213

      画图

      回复
  4. 头像
    帅哥
    Windows 10 · Google Chrome

    Joe主题怎么没用上呢

    回复
  5. 头像
    2broear
    Windows 10 · Google Chrome

    nb

    回复