微信小程序canvas验证码生成及使用(前端生成)
先看效果:

wxml:
<canvas class="v-code" bindtap="changeImg" style="width:100px; height:40px;" canvas-id="canvas"></canvas>
js:
const MCAP = require('../../utils/mcaptcha');
Page({
data: {
codeStr: '', //生成的验证码
code: '', //输入的验证码
},
/**
* 更换验证码
*/
changeImg: function () {
this.initDraw();
},
/**
* 制作验证码
*/
initDraw: function () {
var that = this;
var codes = that.getRanNum();
that.setData({
codeStr: codes //生成的验证码
})
let mac = new MCAP({
el: 'canvas',
width: 100,
height: 40,
code: codes
});
},
/**
* 获取随机数
*/
getRanNum: function () {
var chars = '0123456789';
// var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
var pwd = '';
for (var i = 0; i < 4; i++) {
if (Math.random() < 10) {
pwd += chars.charAt(Math.random() * 10 - 1);
}
}
return pwd;
},
})
mcaptcha.js代码:
module.exports = class Mcaptcha {
constructor(options) {
this.options = options;
this.fontSize = options.height * 3 / 4;
this.init();
this.refresh(this.options.code);
}
init() {
this.ctx = wx.createCanvasContext(this.options.el);
this.ctx.setTextBaseline("middle");
this.ctx.setFillStyle(this.randomColor(180, 240));
this.ctx.fillRect(0, 0, this.options.width, this.options.height);
}
refresh(code) {
let arr = (code + '').split('');
if (arr.length === 0) {
arr = ['e', 'r', 'r', 'o', 'r'];
};
let offsetLeft = this.options.width * 0.6 / (arr.length - 1);
let marginLeft = this.options.width * 0.2;
arr.forEach((item, index) => {
this.ctx.setFillStyle(this.randomColor(0, 180));
let size = this.randomNum(24, this.fontSize);
this.ctx.setFontSize(size);
let dis = offsetLeft * index + marginLeft - size * 0.3;
let deg = this.randomNum(-30, 30);
this.ctx.translate(dis, this.options.height * 0.5);
this.ctx.rotate(deg * Math.PI / 180);
this.ctx.fillText(item, 0, 0);
this.ctx.rotate(-deg * Math.PI / 180);
this.ctx.translate(-dis, -this.options.height * 0.5);
})
this.ctx.draw();
}
randomNum(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
randomColor(min, max) {
let r = this.randomNum(min, max);
let g = this.randomNum(min, max);
let b = this.randomNum(min, max);
return "rgb(" + r + "," + g + "," + b + ")";
}
}

浙公网安备 33010602011771号