js实现图片验证码
实现图片验证码的基本思路
图片验证码通常由随机生成的字符或数字组成,经过扭曲、干扰线、噪点等处理后呈现为图像。以下是一个基于JavaScript和Canvas的实现方法:

生成随机字符串
function generateRandomString(length) {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let result = '';
for (let i = 0; i < length; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
}
return result;
}
创建Canvas绘制验证码
function createCaptcha() {
const canvas = document.getElementById('captchaCanvas');
const ctx = canvas.getContext('2d');
const captchaText = generateRandomString(6);
// 清除画布
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';
// 添加文字扭曲效果
for (let i = 0; i < captchaText.length; i++) {
ctx.save();
ctx.translate(30 + i * 20, 30);
ctx.rotate((Math.random() - 0.5) * 0.4);
ctx.fillText(captchaText[i], 0, 0);
ctx.restore();
}
// 添加干扰线
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 < 100; i++) {
ctx.fillStyle = getRandomColor();
ctx.fillRect(
Math.random() * canvas.width,
Math.random() * canvas.height,
1,
1
);
}
return captchaText;
}
function getRandomColor() {
const letters = '0123456789ABCDEF';
let color = '#';
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
HTML结构
<div class="captcha-container">
<canvas id="captchaCanvas" width="200" height="60"></canvas>
<button id="refreshCaptcha">刷新</button>
</div>
<input type="text" id="captchaInput" placeholder="输入验证码">
<button id="verifyCaptcha">验证</button>
验证逻辑
let correctCaptcha = '';
document.addEventListener('DOMContentLoaded', function() {
correctCaptcha = createCaptcha();
document.getElementById('refreshCaptcha').addEventListener('click', function() {
correctCaptcha = createCaptcha();
});
document.getElementById('verifyCaptcha').addEventListener('click', function() {
const userInput = document.getElementById('captchaInput').value;
if (userInput === correctCaptcha) {
alert('验证码正确');
} else {
alert('验证码错误');
correctCaptcha = createCaptcha();
}
});
});
增强安全性措施
在实际应用中,纯前端验证码安全性不足,建议配合后端验证:

- 生成验证码时,将正确值存储在服务器session中
- 用户提交时,将输入值与服务器存储的值比对
- 验证码应设置有效期(通常2-5分钟)
- 限制单位时间内验证尝试次数
替代方案
对于更高安全需求,可以考虑:
- 使用第三方验证码服务(如reCAPTCHA)
- 实现滑动拼图验证码
- 短信/邮箱验证码验证
- 行为分析验证(鼠标移动轨迹等)






