JS基于Canvas绘制数字字母验证码完整代码

作者:微光时间:2026-12-01浏览:225

使用 Canvas 绘制随机字符与干扰元素,结合 CSS 定位与 JS 事件监听实现点击刷新功能。

JS基于Canvas绘制数字字母验证码完整代码

验证码生成原理与结构

核心逻辑是创建画布后,通过循环生成随机坐标、颜色和字符,并叠加线条或噪点以增强识别难度。

JS基于Canvas绘制数字字母验证码完整代码

验证码通常包含背景色、随机文本和干扰项。文本部分需从指定字符集中抽取,确保每次加载内容不同。干扰元素如直线或散点,能有效防止简单 OCR 识别。结构上,画布尺寸需适配显示区域,避免拉伸变形。

完整实现代码与运行方式

将以下代码保存为 .html 文件,直接在浏览器中打开即可看到可交互的验证码效果。

JS基于Canvas绘制数字字母验证码完整代码

<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>Canvas 验证码</title>
<style>
  body { display: flex; justify-content: center; align-items: center; height: 100vh; background: #f0f2f5; }
  .captcha-box { text-align: center; }
  canvas { cursor: pointer; border: 1px solid #ccc; border-radius: 4px; }
  p { color: #666; margin-top: 10px; font-size: 14px; }
</style>
</head>
<body>
<div class="captcha-box">
  <canvas id="captcha" width="120" height="40"></canvas>
  <p>点击验证码刷新</p>
</div>
<script>
const canvas = document.getElementById('captcha');
const ctx = canvas.getContext('2d');
const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';

function randomColor(min, max) {
  return `rgb(${Math.floor(Math.random() * (max - min)) + min}, ${Math.floor(Math.random() * (max - min)) + min}, ${Math.floor(Math.random() * (max - min)) + min})`;
}

function drawCaptcha() {
  // 清空画布
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  
  // 绘制背景
  ctx.fillStyle = randomColor(200, 240);
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  
  // 绘制干扰线
  for (let i = 0; i < 3; i++) {
    ctx.strokeStyle = randomColor(100, 200);
    ctx.beginPath();
    ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
    ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
    ctx.stroke();
  }
  
  // 绘制文字
  const code = [];
  for (let i = 0; i < 4; i++) {
    const char = chars[Math.floor(Math.random() * chars.length)];
    code.push(char);
    ctx.font = `${Math.random() * 10 + 20}px Arial`;
    ctx.fillStyle = randomColor(50, 160);
    ctx.fillText(char, 20 + i * 25, 25 + Math.random() * 10);
  }
  
  // 可选:打印验证码到控制台用于测试
  console.log('Current Captcha:', code.join(''));
}

canvas.addEventListener('click', drawCaptcha);

// 初始绘制
drawCaptcha();
</script>
</body>
</html>

程序运行后显示一个 120x40 像素的画布,内含四个随机大写字母或数字。点击画布任意位置,背景、线条和文字均会重新随机生成。控制台会输出当前显示的验证码字符串,便于调试比对。输入变化主要为点击次数,每次点击触发一次完整的重绘流程,包括背景填充、干扰线绘制和字符渲染。

代码包含 HTML 结构、CSS 样式及 JavaScript 逻辑。点击画布会触发重绘函数,实现刷新功能。所有资源均为原生 API,无需外部库。

点击刷新机制与状态重置

点击事件绑定在画布上,调用重绘函数前无需额外清理,因为每次绘制都会覆盖旧内容。

实际开发中,若需保留验证码值供表单提交,可将生成的字符串存入隐藏域或变量。当前示例仅展示视觉呈现,未涉及后端验证逻辑。开发者可根据需求扩展字符集或调整干扰密度。

作者最新文章
相关文章
更多