利用canvas繪圖,前端實(shí)現(xiàn)登錄驗(yàn)證碼间驮,如下:
1,頁面:
<canvas id="canvas" @click="showNum" width="138" height="36"></canvas>
2马昨,數(shù)據(jù):
3竞帽,頁面載入成功后:
mounted(){
????this.draw(this.num);
????this.number =this.num.join().replace(/,/g,'');
}
4扛施,方法中:
/*點(diǎn)擊更換-驗(yàn)證碼*/
showNum(){
????this.draw(this.num);
????this.number =this.num.join().replace(/,/g,'');
},
draw(num) {
????var canvas_width=138;
????var canvas_height=36;
????var canvas =document.getElementById("canvas");//獲取到canvas的對象,演員
? ? var context =canvas.getContext("2d");//獲取到canvas畫圖的環(huán)境屹篓,演員表演的舞臺
? ? canvas.width =canvas_width;
????canvas.height =canvas_height;
????var sCode ="A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,U,V,W,X,Y,Z,1,2,3,4,5,6,7,8,9,0";
????var aCode =sCode.split(",");
????var aLength =aCode.length;//獲取到數(shù)組的長度
? ? for (var i =0;i <=3;i++) {
????????var j =Math.floor(Math.random() *aLength);//獲取到隨機(jī)的索引值
? ? ????var deg =Math.random() *15 *Math.PI /180;//產(chǎn)生0~30之間的隨機(jī)弧度
? ? ????var txt =aCode[j];//得到隨機(jī)的一個內(nèi)容
? ? ? ? //num[i] = txt.toLowerCase(); toUpperCase()
? ????? num[i] =txt;
????????var x =20 +i *30;//文字在canvas上的x坐標(biāo)
? ? ????var y =20 +Math.random() *8;//文字在canvas上的y坐標(biāo)
? ? ????context.font ="bold 23px 微軟雅黑";
????????context.translate(x,y);
????????context.rotate(deg);
????????context.fillStyle =this.randomColor();
????????context.fillText(txt,0,0);
????????context.rotate(-deg);
????????context.translate(-x, -y);
????}
????for (var i =0;i <=5;i++) {//驗(yàn)證碼上顯示線條
? ? ????context.strokeStyle =this.randomColor();
????????context.beginPath();
????????context.moveTo(Math.random() *canvas_width,Math.random() *canvas_height);
????????context.lineTo(Math.random() *canvas_width,Math.random() *canvas_height);
????????context.stroke();
????}
????for (var i =0;i <=30;i++) {//驗(yàn)證碼上顯示小點(diǎn)
? ? ????context.strokeStyle =this.randomColor();
????????context.beginPath();
????????var x =Math.random() *canvas_width;
????????var y =Math.random() *canvas_height;
????????context.moveTo(x,y);
????????context.lineTo(x +1,y +1);
????????context.stroke();
????}
},
//得到隨機(jī)的顏色值
randomColor() {
? ????var r =Math.floor(Math.random() *256);
? ? ? var g =Math.floor(Math.random() *256);
? ? ? var b =Math.floor(Math.random() *256);
? ? ? return "rgb(" +r +"," +g +"," +b +")";
}