前言
效果展示(代码下面自取)
正文
HTML:创建一个120*40的canvas画布,为其绑定一个点击事件,点击后触发回调函数draw
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<canvas id="canvas" width="120" height="40" onclick="draw()"></canvas>
</body>
</html>
最重要的部分就是js部分啦,接下来让我们开始js:
- 定义一个变量pool,用于表示生成验证码内容的范围为0-9和A-Z
let pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
- 定义一个函数
randomNum,用于生成给定区间上的随机数
function randomNum(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
- 定义一个函数
randomColor,用于随机生成验证码内容的颜色
function randomColor(min, max) {
const r = randomNum(min, max);
const g = randomNum(min, max);
const b = randomNum(min, max);
return `rgb(${r}, ${g}, ${b})`;
}
函数draw:
- 对画布进行随机填充颜色
let canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
// 填充色 随机
ctx.fillStyle = randomColor(100, 230);
ctx.fillRect(0, 0, canvas.width, canvas.height);
- 定义随机生成的字符串变量为
imgCode,通过for循环调用四次randomNum(范围为0-pool.length)生成四次随机数,然后取到pool对应下标的元素,同时调用四次randomNum用于实现字符串的随机大小fontSize,就可以实现随机生成字符串
// 随机生成字符串
let imgCode = '';
for (let i = 0;i < 4; i++) {
const text = pool[randomNum(0, pool.length)];
imgCode += text;
const fontSize = randomNum(18, 40);
const deg = randomNum(-30, 30);
ctx.font = `${fontSize}px Simhei`;
ctx.textBaseline = 'top';
ctx.fillStyle = randomColor(80, 150);
ctx.save(); // 将当前状态封存入栈
ctx.translate(30 * i + 15, 15);
ctx.rotate(deg * Math.PI / 180);
ctx.fillText(text, -10, -15);
ctx.restore(); // 恢复
}
- 随机生成干扰线条(生成了40条),通过for循环调用
randomNum生成范围为(0, canvas.width)和(0, canvas.height)的两个随机数,分别为画线条起点和终点的(x,y),再调用randomColor生成线条的随机颜色
// 随机生成干扰线条
for (let i = 0;i < 5; i++) {
ctx.beginPath();
ctx.moveTo(randomNum(0, canvas.width), randomNum(0, canvas.height));
ctx.lineTo(randomNum(0, canvas.width), randomNum(0, canvas.height));
ctx.strokeStyle = randomColor(100, 230);
ctx.closePath();
ctx.stroke();
}
- 生成随机小点(生成了40个),通过for循环调用
randomNum画随机大小的圆,同时调用randomColor生成随机颜色的圆
// 随机小点
for (let i = 0;i < 40; i++) {
ctx.beginPath();
ctx.arc(randomNum(0, canvas.width), randomNum(0, canvas.height), 1, 0, 2*Math.PI);
ctx.fillStyle = randomColor(150, 200);
ctx.closePath();
ctx.fill();
}
最后调用函数draw
draw();
结语
随机生成的验证码是不是很有趣呢~快去试试