js实现汉字验证码
实现汉字验证码的步骤
生成随机汉字
使用Unicode编码范围生成随机汉字,汉字的Unicode范围大致在\u4e00到\u9fa5之间。
function getRandomChinese() {
const unicode = 0x4e00 + Math.floor(Math.random() * (0x9fa5 - 0x4e00 + 1));
return String.fromCharCode(unicode);
}
创建验证码字符串
调用上述函数生成指定长度的汉字字符串。
function createCaptcha(length = 4) {
let captcha = '';
for (let i = 0; i < length; i++) {
captcha += getRandomChinese();
}
return captcha;
}
渲染验证码到Canvas
使用Canvas绘制验证码,可以添加干扰线、噪点等增强安全性。
function drawCaptcha(canvasId, captcha) {
const canvas = document.getElementById(canvasId);
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 设置背景色
ctx.fillStyle = '#f5f5f5';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 绘制文字
ctx.font = '40px Arial';
ctx.fillStyle = '#333';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(captcha, canvas.width / 2, canvas.height / 2);
// 添加干扰线
for (let i = 0; i < 5; i++) {
ctx.strokeStyle = `rgb(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255})`;
ctx.beginPath();
ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
ctx.stroke();
}
}
验证用户输入
比较用户输入的字符串与生成的验证码是否一致,忽略大小写和前后空格。
function validateCaptcha(input, captcha) {
return input.trim() === captcha;
}
完整示例
整合上述代码,实现一个完整的汉字验证码功能。
<!DOCTYPE html>
<html>
<head>
<title>汉字验证码</title>
</head>
<body>
<canvas id="captchaCanvas" width="200" height="80"></canvas>
<button id="refreshBtn">刷新</button>
<input type="text" id="userInput" placeholder="输入验证码">
<button id="submitBtn">验证</button>
<p id="result"></p>
<script>
let currentCaptcha = createCaptcha();
document.addEventListener('DOMContentLoaded', () => {
drawCaptcha('captchaCanvas', currentCaptcha);
document.getElementById('refreshBtn').addEventListener('click', () => {
currentCaptcha = createCaptcha();
drawCaptcha('captchaCanvas', currentCaptcha);
});
document.getElementById('submitBtn').addEventListener('click', () => {
const userInput = document.getElementById('userInput').value;
const isValid = validateCaptcha(userInput, currentCaptcha);
document.getElementById('result').textContent = isValid ? '验证通过' : '验证失败';
});
});
</script>
</body>
</html>
增强安全性
为提高安全性,可以在服务端生成和验证验证码,避免前端被绕过。同时可以增加以下措施:
- 限制验证码有效时间
- 记录验证码尝试次数,防止暴力破解
- 使用更复杂的干扰元素,如扭曲文字、背景噪点等
通过以上方法可以实现一个基本的汉字验证码功能,适用于网页防机器人提交等场景。







