js实现图片验证码
实现图片验证码的步骤
生成随机验证码文本
使用Math.random()和字符串拼接生成随机字符组合,通常包含数字和字母:
function generateRandomCode(length = 4) {
const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
let result = '';
for (let i = 0; i < length; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
}
return result;
}
创建Canvas绘制验证码
利用HTML5 Canvas API绘制带有干扰元素的验证码图片:
function createCaptcha() {
const canvas = document.getElementById('captchaCanvas');
const ctx = canvas.getContext('2d');
const code = generateRandomCode();
// 清除画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制背景色
ctx.fillStyle = '#f5f5f5';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 绘制验证码文本
ctx.font = '30px Arial';
ctx.fillStyle = '#333';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(code, canvas.width/2, canvas.height/2);
// 添加干扰线
for (let i = 0; i < 5; 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();
}
// 添加干扰点
for (let i = 0; i < 50; i++) {
ctx.fillStyle = getRandomColor();
ctx.beginPath();
ctx.arc(
Math.random() * canvas.width,
Math.random() * canvas.height,
1,
0,
2 * Math.PI
);
ctx.fill();
}
return code;
}
function getRandomColor() {
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
return `rgb(${r},${g},${b})`;
}
HTML结构示例
需要准备Canvas元素和刷新按钮:
<canvas id="captchaCanvas" width="150" height="50"></canvas>
<button id="refreshCaptcha">刷新验证码</button>
<input type="text" id="userInput" placeholder="输入验证码">
<button id="verifyBtn">验证</button>
初始化与验证逻辑
页面加载时初始化验证码,并设置事件监听:
let currentCode = '';
document.addEventListener('DOMContentLoaded', () => {
currentCode = createCaptcha();
document.getElementById('refreshCaptcha').addEventListener('click', () => {
currentCode = createCaptcha();
});
document.getElementById('verifyBtn').addEventListener('click', () => {
const userInput = document.getElementById('userInput').value;
if (userInput.toUpperCase() === currentCode) {
alert('验证成功');
} else {
alert('验证失败');
currentCode = createCaptcha();
}
});
});
进阶优化方向
增加字母大小写转换处理,在验证时统一转为大写或小写比较
// 修改验证逻辑
if (userInput.toUpperCase() === currentCode.toUpperCase()) {
// 验证通过
}
添加验证码过期时间,通过localStorage或服务端记录生成时间
// 存储生成时间
localStorage.setItem('captchaTime', Date.now());
// 验证时检查是否过期(如5分钟)
const generateTime = localStorage.getItem('captchaTime');
if (Date.now() - generateTime > 300000) {
alert('验证码已过期');
}
安全注意事项
前端验证仅作为用户体验优化,重要操作必须结合服务端验证 避免直接将验证码文本返回前端,建议通过加密token或会话存储 对于高安全性场景,建议使用专业验证码服务如reCAPTCHA







