在JavaScript中生成验证码通常涉及到创建一个包含随机字符或图像的验证码,并在前端显示给用户,同时将验证码的值存储在会话(session)或本地存储(localStorage/sessionStorage)中,以便后续验证用户输入的验证码是否正确。
以下是一个简单的JavaScript验证码生成示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>验证码生成</title>
</head>
<body>
<img id="captchaImage" src="" alt="验证码">
<button onclick="generateCaptcha()">刷新验证码</button>
<form>
<input type="text" id="captchaInput" placeholder="请输入验证码">
<button type="submit">提交</button>
</form>
<script src="captcha.js"></script>
</body>
</html>
// 生成随机验证码字符串
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;
}
// 创建验证码图像
function createCaptchaImage(text) {
const canvas = document.createElement('canvas');
canvas.width = 120;
canvas.height = 40;
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#f2f2f2';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.font = 'bold 24px Arial';
ctx.fillStyle = '#333';
ctx.fillText(text, 10, 28);
// 添加干扰线
for (let i = 0; i < 5; i++) {
ctx.beginPath();
ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
ctx.strokeStyle = '#ccc';
ctx.stroke();
}
return canvas.toDataURL();
}
// 生成并显示验证码
function generateCaptcha() {
const captchaText = generateRandomString(5);
const captchaImage = createCaptchaImage(captchaText);
document.getElementById('captchaImage').src = captchaImage;
// 将验证码值存储在sessionStorage中
sessionStorage.setItem('captcha', captchaText);
}
// 验证用户输入的验证码
document.querySelector('form').addEventListener('submit', function (event) {
event.preventDefault();
const userInput = document.getElementById('captchaInput').value;
const storedCaptcha = sessionStorage.getItem('captcha');
if (userInput === storedCaptcha) {
alert('验证码正确!');
} else {
alert('验证码错误,请重试!');
generateCaptcha(); // 刷新验证码
}
});
// 初始化显示验证码
generateCaptcha();
generateRandomString
函数用于生成指定长度的随机字符串,作为验证码的文本内容。createCaptchaImage
函数使用HTML5的Canvas API来绘制验证码文本和干扰线,然后将画布内容转换为Data URL,以便在<img>
标签中显示。generateCaptcha
函数调用上述两个函数来生成验证码文本和图像,并将图像显示在页面上。同时,它还将验证码文本存储在sessionStorage
中,以便后续验证。sessionStorage
中的验证码匹配,并给出相应的提示。验证码广泛应用于网站和应用程序的登录、注册、找回密码等需要验证用户身份的场景,以防止恶意自动化攻击。
领取专属 10元无门槛券
手把手带您无忧上云