图形验证码

10/23/2021 Javascript

# 需求

验证码功能,来辅助进行验证,提高安全性。随机生成验证码,每个验证码的颜色不一样。

# 实现

用 canvas 画布并渲染出验证码图形,并且得到随机的颜色值。

<canvas id="myCanvas"></canvas>
1
// 随机颜色
const randomColor = () => {
    const colorValue = '0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f'
    const colorArray = colorValue.split(',')
    let color = '#'
    for (let i = 0; i < 6; i++) {
        color += colorArray[Math.floor(Math.random() * 16)]
    }
    return color
}
// 生成随机验证码
const createCode = () => {
    let code = ''
    const codeLength = 4 // 验证码的长度,可变
    const canvas = document.getElementById('myCanvas') as HTMLCanvasElement // 获取画布

    const selectChar = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')

    const ctx = canvas.getContext('2d')

    if (canvas !== null && ctx) {
        ctx.fillRect(0, 0, 70, 35)
        ctx.clearRect(0, 0, canvas.width, canvas.height)
        ctx.fillStyle = '#FFFFFF'
        ctx.font = '80px arial'
        const obj = {
            0: 30,
            1: 90,
            2: 150,
            3: 210,
        }
        for (let i = 0; i < codeLength; i++) {
            const charIndex = Math.floor(Math.random() * 36)
            code += selectChar[charIndex]
            ctx.fillStyle = randomColor()
            ctx.fillText(selectChar[charIndex], obj[String(i)], 100)
        }
    }
    // 赋值给全局变量,用来和用户输入的进行校验
    this.verifyCode = code
}
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

# 效果展示

效果图

上次更新: 10/25/2021, 6:37:07 PM