获取验证码canvas
生活随笔
收集整理的這篇文章主要介紹了
获取验证码canvas
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
2019獨(dú)角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>
1,html部分
<div class="box"><label class="side">驗(yàn)證碼</label><input class="box-flex input-full" id="verify" type="text" placeholder="請(qǐng)輸入驗(yàn)證碼" ><div class="side" style="width: 100px;margin-left:10px;"><canvas width="100" height="40" id="verifyCanvas"></canvas><img id="code_img"></div></div>2,js部分
//下面為驗(yàn)證碼var nums = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", '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', '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'];drawCode();// 繪制驗(yàn)證碼function drawCode() {var canvas = document.getElementById("verifyCanvas"); //獲取HTML端畫(huà)布var context = canvas.getContext("2d"); //獲取畫(huà)布2D上下文context.fillStyle = "#565656"; //畫(huà)布填充色context.fillRect(0, 0, canvas.width, canvas.height); //清空畫(huà)布context.fillStyle = "white"; //設(shè)置字體顏色context.font = "25px Arial"; //設(shè)置字體var rand = new Array();var x = new Array();var y = new Array();for (var i = 0; i < 5; i++) {rand[i] = nums[Math.floor(Math.random() * nums.length)]x[i] = i * 16 + 10;y[i] = Math.random() * 20 + 20;context.fillText(rand[i], x[i], y[i]);}//畫(huà)3條隨機(jī)線for (var i = 0; i < 3; i++) {drawline(canvas, context);}// 畫(huà)30個(gè)隨機(jī)點(diǎn)for (var i = 0; i < 30; i++) {drawDot(canvas, context);}convertCanvasToImage(canvas)}// 隨機(jī)線function drawline(canvas, context) {context.moveTo(Math.floor(Math.random() * canvas.width), Math.floor(Math.random() * canvas.height)); //隨機(jī)線的起點(diǎn)x坐標(biāo)是畫(huà)布x坐標(biāo)0位置,y坐標(biāo)是畫(huà)布高度的隨機(jī)數(shù)context.lineTo(Math.floor(Math.random() * canvas.width), Math.floor(Math.random() * canvas.height)); //隨機(jī)線的終點(diǎn)x坐標(biāo)是畫(huà)布寬度,y坐標(biāo)是畫(huà)布高度的隨機(jī)數(shù)context.lineWidth = 0.5; //隨機(jī)線寬context.strokeStyle = 'rgba(50,50,50,0.3)'; //隨機(jī)線描邊屬性context.stroke(); //描邊,即起點(diǎn)描到終點(diǎn)}// 隨機(jī)點(diǎn)(所謂畫(huà)點(diǎn)其實(shí)就是畫(huà)1px像素的線,方法不再贅述)function drawDot(canvas, context) {var px = Math.floor(Math.random() * canvas.width);var py = Math.floor(Math.random() * canvas.height);context.moveTo(px, py);context.lineTo(px + 1, py + 1);context.lineWidth = 0.2;context.stroke();}// 繪制圖片function convertCanvasToImage(canvas) {document.getElementById("verifyCanvas").style.display = "none";var image = document.getElementById("code_img");image.src = canvas.toDataURL("image/png");return image;}// 點(diǎn)擊圖片刷新document.getElementById('code_img').onclick = function () {$('#verifyCanvas').remove();$('#verify').after('<canvas width="100" height="40" id="verifyCanvas"></canvas>');drawCode();}轉(zhuǎn)載于:https://my.oschina.net/u/2393989/blog/2254786
總結(jié)
以上是生活随笔為你收集整理的获取验证码canvas的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 公牛插座怎么样?公牛插座的价格是多少
- 下一篇: 数据运营的三种角色