多次canvas.createImage加载同一个src,不触发onload也不能canvas画图
<button bind:tap="drawCanvas" type="primary">drawCanvas</button>
<image src="{{ imageSrc }}" />
正常情况下,点击按钮,图片会在新的坐标绘制,但是第二次点击直接就是用不了了。 // index.js
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
Page({
data: {
times: 0,
logs: [],
imageSrc: ''
},
async drawCanvas() {
let times = this.data.times;
let log = (msg, ...args) => {
this.setData({ logs: [msg, ...this.data.logs] })
console.log(msg, ...args)
}
async function loadImage(can, src) {
return new Promise((resolve, reject) => {
const img = can.createImage()
const timer = setTimeout(() => {
log('image load timeout! force continue! size = ' + img.width + 'x' + img.height)
resolve(img)
}, 500)
img.onload = () => {
log('image loaded!', img.width, img.height)
resolve(img)
clearTimeout(timer)
}
img.onerror = (error) => {
log('Failed to load image:', component.imageUrl, error);
reject(error);
clearTimeout(timer)
};
img.src = src
})
}
try {
this.setData({ times: times + 1 })
console.log('create canvas')
const can = wx.createOffscreenCanvas({
width: 800,
height: 480,
type: '2d'
})
log('get ctx')
/** @type {CanvasRenderingContext2D} */
const ctx = can.getContext('2d')
log('fill canvas')
ctx.fillStyle = '#ee3300'
ctx.fillRect(0, 0, 800, 480)
const image = await loadImage(can, defaultAvatarUrl)
ctx.drawImage(image, (100 * times) % 800, 40, 300, 400)
ctx.fillStyle = '#3003ff'
ctx.fillRect(10, 60, 800, 60)
log('saving image')
const out = await wx.canvasToTempFilePath({ canvas: can })
this.setData({ imageSrc: out.tempFilePath })
log('OK!')
} catch (err) {
error('draw err', err)
}
}
})
翻到一个旧的帖子发现好像一直没fix,就这样摆烂了么? https://developers.weixin.qq.com/community/develop/doc/000e66a1b2c98836858ea46d55b800