JS生成验证码图片

关键步骤

  • 加上干扰点

    1
    2
    3
    4
    for (let i = 0.05 * w * h; i > 0; i--) {
    ctx.fillStyle = randomColor(0, 256);
    ctx.fillRect(randomInt(0, w), randomInt(0, h), 1, 1);
    }
  • 显示数字

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    ctx.font = `${h - 4}px Consolas`;
    ctx.fillStyle = randomColor(160, 200);
    let value = "";
    for (let i = 0; i < n; i++) {
    let x = (w - 10) / n * i + 5,
    y = h - 12;
    let r = Math.PI * randomFloat(-0.12, 0.12);
    let ch = CHARTS[randomInt(0, CHARTS.length)];
    value += ch;
    ctx.translate(x, y);
    ctx.rotate(r);
    ctx.fillText(ch, 0, 0);
    ctx.rotate(-r);
    ctx.translate(-x, -y);
    }
  • 获取验证码图片base64值

    1
    canvas.toDataURL('image/jpg')

完整实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<!DOCTYPE html>
<html>

<head>
<title></title>
</head>

<body>
<img id="img">
<script type="text/javascript">
function getCaptcha(w, h, n) {
const CHARTS = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ".split("");
const randomInt = (s, e) => {
if (s > e) {
let t = s;
s = e;
e = t;
}
s = Math.ceil(s);
e = Math.floor(e);
return s + Math.floor(Math.random() * (e - s))
}
const randomFloat = (s, e) => {
return s + Math.random() * (e - s);
}
const randomColor = (s, e) => {
return `rgb(${randomInt(s,e)},${randomInt(s,e)},${randomInt(s,e)})`;
}

let canvas = document.createElement('canvas');
let ctx = canvas.getContext('2d');

ctx.rect(0, 0, w, h);
ctx.clip();

ctx.fillStyle = randomColor(200, 250);
ctx.fillRect(0, 0, w, h);

for (let i = 0.05 * w * h; i > 0; i--) {
ctx.fillStyle = randomColor(0, 256);
ctx.fillRect(randomInt(0, w), randomInt(0, h), 1, 1);
}

ctx.font = `${h - 4}px Consolas`;
ctx.fillStyle = randomColor(160, 200);
let value = "";
for (let i = 0; i < n; i++) {
let x = (w - 10) / n * i + 5,
y = h - 12;
let r = Math.PI * randomFloat(-0.12, 0.12);
let ch = CHARTS[randomInt(0, CHARTS.length)];
value += ch;
ctx.translate(x, y);
ctx.rotate(r);
ctx.fillText(ch, 0, 0);
ctx.rotate(-r);
ctx.translate(-x, -y);
}

let base64Src = canvas.toDataURL('image/jpg');
return {
value,
base64Src
};
}
let res = getCaptcha(100, 40, 4);
console.log(res);
document.querySelector("#img").src = res.base64Src;
</script>
</body>

</html>

输出

1
2
3
4
{
base64Src: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASw....",
value: "Z9KF"
}

效果展示

验证码

 欢迎关注我的博客公众号
如果觉得我的文章对你有用,请随意赞赏
0%