当你想在Angular中使用Canvas时,你可以做的是在组件内部创建一个,然后从该组件的生命周期钩子和事件处理程序中进行绘制。

1、引入canvas

首先需要引入一个canvas元素,我们可以在组件的模板中进行操作。我们还将一个引用变量附加到元素,以便我们能够从组件类中引用它:

login.component.html
  • html
1
<canvas #checkCode width="80" height="35" class="checkCode" (click)="clickChange()">

2、在组件类中获取canvas

在组件类中,我们可以使用@ViewChild()装饰器向画布注入引用。组件初始化后,我们就可以访问Canvas DOM节点以及其绘图上下文:

login.component.ts
  • ts
1
2
3
4
export class LoginComponent implements OnInit {
@ViewChild('checkCode') canvasRef: ElementRef;
public code: any; // 验证码
}

3、在生命钩子函数中绘制图形

login.component.ts
  • ts
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
ngOnInit() {
this.clickChange();
}

// 创建随机码
public createCode() {
this.code = '';
const codeLength = 4; // 验证码的长度
const random = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
'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']; // 所有候选组成验证码的字符,当然也可以用中文的
for (let i = 0; i < codeLength; i++) { // 循环操作
const index = Math.floor(Math.random() * 52); // 取得随机数的索引(0~51)
this.code += random[index]; // 根据索引取得随机数加到code上
}
return this.code;
}

/*干扰线的随机x坐标值*/
public lineX() {
const ranLineX = Math.floor(Math.random() * 80);
return ranLineX;
}

/*干扰线的随机y坐标值*/
public lineY() {
const ranLineY = Math.floor(Math.random() * 35);
return ranLineY;
}

// 生成随机颜色
public rgb() {
// 因为在angular4里面不能使用arguments,所以换了一种方法。
return '#' + Math.floor(Math.random() * 16777215).toString(16);
}

public clickChange() {
// * 注意:这里跟js不一样!!!
const cxt: CanvasRenderingContext2D = this.canvasRef.nativeElement.getContext('2d');
cxt.fillStyle = '#fff';
cxt.fillRect(0, 0, 80, 35);

/*生成干扰线20条*/
for (let j = 0; j < 20; j++) {
cxt.strokeStyle = this.rgb();
cxt.beginPath(); // 若省略beginPath,则每点击一次验证码会累积干扰线的条数
cxt.moveTo(this.lineX(), this.lineY());
cxt.lineTo(this.lineX(), this.lineY());
cxt.lineWidth = 0.5;
cxt.closePath();
cxt.stroke();
}

cxt.fillStyle = '#6271a9';
cxt.font = 'bold 20px Arial';
cxt.fillText(this.createCode(), 15, 25); // 把rand()生成的随机数文本填充到canvas中
}