畫布實現隨機驗證碼
阿新 • • 發佈:2017-08-29
add 等於 得到 fse abc div for baseline def
1. html模板:
1 <div class="c-code"> 2 <canvas id="c-cvs"></canvas> 3 </div>
2. 使用:
2.1 引用js文件
2.2 在模板之外添加一個盒子,寬高必須給,驗證碼寬高與之相等
2.3 每調用一次drawBg(),刷新一次
2.4 drawBg().textArr 得到當前的文本內容存為數組
2.5 drawBg().text 得到當前的文本內容存為字符串
3. js代碼:
(function (w){ var oCode=document.getElementsByClassName("c-code")[0]; var cvs=document.getElementById("c-cvs"); var ctx=cvs.getContext("2d"); //設置整個內容寬高與父盒子相等 oCode.style.width="100%"; oCode.style.height="100%"; function drawBg(){ //獲取盒子寬高 this.width=oCode.offsetWidth; this.height=oCode.offsetHeight; //隨機點坐標 this.randomX=0; this.randomY=0; //存放驗證碼內容(數組) this.textArr=[]; //存放驗證碼內容(字符串) this.text=""; this._init(); this.draw(); this.addPoint(); this.addText(); } drawBg.prototype={ constructor: drawBg, //設置畫布寬高 _init: function (){ cvs.width=this.width; cvs.height=this.height; }, //獲取隨機的顏色 randomColor: function (){ var colorStr="0123456789abcdef"; var colorArr=colorStr.split(""); this.color="#"; //0-15隨機數 var randomNum; for (var i = 0; i < 6; i++) { randomNum=Math.floor(Math.random()*16) this.color+=colorArr[randomNum] } return this.color; }, //繪制背景 draw: function (){ //每次創建先清除畫布 ctx.clearRect(0,0,this.width,this.height); ctx.fillStyle=this.randomColor(); ctx.fillRect(0,0,this.width,this.height); }, //繪制隨機點 randomPoint: function (){ this.randomX=Math.random()*this.width; this.randomY=Math.random()*this.height; ctx.fillStyle=this.randomColor(); ctx.fillRect(this.randomX,this.randomY,2,2); ctx.fill(); }, //添加多個隨機點 addPoint: function (){ //生成的點的個數等於(寬*高/10) var num=Math.floor(this.width*this.height/10); for (var i = 0; i < num; i++) { this.randomPoint(); } }, //添加文本 addText: function (){ // 0-61隨機數 var randomNum; //textData: (0-9 a-z A-Z) var textData=[]; for(var i=48;i<58;i++){ textData.push(String.fromCharCode(i)); } for(var i=65;i<91;i++){ textData.push(String.fromCharCode(i)); } for(var i=97;i<123;i++){ textData.push(String.fromCharCode(i)); } this.text=""; this.textArr=[]; for(var i=0;i<4;i++){ randomNum=Math.floor(Math.random()*62); this.text+=textData[randomNum]; this.textArr.push(textData[randomNum]); } //繪制文本 ctx.font="bold 25px Arial"; ctx.textAlign="center"; ctx.textBaseline="middle"; ctx.fillStyle=this.randomColor; ctx.fillText(this.text,this.width/2,this.height/2); } } w.drawBg=function (){ return new drawBg(); } })(window)
4. 鏈接地址( http://hsianglee.top/component/randomCode.html )
畫布實現隨機驗證碼