微信小程序 canvas 生成随机验证码

https://blog.****.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 生成随机验证码

上一篇:《算法技术手册》一2.6 参考文献


下一篇:本地html文件实现URL页面跳转