画布实现随机验证码
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. 鏈接地址( https://github.com/hsiangleev/component-randomCode?)
轉載于:https://www.cnblogs.com/hsianglee/p/7449798.html
總結
- 上一篇: java中List Set Map使用
- 下一篇: 【bzoj1010-toy】斜率优化入门