原生js+canvas實(shí)現(xiàn)驗(yàn)證碼
本文實(shí)例為大家分享了js+canvas實(shí)現(xiàn)驗(yàn)證碼的具體代碼,供大家參考,具體內(nèi)容如下
效果展示:
源碼展示:
<!DOCTYPE html><html lang='en'><head> <meta charset='UTF-8'> <title>Title</title></head><body><style> canvas { border: 1px solid #000; vertical-align: bottom; } input { padding: 0; width: 120px; height: 30px; vertical-align: bottom; border: 1px solid #000; } </style> <input type='text' name='textContent' placeholder='輸入'><canvas height='30'></canvas><button>提交</button> <script> /*1、背景顏色時(shí)隨機(jī)的 * 2、其中的內(nèi)容是隨機(jī)的 * 3、內(nèi)容的顏色 隨機(jī)的 * 4、每個(gè)字的旋轉(zhuǎn)度數(shù)隨機(jī)的 * 5、文本的大小隨機(jī)的 * 6、干擾線的位置隨機(jī)的 * 7、干擾線的顏色隨機(jī)的 * 8、干擾點(diǎn) * */ var btn = document.querySelector('button'); var can = document.querySelector('canvas'); var ctx = can.getContext('2d'); var text = '0123456789abcdefghijklmnopqrstuvwsyzABCDEFGHIGKLMNOPQRSTUVWSYZ'; //設(shè)置4個(gè)內(nèi)容 將canvas 平分成4分 然后讓內(nèi)容在1/4的空間旋轉(zhuǎn)縮放 //原理 :每次都是位移旋轉(zhuǎn)之后再回復(fù)原位 for (var i = 0; i < 4; i++) { var txt = text[randNum(0,text.length-1)]; ctx.fillStyle = getRandColor(80,150); ctx.font=randNum(12,25)+'px ’宋體’'; ctx.textBaseline = 'top'; var x = randNum(0,10); var deg = randNum(-30,30); ctx.translate(x+30*i,0); ctx.rotate(Math.PI/180*deg); ctx.fillText(txt,0,0); ctx.rotate(Math.PI/180*-deg); ctx.translate(-(x+30*i),0); } /*干擾點(diǎn)*/ for(var i=0;i<30;i++){ ctx.beginPath(); ctx.arc(randNum(0,120),randNum(0,30),1,0,Math.PI*2); ctx.fillStyle=getRandColor(150,180); ctx.fill(); } /*干擾線*/ for(var i=0;i<4;i++){ ctx.beginPath(); ctx.moveTo(randNum(0,120),randNum(0,30)); ctx.lineTo(randNum(0,120),randNum(0,30)); ctx.strokeStyle=getRandColor(150,180); ctx.lineWidth= randNum(1,2); ctx.stroke(); } /* 獲取隨機(jī)色值*/ // a 先獲取一個(gè)隨機(jī)數(shù) console.log(Math.random()); //產(chǎn)生一個(gè)0~1之間的隨機(jī)小數(shù) var num = Math.random() * (100 - 30 + 1) + 30; //產(chǎn)生一個(gè)隨機(jī)數(shù)30~100 之間的數(shù) console.log(num); // b 獲取一個(gè)區(qū)間段的隨機(jī)數(shù)(整數(shù)) function randNum(min, max) { return parseInt(Math.random() * (max - min + 1) + min); } // c獲取隨機(jī)顏色值 function getRandColor(min, max) { var R = randNum(min, max); var G = randNum(min, max); var B = randNum(min, max); return ’rgb(’ + R + ’,’ + G + ’,’ + B + ’)’; } </script> </body></html>
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. vue實(shí)現(xiàn)web在線聊天功能2. SpringBoot+TestNG單元測(cè)試的實(shí)現(xiàn)3. Springboot 全局日期格式化處理的實(shí)現(xiàn)4. idea配置jdk的操作方法5. Docker容器如何更新打包并上傳到阿里云6. Java GZip 基于內(nèi)存實(shí)現(xiàn)壓縮和解壓的方法7. 完美解決vue 中多個(gè)echarts圖表自適應(yīng)的問題8. VMware中如何安裝Ubuntu9. python 浮點(diǎn)數(shù)四舍五入需要注意的地方10. JAMon(Java Application Monitor)備忘記
