一、创建自定义组件verification-code
verification-code.js
var ctx;
Component({
properties: {
width:{
type: Number,
value: 150
},
height: {
type: Number,
value: 48
},
count:{
type:Number,
value:4
},
fontSize: {
type: Number,
value: 34
},
fontFamily:{
type: String,
value: "SimHei"
}
},
data: {
text: '',
count: 4,
width:90,
height:28,
fontSize:30,
fontFamily:"SimHei"
},
ready() {
this.setData({
count:this.properties.count,
width:this.properties.width,
height:this.properties.height,
fontSize:this.properties.fontSize,
fontFamily:this.properties.fontFamily
})
this.drawPic(this)
},
methods: {
crash(){
this.drawPic(this)
},
drawPic(that) {
ctx = wx.createCanvasContext('canvas',this);
ctx.fillStyle = randomColor(180, 240);
ctx.fillRect(0, 0, that.data.width, that.data.height)
var arr;
var text = '';
var str = 'ABCEFGHJKLMNPQRSTWXY123456789';
for (var i = 0; i < that.data.count; i++) {
var txt = str[randomNum(0, str.length)];
ctx.fillStyle = randomColor(50, 160);
ctx.font = randomNum(20, 26) + 'px SimHei';
var x = 10 + i * 20;
var y = randomNum(25, 30);
var deg = randomNum(-30, 30);
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, that.data.width), randomNum(0, that.data.height));
ctx.lineTo(randomNum(0, that.data.width), randomNum(0, that.data.height));
ctx.stroke();
}
for (var i = 0; i < 20; i++) {
ctx.fillStyle = randomColor(0, 255);
ctx.beginPath();
ctx.arc(randomNum(0, that.data.width), randomNum(0, that.data.height), 1, 0, 2 * Math.PI);
ctx.fill();
}
ctx.draw(false, function() {
console.log(text)
that.triggerEvent('result', { text });
that.setData({
text: text,
})
})
}
}
})
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 + ")";
}
verification-puzzle.json
{
"component": true,
"usingComponents": {}
}
verification-puzzle.wxml
<canvas style="width:{{width}}px;height:{{height}}px" canvas-id="canvas" bindtap='crash'></canvas>
二、在index页面使用
index.wxml
<verification-code id="verification"></verification-code>
<view bindtap="crash">刷新</view>
index.js
Page({
data: {},
crash() {
this.verification.crash()
},
onLoad: function (options) {
},
onReady: function () {
this.verification = this.selectComponent('#verification')
},
onShow: function () {
},
onHide: function () {
},
onUnload: function () {
},
onPullDownRefresh: function () {
},
onReachBottom: function () {
},
onShareAppMessage: function () {
}
})
index.json
{
"usingComponents": {
"verification-code": "/components/verification-code/verification-code"
}
}
|