Improve loadImage to use a placeholder and prevent game crash

This commit is contained in:
Schluffe
2026-08-08 19:15:47 +02:00
parent 9bdffd06e4
commit e0c22b6952
3 changed files with 23 additions and 5 deletions
+12 -4
View File
@@ -1,5 +1,6 @@
import { afterEach, beforeEach, expect, test } from "vitest"; import { afterEach, beforeEach, expect, test } from "vitest";
import { loadImage } from "./loadImage.ts"; import { loadImage } from "./loadImage.ts";
import missingTextureSrc from "./missingTexture.svg?url";
class MockImage { class MockImage {
static instances: MockImage[] = []; static instances: MockImage[] = [];
@@ -47,9 +48,16 @@ test("loadImage error", async () => {
const promise = loadImage("missing.png"); const promise = loadImage("missing.png");
const image = MockImage.instances[0]; const image = MockImage.instances[0];
image.onerror!("missing"); image.onerror!("boom");
// errors are logged, but the promise still resolves with the image const placeholder = MockImage.instances[1];
await expect(promise).resolves.toBe(image);
expect(errors).toEqual([["missing"]]); expect(errors).toEqual([["boom"]]);
expect(placeholder.src).toBe(missingTextureSrc);
placeholder.onload!();
// errors are logged, but the promise still resolves
// with a drawable placeholder texture
await expect(promise).resolves.toBe(placeholder);
}); });
+6 -1
View File
@@ -1,3 +1,8 @@
import missingTextureSrc from "./missingTexture.svg?url";
const placeholder = new Image();
placeholder.src = missingTextureSrc;
export function loadImage(src: string): Promise<HTMLImageElement> { export function loadImage(src: string): Promise<HTMLImageElement> {
return new Promise((resolve) => { return new Promise((resolve) => {
const image = new Image(); const image = new Image();
@@ -5,7 +10,7 @@ export function loadImage(src: string): Promise<HTMLImageElement> {
image.onload = () => resolve(image); image.onload = () => resolve(image);
image.onerror = (error) => { image.onerror = (error) => {
console.error(error); console.error(error);
resolve(image); resolve(placeholder);
}; };
image.src = src; image.src = src;
+5
View File
@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16">
<rect width="16" height="16" fill="#ff00ff"/>
<rect width="8" height="8" fill="#000000"/>
<rect x="8" y="8" width="8" height="8" fill="#000000"/>
</svg>

After

Width:  |  Height:  |  Size: 220 B