一:需要加载的js mcaptcha.js
https://pan.baidu.com/s/1hbHZkqJCuYBPtkT9kFeZtg
二:效果图
image.png三:html
<view class='member_main input_center'>
<view class='center_left'>
<input placeholder-class="phcolor" type='text' class="weui-input" maxlength="4" placeholder='请输入验证码' value='{{code}}' name="code" bindinput='bindCode' />
</view>
<view class="capture">
<canvas style="width:{{cvs.width}};height:{{cvs.height}};" canvas-id="canvas"></canvas>
</view>
<view class="changeImg" bindtap="changeImg">换一换</view>
</view>
<view class='btn'>
<button catchtap='saves'>提交</button>
</view>
四:css
.member_main {
width: 96%;
margin: 30rpx 20rpx;
padding-bottom: 20rpx;
border-bottom: 1px solid #dcdcde;
}
.member_main input {
background: none;
border: none;
padding: 15px 0;
outline: none;
width: 95%;
font-size: 40rpx;
}
.phcolor {
color: #d1d1d1;
}
.input_center {
height: 90rpx;
display: flex;
align-items: center;
border-bottom: 1px solid #f0f0f0;
}
.input_center view {
display: inline-block;
}
.input_center .center_left {
width: 45%;
}
.input_center .capture {
width: 35%;
}
.input_center .changeImg {
width: 20%;
padding: 20rpx;
text-decoration: underline;
color: #4b5987;
}
.btn {
width: 90%;
margin: 0 auto;
padding: 0;
display: flex;
flex-direction: column;
text-align: center;
}
.btn button {
width: 100%;
background: #485a8b;
border: none;
text-align: center;
color: #fff;
outline: none;
font-size: 40rpx;
}
canvas {
width: 300rpx;
height: 80rpx;
}
五:js
1:加载mcaptcha.js
var MCAP = require('../../utils/mcaptcha.js');
2:初始化变量
/**
* 页面的初始数据
*/
data: {
codeStr: '', //生成的验证码
code: '', //输入的验证码
},
3:onLoad里面初始化验证码
/**
* 初始化验证码
*/
onLoad: function(options) {
var that = this;
that.initDraw(); //生成验证码
},
4:制作验证码
/**
* 制作验证码
*/
initDraw() {
var that = this;
var codes = that.getRanNum();
that.setData({
codeStr: codes //生成的验证码
})
new MCAP({
el: 'canvas',
width: 120,
height: 40,
code: codes
});
},
5:换一换更换验证码
/**
* 更换验证码
*/
changeImg: function () {
this.initDraw();
},
6:输入验证码绑定变量
/**
* 图片验证码绑定变量
*/
bindCode: function(e) {
this.setData({
code: e.detail.value
})
},
7:提交获取验证码
/**
* 点击提交触发
*/
saves: function() {
console.log('输入的验证码为:'+this.data.code)
},
8:制作验证码生成随机数函数
/**
* 获取随机数
*/
getRanNum: function () {
var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
var pwd = '';
for (var i = 0; i < 4; i++) {
if (Math.random() < 48) {
pwd += chars.charAt(Math.random() * 48 - 1);
}
}
return pwd;
},
网友评论