JavaScript验证码图的制作通常涉及到HTML5的Canvas绘图API。以下是创建一个简单验证码图的步骤:
验证码(CAPTCHA)是一种用于验证用户是否为自动程序(机器人)的技术。它通常包含一组随机生成的字符或图像,要求用户输入他们看到的内容,以此来区分人类和自动化程序。
<canvas>
元素。以下是一个简单的JavaScript验证码生成示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>验证码示例</title>
<style>
canvas {
border: 1px solid #000;
}
</style>
</head>
<body>
<canvas id="captchaCanvas" width="120" height="40"></canvas>
<input type="text" id="captchaInput" placeholder="请输入验证码">
<button onclick="validateCaptcha()">验证</button>
<script>
function generateCaptcha() {
const canvas = document.getElementById('captchaCanvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 生成随机字符
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let captcha = '';
for (let i = 0; i < 5; i++) {
captcha += chars.charAt(Math.floor(Math.random() * chars.length));
}
// 绘制验证码
ctx.font = 'bold 24px Arial';
ctx.fillStyle = '#333';
ctx.fillText(captcha, 10, 30);
// 添加干扰
for (let i = 0; i < 10; 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 captcha;
}
function validateCaptcha() {
const userInput = document.getElementById('captchaInput').value;
const captcha = generateCaptcha(); // 这里应该保存验证码值,用于比对
if (userInput === captcha) {
alert('验证成功!');
} else {
alert('验证失败,请重试!');
generateCaptcha(); // 刷新验证码
}
}
// 初始化验证码
generateCaptcha();
</script>
</body>
</html>
这个示例代码仅用于演示目的,实际应用中需要考虑更多的安全性和用户体验因素。
领取专属 10元无门槛券
手把手带您无忧上云