如何等到 canvas 完成重新渲染?

How to wait until canvas has finished re-rendering?

我有一个 renderText() 函数,可以用文本 (ctx.fillText(char, charLocation, 400)) 填充 canvas。我希望它呈现文本,暂停 2 秒,然后呈现新文本。

解决方法:

renderText();
setTimeout(() => {
    renderNewText();
}, 2000);

这个解决方案目前没问题,但如果我想将它减少到 0.1 秒,而 renderText() 执行时间超过 0.1 秒,导致 renderNewText() 在 [=12] 之前执行怎么办? =]?我怎么能肯定地等到 renderText() 完成 fillText 后再暂停,不管我想暂停多长时间?

我所知道的:我知道 canvascontext 完全同步呈现;因此,renderText() 不会 return 任何承诺,即使在退出 renderText() 后,上下文中调用的所有方法也会继续。此外,没有任何事件可以在完成时发出信号,至少根据我读过的所有评论和主题是这样。在我在 Stack Overflow 上查找的所有解决方案中,答案几乎都是 "You can't",但我觉得很难相信。

我敢肯定肯定有一些我真的没有在这里得到的东西,可能是事件循环或 Promises 或其他东西。

来自@towc 的

canvas api calls are asynchronous, sure, but they're queued, so the order is preserved. To know more about this, read up on the event loop. If you have a race condition, it's somewhere else