闲来无事,就想着写一个玩玩,话不多说,先看效果:





上源码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>前端生成验证码</title>
</head>
<body>
<canvas id="canvas" width="160" height="50"></canvas>
</body>
<script>
const getRandom = (min, max) => {
return Math.floor(Math.random() * (max - min + 1)) + min
}
const getColor = (min, max) => {
let r = getRandom(min, max);
let g = getRandom(min, max);
let b = getRandom(min, max);
return `rgb(${r},${g},${b}`
}
const getVerificationCode = (selector, width, height) => {
let canvas = document.querySelector(selector);
let ctx = canvas.getContext('2d');
ctx.fillStyle = getColor(215, 250);
ctx.fillRect(0, 0, width, height);
let verificationCode = '';
for (let i = 0; i < 5; i++) {
let ascii = getRandom(48, 122);
if ((ascii > 57 && ascii < 65) || (ascii > 90 && ascii < 97)) {
i--;
continue;
}
const c = String.fromCharCode(ascii);
verificationCode += c;
let fontSize = getRandom(height-(height*.4), height-(height*.1));
ctx.font = fontSize + 'px Simhei';
ctx.textBaseline = 'top';
ctx.fillStyle = getColor(80, 150);
ctx.save();
ctx.translate(30 * i + 20, 10);
let deg = getRandom(-30, 30);
ctx.rotate(deg * Math.PI / 180);
ctx.fillText(c, -10, -10);
ctx.restore();
}
for (let j = 0; j < 5; j++) {
ctx.beginPath();
ctx.moveTo(getRandom(0, width), getRandom(0, height));
ctx.lineTo(getRandom(0, width), getRandom(0, height));
ctx.strokeStyle = getColor(180, 230);
ctx.closePath();
ctx.stroke();
}
for (let j = 0; j < 40; j++) {
ctx.beginPath();
ctx.arc(getRandom(0, width), getRandom(0, height), 1, 0, 2 * Math.PI);
ctx.closePath();
ctx.fillStyle = getColor(150, 200);
ctx.fill();
}
return verificationCode;
}
let verificationCode = getVerificationCode('#canvas', 160, 60);
console.log("生成的验证码是:", verificationCode);
</script>
</html>