微信小程序 canvas 生成隨機驗證碼
阿新 • • 發佈:2018-11-22
微信 font mco 字體顏色 字體大小 sdn 隨機 ref radi
https://blog.csdn.net/qq_16646819/article/details/81020245?utm_source=blogxgwz0
js
1 // pages/bind/bind.js 2 var app = getApp(); 3 var baseUrl = getApp().baseUrl; 4 var ctx; 5 Page({ 6 7 /** 8 * 頁面的初始數據 9 */ 10 data: { 11 text: ‘‘, 12 }, 13 14 /** 15 * 生命周期函數--監聽頁面加載16 */ 17 onLoad: function(options) { 18 var that = this; 19 drawPic(that); 20 }, 21 change: function() { 22 var that = this; 23 drawPic(that); 24 }, 25 mobile(e) { 26 this.setData({ 27 mobile: e.detail.value 28 })29 }, 30 })
1 function randomNum(min, max) { 2 return Math.floor(Math.random() * (max - min) + min); 3 } 4 /**生成一個隨機色**/ 5 function randomColor(min, max) { 6 var r = randomNum(min, max); 7 var g = randomNum(min, max); 8 var b = randomNum(min, max); 9 return"rgb(" + r + "," + g + "," + b + ")"; 10 } 11 12 /**繪制驗證碼圖片**/ 13 function drawPic(that) { 14 ctx = wx.createCanvasContext(‘canvas‘); 15 /**繪制背景色**/ 16 ctx.fillStyle = randomColor(180, 240); //顏色若太深可能導致看不清 17 ctx.fillRect(0, 0, 90, 28) 18 /**繪制文字**/ 19 var arr; 20 var text = ‘‘; 21 var str = ‘ABCEFGHJKLMNPQRSTWXY123456789‘; 22 for (var i = 0; i < 4; i++) { 23 var txt = str[randomNum(0, str.length)]; 24 ctx.fillStyle = randomColor(50, 160); //隨機生成字體顏色 25 ctx.font = randomNum(20, 26) + ‘px SimHei‘; //隨機生成字體大小 26 var x = 5 + i * 20; 27 var y = randomNum(20, 25); 28 var deg = randomNum(-20, 20); 29 //修改坐標原點和旋轉角度 30 ctx.translate(x, y); 31 ctx.rotate(deg * Math.PI / 180); 32 ctx.fillText(txt, 5, 0); 33 text = text + txt; 34 //恢復坐標原點和旋轉角度 35 ctx.rotate(-deg * Math.PI / 180); 36 ctx.translate(-x, -y); 37 } 38 /**繪制幹擾線**/ 39 for (var i = 0; i < 4; i++) { 40 ctx.strokeStyle = randomColor(40, 180); 41 ctx.beginPath(); 42 ctx.moveTo(randomNum(0, 90), randomNum(0, 28)); 43 ctx.lineTo(randomNum(0, 90), randomNum(0, 28)); 44 ctx.stroke(); 45 } 46 /**繪制幹擾點**/ 47 for (var i = 0; i < 20; i++) { 48 ctx.fillStyle = randomColor(0, 255); 49 ctx.beginPath(); 50 ctx.arc(randomNum(0, 90), randomNum(0, 28), 1, 0, 2 * Math.PI); 51 ctx.fill(); 52 } 53 ctx.draw(false, function() { 54 that.setData({ 55 text: text 56 }) 57 }); 58 }
wxml:
<canvas canvas-id="canvas" bindtap=‘change‘></canvas>
wxss
canvas {
width: 90px;
height: 28px;
border-radius: 14px;
}
驗證方法:
先獲取輸入的 驗證碼的值,通過js的.tolowerCase();方法將輸入的值中小寫字母全部轉成小寫已達到驗證碼不區分大小寫的目的,之後將輸入的值與data中的text進行比較,不一致則驗證碼輸入錯誤
微信小程序 canvas 生成隨機驗證碼