最近在做一款表情合成器,就是多个身体组件图片按照一定层级进行顺序绘制出一个完整的图片,如果所示
遇到在小程序里使用canvas2d后,图片顺序加载的问题。
按照官方文档,canvas2d的绘制图片的逻辑是同步请求,而不是之前的一张一张的绘制。这也就导致图片在合成加载时,先load完成哪一张图片就先绘制这样,会因为图片的层级顺序导致图片不成功。
使用next()函数,判断绘制完一张后再进行下一张绘制,记录一下uniapp的写法:
...
async drawAll() {
const that = this;
let views = this.isAsync ? await this.initBoard() : this.board.views
if (!this.context || !views.length) {
return
}
this.context.clearRect(0, 0, that.canvasNode.width, that.canvasNode.height)
...
const promises = new Promise((resolve, reject) => {
const _views = views
.map(n => ({
...n,
zIndex: n.zIndex || 0
}))
.sort((n, m) => n.zIndex - m.zIndex)
const next = (index = 0) => {
const item = _views[index]
if (index < _views.length) {
const dd = this.drawView(this.context, item).then((res) => {
next(++index)
}).catch(error => {})
} else {
resolve()
}
}
next()
});
Promise.all([board].concat(promises)).then((res) => {
clearTimeout(this.timer)
this.timer = setTimeout(() => {
this.saveImgToLocal();
}, 100)
})
}
...