微信小程序-拼图动态验证


一、创建自定义组件verification-puzzle
verification-puzzle.js
var ctxShadow;
var ctxPuzzle;
Component({
/**
* 组件的属性列表
*/
properties: {
width: {
type: String,
value: "500rpx"
},
height: {
type: String,
value: "80rpx"
},
},
/**
* 组件的初始数据
*/
data: {
oriSrc:'https://ns-strategy.cdn.bcebos.com/ns-strategy/upload/fc_big_pic/part-00798-3706.jpg',
imgPuzzle: '',
imgShadow: '',
translateX: 0,
oriX:0,
x: 0,
oldx: 0,
isOk: false,
size: {
},
width:"500rpx",
height:"80rpx"
},
ready() {
this.setData({
width:this.properties.width,
height:this.properties.height
})
this.drawPic(100, 70, 5)
let getSize = (selector) => {
return new Promise((resolve, reject) => {
let view = wx.createSelectorQuery().in(this).select(selector);
view.fields({
size: true,
}, (res) => {
resolve(res.width);
}).exec();
});
}
getSize("#pathway").then((res1) => {
this.data.size.pathway = res1;
getSize("#track").then((res2) => {
this.data.size.track = res2;
});
})
},
/**
* 组件的方法列表
*/
methods: {
drawPic(x, y, r) {
var that = this
that.setData({
translateX: -x,
oriX:-x
})
ctxPuzzle = wx.createCanvasContext('canvasPuzzle',this)
ctxShadow = wx.createCanvasContext('canvasShadow',this)
this.clip(ctxPuzzle, x, y, r)
wx.getImageInfo({
src: that.data.oriSrc,
success: function (res) {
ctxPuzzle.drawImage(res.path, 0, 0, 250, 150);
ctxPuzzle.restore();
ctxPuzzle.draw(false, setTimeout(() => {
wx.canvasToTempFilePath({
canvasId: 'canvasPuzzle',
success: function (e) {
console.log("!!!!", e)
that.setData({
imgPuzzle: e.tempFilePath
})
},
fail: function (e) {
console.log("AAAA", e)
}
}, that)
}, 100))
}
})
this.clip