In the WeChat applet, the function of clicking the canvas to convert it into a picture and then previewing it is implemented. Since the asynchronous method is called in the for loop, according to the online suggestions, an immediate execution function is used inside the for loop. Multiple tests have found that , sometimes the console will first print out "loop index is 1", and then print out "loop index is 0" (for convenience, the model length is 2), leading to a situation like this: you click on the first canvas, As a result, the preview was the second one. I am puzzled and hope God can enlighten me.
<canvas wx:for="{{ model }}" bindtap="previewImg" canvas-id="{{ 'mycanvas' + index }}" data-index="{{ index }}"/>
// 点击图片进行预览
previewImg: function (e) {
var tempFilePathList = [];
var index = e.target.dataset.index;
var self = this;
var loopedModel = self.data.model;
for (var i = 0; i < loopedModel.length; i++) {
(function (a) {
wx.canvasToTempFilePath({
canvasId: 'mycanvas' + a,
success: function (res) {
console.log('loop index is ' + a);
tempFilePathList.push(res.tempFilePath);
if (a == loopedModel.length - 1) { // 循环到最后一个了
console.log('current image is ' + tempFilePathList[index]);
wx.previewImage({
current: tempFilePathList[index], // 当前显示图片的http链接
urls: tempFilePathList // 需要预览的图片http链接列表
})
}
},
fail: function (res) {
console.log(res);
}
});
}(i))
}
},
This is normal. The time of asynchronous return is uncertain, so if you have two asynchronous methods at the same time, the order of return is also uncertain. I haven't done it with WeChat, but it should also support the h5 synchronization method. You can try it. If it doesn't work, add a variable control. When there are multiple requests in the queue that have not been returned, you will only display the last one, and the others will not be displayed.