日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

画布实现随机验证码

發布時間:2023/12/18 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 画布实现随机验证码 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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

總結

以上是生活随笔為你收集整理的画布实现随机验证码的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。