<!DOCTYPE html>
<html>
<head>
<title>图形验证码示例</title>
<style>
body {
font-family: Arial, sans-serif;
}
canvas {
border: 1px solid #ccc;
}
</style>
</head>
<body>
<h1>图形验证码示例</h1>
<canvas id="captchaCanvas" width="120" height="40"></canvas>
<script>
// 生成随机的四位验证码
function generateCaptcha() {
let captcha = '';
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (let i = 0; i < 4; i++) {
captcha += characters.charAt(Math.floor(Math.random() * characters.length));
}
return captcha;
}
// 创建图形验证码
function createCaptcha() {
const canvas = document.getElementById('captchaCanvas');
const context = canvas.getContext('2d');
const captcha = generateCaptcha();
// 设置画布样式
context.fillStyle = '#f5f5f5';
context.fillRect(0, 0, canvas.width, canvas.height);
context.font = 'bold 24px Arial';
context.fillStyle = '#333';
context.textAlign = 'center';
context.textBaseline = 'middle';
// 绘制验证码文本
context.fillText(captcha, canvas.width / 2, canvas.height / 2);
// 绘制干扰线
for (let i = 0; i < 6; i++) {
context.strokeStyle = getRandomColor();
context.beginPath();
context.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
context.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
context.stroke();
}
// 返回生成的验证码
return captcha;
}
// 获取随机颜色
function getRandomColor() {
const letters = '0123456789ABCDEF';
let color = '#';
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
// 生成并显示验证码
const captcha = createCaptcha();
console.log('验证码:', captcha);
</script>
</body>
</html>
开箱即用