angular中使用canvas画布做验证码

时间:2022-06-26 09:51:33
    //填充画布,五位随机数
drawNumber(): void {
this.clearCanvas(); let ctx: CanvasRenderingContext2D = this.myGraph.nativeElement.getContext("2d"); ctx.shadowBlur = 200;
ctx.shadowColor = "black";
ctx.font = "italic 20px Verdana";
ctx.textAlign = "left"; var gradient = ctx.createLinearGradient(0, 0, this.myGraph.nativeElement.width, 0);
gradient.addColorStop(0, "magenta");
gradient.addColorStop(0.5, "blue");
gradient.addColorStop(1.0, "red"); ctx.strokeStyle = gradient;

var num = Math.random().toFixed(5) + "";
 this.validateCode = num.slice(2)
 ctx.strokeText(this.validateCode, 3, 22);

}

//清空画布
clearCanvas(): void {
let ctx: CanvasRenderingContext2D = this.myGraph.nativeElement.getContext("2d");
ctx.clearRect(0, 0, this.myGraph.nativeElement.width, this.myGraph.nativeElement.height);
}