字符集擴展為 0-9 + a-z(或含大寫),隨機索引範圍變為 36(或 62)。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>字母數字驗證碼</title>
<style>
.captcha { font-family:Arial; font-style:italic; font-weight:bold; color:#c00; letter-spacing:3px; border:1px solid #ccc; padding:2px 8px; background:#f9f9f9; cursor:pointer; user-select:none; }
</style>
</head>
<body onload="generateCaptcha()">
<input type="text" id="input1" placeholder="輸入驗證碼" />
<input type="text" id="checkCode" class="captcha" readonly onclick="generateCaptcha()" title="點擊刷新" />
<br><br>
<button onclick="validate()">提交驗證</button>
<script>
var code = '';
function generateCaptcha(len = 4) {
// 字符集:數字 + 小寫字母(可加大寫)
var chars = '0123456789abcdefghijklmnopqrstuvwxyz'; // 36字符
// var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; // 62字符
code = '';
for (var i = 0; i < len; i++) {
code += chars[Math.floor(Math.random() * chars.length)];
}
document.getElementById('checkCode').value = code;
}
function validate() {
var input = document.getElementById('input1').value.trim().toLowerCase(); // 不區分大小寫
if (!input) { alert('請輸入驗證碼!'); return; }
if (input !== code.toLowerCase()) {
alert('驗證碼錯誤!');
generateCaptcha();
} else {
alert('驗證成功!');
}
}
</script>
</body>
</html>
// 移除 0/O, 1/l/I, 8/B, 5/S, 2/Z 等
var safeChars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz'; // 56字符
function drawCaptcha(canvas, code) {
var ctx = canvas.getContext('2d');
var w = canvas.width, h = canvas.height;
ctx.fillStyle = '#fff'; ctx.fillRect(0,0,w,h);
// 背景噪點
for (var i=0; i<100; i++) {
ctx.fillStyle = 'rgba(0,0,0,' + Math.random()*0.1 + ')';
ctx.fillRect(Math.random()*w, Math.random()*h, 1, 1);
}
// 干擾線
for (var i=0; i<3; i++) {
ctx.beginPath();
ctx.moveTo(0, Math.random()*h);
ctx.lineTo(w, Math.random()*h);
ctx.strokeStyle = 'rgba(0,0,0,0.1)';
ctx.stroke();
}
// 文字逐個繪製(旋縮平移)
ctx.font = 'bold 28px Arial';
ctx.textBaseline = 'middle';
code.split('').forEach(function(ch, i) {
ctx.save();
ctx.translate(30 + i*35, h/2);
ctx.rotate((Math.random()-0.5)*0.4);
ctx.scale(1, 0.8 + Math.random()*0.4);
ctx.fillStyle = 'hsl(' + Math.random()*360 + ', 70%, 40%)';
ctx.fillText(ch, 0, 0);
ctx.restore();
});
}