canvas繪製二維碼
阿新 • • 發佈:2019-01-29
第一步:複製下面的程式碼!
第二步:給你程式碼!
html: <!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> <title>canvas-驗證碼</title> </head> <body> <canvas id="canvas"></canvas> </body> <script type="text/javascript"> function getColor(){ 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 +")"; }//隨機顏色 window.onload=function(){ var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d');//建立2d環境 canvas.width = 120;//設定寬度 canvas.height = 40;//設定高度 context.strokeRect(0,0,120,40)//繪製畫布(x,y,width,height) //文字繪製 var aCode = [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'];//建立隨機陣列 for(i=0;i<4;i++){ var index = Math.floor(Math.random()*aCode.length);//獲取隨機索引值 var txt = aCode[index];//獲取陣列中的隨機內容 var x = 20+i*20; var y = 20+Math.random()*10; var deg = Math.random()*90*Math.PI/360; context.font = 'bold 20px 微軟雅黑';//設定文字樣式 context.fillStyle = getColor(); context.translate(x,y); context.rotate(deg); context.fillText(txt,0,0); context.rotate(-deg); context.translate(-x,-y); } //繪製干擾線 for(var i=0;i<8;i++){ context.strokeStyle = getColor(); context.beginPath(); context.moveTo(Math.random()*120,Math.random()*40);//設定起點座標 context.lineTo(Math.random()*120,Math.random()*40);//設定重點的座標 context.stroke();//開始繪製 } //繪製干擾點 for(var i=0;i<20;i++){ var x = Math.random()*120; var y = Math.random()*40; context.strokeStyle = getColor(); context.beginPath(); context.moveTo(x,y); context.lineTo(x+1,y+1); context.stroke(); } } </script> </html>
看效果!!!!!!
重新整理試試!!