jscanvas
// pages/bind/bind.js var app = getApp(); var ctx; Page({ /** * 頁面的初始數據 */ data: { text: '', }, /** * 生命週期函數--監聽頁面加載 */ onLoad: function(options) { var that = this; drawPic(that); }, change: function() { var that = this; drawPic(that); }, mobile(e) { this.setData({ mobile: e.detail.value }) }, }) function randomNum(min, max) { return Math.floor(Math.random() * (max - min) + min); } /**生成一個隨機色**/ function randomColor(min, max) { var r = randomNum(min, max); var g = randomNum(min, max); var b = randomNum(min, max); return "rgb(" + r + "," + g + "," + b + ")"; } /**繪製驗證碼圖片**/ function drawPic(that) { ctx = wx.createCanvasContext('canvas'); /**繪製背景色**/ ctx.fillStyle = randomColor(180, 240); //顏色若太深可能致使看不清 ctx.fillRect(0, 0, 90, 28) /**繪製文字**/ var arr; var text = ''; var str = 'ABCEFGHJKLMNPQRSTWXY123456789'; for (var i = 0; i < 4; i++) { var txt = str[randomNum(0, str.length)]; ctx.fillStyle = randomColor(50, 160); //隨機生成字體顏色 ctx.font = randomNum(20, 26) + 'px SimHei'; //隨機生成字體大小 var x = 5 + i * 20; var y = randomNum(20, 25); var deg = randomNum(-20, 20); //修改座標原點和旋轉角度 ctx.translate(x, y); ctx.rotate(deg * Math.PI / 180); ctx.fillText(txt, 5, 0); text = text + txt; //恢復座標原點和旋轉角度 ctx.rotate(-deg * Math.PI / 180); ctx.translate(-x, -y); } /**繪製干擾線**/ for (var i = 0; i < 4; i++) { ctx.strokeStyle = randomColor(40, 180); ctx.beginPath(); ctx.moveTo(randomNum(0, 90), randomNum(0, 28)); ctx.lineTo(randomNum(0, 90), randomNum(0, 28)); ctx.stroke(); } /**繪製干擾點**/ for (var i = 0; i < 20; i++) { ctx.fillStyle = randomColor(0, 255); ctx.beginPath(); ctx.arc(randomNum(0, 90), randomNum(0, 28), 1, 0, 2 * Math.PI); ctx.fill(); } ctx.draw(false, function() { that.setData({ text: text }) }); }
wxml:app
<canvas canvas-id="canvas" bindtap='change'></canvas>
wxssdom
canvas { width: 90px; height: 28px; border-radius: 14px; }
驗證方法:xss
先獲取輸入的 驗證碼的值,經過js的.toUpperCase();方法將輸入的值中小寫字母所有轉成大寫已達到驗證碼不區分大小寫的目的,以後將輸入的值與data中的text進行比較,不一致則驗證碼輸入錯誤函數