<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<canvas id="can" style="border: 1px solid red;"></canvas>
<span id="change">看不清,换一张</span>
<input type="text" id="txt" placeholder="不区分大小写">
<button id="btn">验证</button>
<script>
var code = '';
var ctx = can.getContext('2d');
function random(a, b) { // a-b之间的随机整数
return Math.floor(Math.random() * (b - a + 1)) + a;
}
function render() {
ctx.clearRect(0, 0, 300, 150)
// 线
for (let i = 0; i < 100; i++) {
ctx.beginPath();
// 0-255, 0-255, 0-255, 0-1
// random(1, 10) 1-10之间的随机数 random(1, 10) / 10 0.1-1之间的随机数
ctx.strokeStyle = `rgba(${random(0, 255)}, ${random(0, 255)}, ${random(0, 255)}, ${random(1, 10) / 10})`;
ctx.lineWidth = random(1, 3);
ctx.moveTo(random(-100, 400), random(-100, 250));
ctx.lineTo(random(-100, 400), random(-100, 250));
ctx.stroke();
}
// 圆
for (let i = 0; i < 100; i++) {
ctx.beginPath();
ctx.fillStyle = `rgba(${random(0, 255)}, ${random(0, 255)}, ${random(0, 255)}, ${random(1, 10) / 10})`;
ctx.arc(random(0, 300), random(0, 150), random(0, 15), 0, Math.PI * 2);
ctx.fill();
}
// 字
var str = 'qwertyuiopasdfghjklzxcvbnmQERTYUIOPASDFGHJKLZXCVBNM1234567890';
for (let i = 0; i < 4; i++) {
var t = str[random(0, str.length - 1)];
console.log(t);
code += t;
ctx.font = `${random(30, 80)}px 微软雅黑`;
ctx.fillStyle = `rgb(${random(0, 255)}, ${random(0, 255)}, ${random(0, 255)})`;
ctx.fillText(t, 45 * (i + 1), 100, 50);
}
}
render();
change.onclick = render;
btn.onclick = function () {
console.log(txt.value, code);
if (txt.value.toLowerCase() === code.toLowerCase()) {
alert('验证成功');
} else {
alert('验证失败');
}
}
</script>
</body>
</html>
原生js手搓验证码
最新推荐文章于 2024-05-17 13:52:13 发布