js_登录验证码绘制
# 绘制代码
export const drawVerificaCode = (canvas, codeStr) => {
// 随机颜色
function randomColor() {
let r = Math.floor(Math.random() * 256)
let g = Math.floor(Math.random() * 256)
let b = Math.floor(Math.random() * 256)
return `rgb(${r},${g},${b})`
}
// 获取canvas
let ctx = canvas.getContext("2d")
// 获取画布的宽高
let canvas_width = canvas.clientWidth || canvas.offsetWidth;
let canvas_height = canvas.clientHeight || canvas.offsetHeight;
// 清空之前绘制的内容
// 0,0清空的起始坐标
// 矩形的宽高
ctx.clearRect(0, 0, canvas_width, canvas_height)
// 开始绘制
// let scode = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,1,2,3,4,5,6,7,8,9,"
let arrCode = codeStr.split("");
// console.log(arrCode);
// let arrLength = arrCode.length
for (let i = 0; i < codeStr.length; i++) {
// let index = Math.floor(Math.random() * arrCode.length)
let txt = arrCode[i]//随机一个字符
// showNum[i] = txt.toLowerCase()//转化为小写存入验证码数组
// 开始控制字符的绘制位置
let x = 10 + 16 * i //每一个验证码绘制的起始点x坐标
let y = 20 + Math.random() * 8// 起始点y坐标
ctx.font = "bold 20px 微软雅黑"
// 开始旋转字符
let deg = Math.random * -0.5
// canvas 要实现绘制内容具有倾斜的效果,必须先平移,目的是把旋转点移动到绘制内容的地方
ctx.translate(x, y)
ctx.rotate(deg)
// 设置绘制的随机颜色
ctx.fillStyle = randomColor()
ctx.fillText(txt, 0, 0)
// 把canvas复原
ctx.rotate(-deg)
ctx.translate(-x, -y)
}
for (let i = 0; i < 30; i++) {
if (i < 5) {
// 绘制线
ctx.strokeStyle = randomColor()
ctx.beginPath()
ctx.moveTo(Math.random() * canvas_width, Math.random() * canvas_height)
ctx.lineTo(Math.random() * canvas_width, Math.random() * canvas_height)
ctx.stroke()
}
// 绘制点
ctx.strokeStyle = randomColor()
ctx.beginPath()
let x = Math.random() * canvas_width
let y = Math.random() * canvas_height
ctx.moveTo(x, y)
ctx.lineTo(x + 1, y + 1)
ctx.stroke()
}
}
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
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
# 组件中引用
<template>
<canvas ref="canvasRef" width="110" height="40"></canvas>
</template>
<script>
import { drawVerificaCode } from "@/utils";
export default {
mounted() {
// 获取验证码
this.getCodeStr()
},
methods: {
getCodeStr() {
this.$request.get("/getCode").then((res) => {
if (res.data.code == 0) {
drawVerificaCode(this.$refs.canvasRef, res.data.data);
}
})
}
}
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
上次更新: 2024/02/20, 17:31:36