From 6a0b96d7eacffe778149dfe9f9fcaec79d6616ba Mon Sep 17 00:00:00 2001 From: Damien Elmes Date: Sat, 28 Oct 2023 07:59:06 +1000 Subject: [PATCH] Fix I/O failing to load if image takes too longer --- ts/image-occlusion/review.ts | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/ts/image-occlusion/review.ts b/ts/image-occlusion/review.ts index 5ac4e94be..576e95bbd 100644 --- a/ts/image-occlusion/review.ts +++ b/ts/image-occlusion/review.ts @@ -40,13 +40,40 @@ interface SetupImageOcclusionOptions { onDidDrawShapes?: DrawShapesCallback; } -function setupImageOcclusion(setupOptions?: SetupImageOcclusionOptions): void { +async function setupImageOcclusion(setupOptions?: SetupImageOcclusionOptions): Promise { + await waitForImage(); window.addEventListener("load", () => { window.addEventListener("resize", () => setupImageOcclusion(setupOptions)); }); window.requestAnimationFrame(() => setupImageOcclusionInner(setupOptions)); } +/** We must make sure the image has loaded before we can access its dimensions. + * This can happen if not preloading, or if preloading takes too long. */ +async function waitForImage(): Promise { + const image = document.querySelector( + "#image-occlusion-container img", + ) as HTMLImageElement | null; + if (!image) { + // error will be handled later + return; + } + + if (image.complete) { + return; + } + + // Wait for the image to load + await new Promise(resolve => { + image.addEventListener("load", () => { + resolve(); + }); + image.addEventListener("error", () => { + resolve(); + }); + }); +} + function setupImageOcclusionInner(setupOptions?: SetupImageOcclusionOptions): void { const canvas = document.querySelector( "#image-occlusion-canvas",