/**生成一个随机数**/
randomNum(min, max) {
return Math.floor(Math.random() * (max - min) + min);
},
/**生成一个随机色**/
randomColor(min, max) {
var r = this.randomNum(min, max);
var g = this.randomNum(min, max);
var b = this.randomNum(min, max);
return "rgb(" + r + "," + g + "," + b + ")";
},
refresh(vCode) {
var ctx = vCode.getContext('2d'),code = '';
ctx.textBaseline = "middle";
ctx.fillStyle = this.randomColor(180, 240);
ctx.fillRect(0, 0, vCode.width, vCode.height);
for(var i = 1; i <= 4; i++) {
let random = new Array('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',0,1,2,3,4,5,6,7,8,9);
var txt = random[this.randomNum(0,random.length)];
code += txt;
ctx.font = this.randomNum(vCode.height/2, vCode.height) + 'px SimHei'; //随机生成字体大小
ctx.fillStyle = this.randomColor(50, 160); //随机生成字体颜色
ctx.shadowOffsetX = this.randomNum(-3, 3);
ctx.shadowOffsetY = this.randomNum(-3, 3);
ctx.shadowBlur = this.randomNum(-3, 3);
ctx.shadowColor = "rgba(0, 0, 0, 0.3)";
var x = vCode.width / 5 * i;
var y = vCode.height / 2;
var deg = this.randomNum(-30, 30);
/**设置旋转角度和坐标原点**/
ctx.translate(x, y);
ctx.rotate(deg * Math.PI / 180);
ctx.fillText(txt, 0, 0);
/**恢复旋转角度和坐标原点**/
ctx.rotate(-deg * Math.PI / 180);
ctx.translate(-x, -y);
}
this.code = code;
/**绘制干扰线**/
for(var i = 0; i < 4; i++) {
ctx.strokeStyle = this.randomColor(40, 180);
ctx.beginPath();
ctx.moveTo(this.randomNum(0, vCode.width), this.randomNum(0, vCode.height));
ctx.lineTo(this.randomNum(0, vCode.width), this.randomNum(0, vCode.height));
ctx.stroke();
}
/**绘制干扰点**/
for(var i = 0; i < vCode.width/2; i++) {
ctx.fillStyle = this.randomColor(0, 255);
ctx.beginPath();
ctx.arc(this.randomNum(0, vCode.width), this.randomNum(0, vCode.height), 1, 0, 2 * Math.PI);
ctx.fill();
}
this.convertCanvasToImage(ctx);
}
this.refresh(this.$refs.vCode);