在浏览器端实现生成验证码并验证输入正误,使用 HTML5 Canvas 来实现。以下是一个简单的浏览器端验证码实现示例:
```html
<!DOCTYPE html>
<html>
<head>
<title>Browser Captcha</title>
<style>
.captcha-container {
display: flex;
align-items: center;
gap: 10px;
}
#captchaCanvas {
border: 1px solid #ddd;
cursor: pointer;
}
</style>
</head>
<body>
<div class="captcha-container">
<canvas id="captchaCanvas" width="120" height="40"></canvas>
<button onclick="refreshCaptcha()">刷新</button>
</div>
<input type="text" id="captchaInput" placeholder="请输入验证码">
<button onclick="validateCaptcha()">验证</button>
<script>
let captchaText = '';
// 生成随机字符
function generateCaptchaText(length) {
const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789';
let text = '';
for (let i = 0; i < length; i++) {
text += chars.charAt(Math.floor(Math.random() * chars.length));
}
return text;
}
// 绘制验证码
function drawCaptcha() {
const canvas = document.getElementById('captchaCanvas');
const ctx = canvas.getContext('2d');
// 清空画布
ctx.fillStyle = '#f9f9f9';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 生成新的验证码文本
captchaText = generateCaptchaText(5);
// 绘制文字
ctx.font = 'bold 24px Arial';
ctx.textBaseline = 'middle';
// 随机颜色和位置绘制每个字符
for (let i = 0; i < captchaText.length; i++) {
ctx.fillStyle = `rgb(${Math.random() * 100}, ${Math.random() * 100}, ${Math.random() * 100})`;
ctx.save();
ctx.translate(20 + i * 20, 20);
ctx.rotate((Math.random() - 0.5) * 0.4);
ctx.fillText(captchaText[i], 0, 0);
ctx.restore();
}
// 添加干扰线
for (let i = 0; i < 3; i++) {
ctx.beginPath();
ctx.strokeStyle = `rgba(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255}, 0.5)`;
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 = `rgba(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255}, 0.5)`;
ctx.fillRect(Math.random() * canvas.width, Math.random() * canvas.height, 2, 2);
}
}
// 刷新验证码
function refreshCaptcha() {
drawCaptcha();
}
// 验证输入
function validateCaptcha() {
const input = document.getElementById('captchaInput').value;
if (input.toLowerCase() === captchaText.toLowerCase()) {
alert('验证成功!');
refreshCaptcha();
document.getElementById('captchaInput').value = '';
} else {
alert('验证码错误,请重试!');
refreshCaptcha();
document.getElementById('captchaInput').value = '';
}
}
// 初始化
window.onload = function() {
drawCaptcha();
// 点击画布刷新验证码
document.getElementById('captchaCanvas').onclick = refreshCaptcha;
};
</script>
</body>
</html>