<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>验证码</title>
<script>
let currentCaptcha = '';
function generateCaptcha() {
const canvas = document.getElementById('captcha');
const context = canvas.getContext('2d');
context.font = '20px Arial';
context.clearRect(0, 0, canvas.width, canvas.height);
currentCaptcha = Math.random().toString(36).substring(2, 8);
context.fillText(currentCaptcha, 10, 30);
}
function verifyCaptcha() {
try {
const input = document.getElementById('captcha-input').value;
if (input && input.trim().toLowerCase() === currentCaptcha.toLowerCase()) {
alert('验证码正确');
console.info(input);
document.getElementById('captcha-input').value = '';
} else if (!input) {
alert('请输入验证码!');
} else {
alert('验证码错误');
document.getElementById('captcha-input').value = '';
generateCaptcha();
}
} catch (error) {
console.error('验证验证码时出现错误:', error);
}
}
document.addEventListener('keydown', function (event) {
if (event.key === 'Enter') {
verifyCaptcha();
}
});
// 初始化生成验证码
generateCaptcha();
</script>
</head>
<body>
<div class="captcha-container">
<canvas id="captcha" width="100" height="40"></canvas><br>
<input type="text" id="captcha-input" class="captcha-input" placeholder="输入验证码" style="width: 100px;">
<button onclick="verifyCaptcha()" class="captcha-button">验证</button>
<button onclick="generateCaptcha()" class="captcha-button">看不清?换一张</button><br>
</div>
</body>
</html>
标签:Web,canvas,入门,currentCaptcha,验证码,context,input,document
From: https://www.cnblogs.com/ss1010/p/18442382