封装可复用的JavaScript验证码生成类

作者:夜航船

时间:2026-12-01

浏览:361

直接实例化 CaptchaGenerator 类,调用 generate() 方法即可获取验证码图片的 Base64 字符串和对应的文本值。

文章目录

封装可复用的JavaScript验证码生成类

验证码生成原理与核心组件

验证码的核心在于随机字符的选择、画布的绘制以及干扰元素的添加。我们将使用 HTML5 Canvas API 来实现这一过程,确保生成的图像清晰且难以被简单的 OCR 识别。

封装可复用的JavaScript验证码生成类

先定义一个配置对象,包含字符集、字体大小、背景颜色等参数。接着,创建一个随机的颜色生成函数,用于绘制文字和干扰线。通过循环遍历选定的字符,将其绘制到画布上,并叠加随机位置的噪点和线条。

完整实现代码与运行方式

将以下代码保存为 captcha.js,在 Node.js 环境中运行即可看到生成的 Base64 数据和控制台输出。

封装可复用的JavaScript验证码生成类

const { createCanvas } = require('canvas');

// 配置项
const config = {
  width: 120,
  height: 40,
  length: 4,
  fontSize: 24,
  colors: ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7']
};

class CaptchaGenerator {
  constructor(cfg) {
    this.cfg = { ...config, ...cfg };
    this.canvas = createCanvas(this.cfg.width, this.cfg.height);
    this.ctx = this.canvas.getContext('2d');
    this.chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789'; // 去除易混淆字符
  }

  randomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }

  randomColor() {
    return this.colors[this.randomInt(0, this.colors.length - 1)];
  }

  generate() {
    const ctx = this.ctx;
    const cfg = this.cfg;

    // 清空画布并设置背景
    ctx.fillStyle = '#F5F5F5';
    ctx.fillRect(0, 0, cfg.width, cfg.height);

    let code = '';

    // 绘制干扰点
    for (let i = 0; i < 30; i++) {
      ctx.fillStyle = this.randomColor();
      ctx.beginPath();
      ctx.arc(this.randomInt(0, cfg.width), this.randomInt(0, cfg.height), 1, 0, 2 * Math.PI);
      ctx.fill();
    }

    // 绘制干扰线
    for (let i = 0; i < 3; i++) {
      ctx.strokeStyle = this.randomColor();
      ctx.beginPath();
      ctx.moveTo(this.randomInt(0, cfg.width), this.randomInt(0, cfg.height));
      ctx.lineTo(this.randomInt(0, cfg.width), this.randomInt(0, cfg.height));
      ctx.stroke();
    }

    // 绘制字符
    for (let i = 0; i < cfg.length; i++) {
      const char = this.chars[this.randomInt(0, this.chars.length - 1)];
      code += char;
      
      ctx.font = `${this.randomInt(cfg.fontSize - 4, cfg.fontSize + 4)}px Arial`;
      ctx.fillStyle = this.randomColor();
      ctx.save();
      
      // 变换坐标系以旋转字符
      const x = 15 + i * 25;
      const y = 25;
      const angle = (Math.random() - 0.5) * 0.4;
      ctx.translate(x, y);
      ctx.rotate(angle);
      ctx.fillText(char, 0, 0);
      ctx.restore();
    }

    return {
      text: code,
      image: this.canvas.toDataURL('image/png')
    };
  }
}

// 执行生成
const generator = new CaptchaGenerator();
const result = generator.generate();
console.log('验证码文本:', result.text);
console.log('Base64 图片:', result.image);

运行成功后,控制台第一行显示生成的四位随机码,第二行输出完整的 Base64 编码字符串。若需验证,可将 Base64 部分复制到在线解码工具中查看图片。修改 config 中的 length 可改变字符数量,调整 fontSize 影响视觉大小。

该脚本模拟了浏览器端的 Canvas 环境,因此需要安装 canvas 模块。运行后,控制台会打印出验证码文本和图片路径,开发者可直接复制 Base64 字符串用于前端展示或测试。

处理特殊字符与抗干扰优化

当字符集中包含易混淆字符(如 '0' 和 'O')时,需调整绘制逻辑以增强可读性。

通过在绘制前对字符进行简单的旋转或位移,可以有效区分相似字形。同时,增加干扰线的密度和随机角度,能进一步提升安全性。本节沿用同一程序,重点观察修改字符集后的输出变化。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章