gpt4 book ai didi

javascript - Canvas 绘图 : Await for images to load in a recursive method

转载 作者:行者123 更新时间:2023-12-02 23:46:52 25 4
gpt4 key购买 nike

我正在实现一种递归方法,该方法采用图像数组并将它们绘制到 Canvas 中:

async drawImages(ctx, images): Promise<any> {
const img = images.shift();
const imgToDraw = new Image();
imgToDraw.src = img.src;
imgToDraw.onload = () => {
ctx.drawImage(imgToDraw, img.x, img.y, img.w, img.h);
if (images.length > 0) {
this.drawImages(ctx, images);
} else {
console.log("I - Processing");
return Promise.resolve();
}
}
}

在该方法执行结束时,我需要检索 Canvas 的 DataURL,我是这样做的:

someCallingMethod() {
//...
await this.drawImages(ctx, images);
console.log("II - Finished");
console.log(canvas.toDataURL());
}

我面临的问题是await 不适用于drawImages 方法。执行此代码时,我总是在 "I - Processing" 日志之前获得 "II - Finished" 日志,因此 canvas.toDataURL() 永远不会包含应该绘制到 Canvas 上的图像。

谢谢

最佳答案

需要同步返回Promise。
在这里,您将在异步 onload 事件处理程序中返回它。
所以 drawImages 不会返回 Promise,而是未定义。

此外,您将希望每次都返回 drawImages 的下一个迭代,以便您的外部 await 等待所有这些 Promise:

const obj = {
async drawImages(ctx, images) {
// return a Promise synchronously
return new Promise((resolve, reject) => {
const img = images.shift();
const imgToDraw = new Image();
imgToDraw.src = img.src;
imgToDraw.onload = () => {
ctx.drawImage(imgToDraw, img.x, img.y, img.w, img.h);
if (images.length > 0) {
// resolve with next iteration so we can await all
resolve(this.drawImages(ctx, images));
} else {
console.log("I - Processing");
// done
resolve();
}
};
imgToDraw.onerror = reject;
});
}
};

(async () => {
const images = [];
// picsum.photos doesn't fill all the indexes...
const urls = ["01", "02", "03", "04", "05", "06", "10", "11", "12", "13"];
const s = 50; // image size
for(let i=0; i<10; i++) {
images.push( {
src: `https://picsum.photos/${s}/${s}?image=10` + urls[i],
x: (i%5)*s,
y: Math.floor(i/5)*s,
w: s,
h: s
});
}
const ctx = canvas.getContext('2d');
await obj.drawImages(ctx, images);
// fill a green rect over to show we are able to await it
ctx.fillStyle = 'rgba(0,255,0, 0.2)';
ctx.fillRect(0,0,canvas.width,canvas.height);
console.log("all done");
})();
<canvas id="canvas" width="250" height="100"></canvas>

关于javascript - Canvas 绘图 : Await for images to load in a recursive method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55821099/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com