Improve loadImage to use a placeholder and prevent game crash
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import { afterEach, beforeEach, expect, test } from "vitest";
|
||||
import { loadImage } from "./loadImage.ts";
|
||||
import missingTextureSrc from "./missingTexture.svg?url";
|
||||
|
||||
class MockImage {
|
||||
static instances: MockImage[] = [];
|
||||
@@ -47,9 +48,16 @@ test("loadImage error", async () => {
|
||||
const promise = loadImage("missing.png");
|
||||
const image = MockImage.instances[0];
|
||||
|
||||
image.onerror!("missing");
|
||||
image.onerror!("boom");
|
||||
|
||||
// errors are logged, but the promise still resolves with the image
|
||||
await expect(promise).resolves.toBe(image);
|
||||
expect(errors).toEqual([["missing"]]);
|
||||
const placeholder = MockImage.instances[1];
|
||||
|
||||
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);
|
||||
});
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
import missingTextureSrc from "./missingTexture.svg?url";
|
||||
|
||||
const placeholder = new Image();
|
||||
placeholder.src = missingTextureSrc;
|
||||
|
||||
export function loadImage(src: string): Promise<HTMLImageElement> {
|
||||
return new Promise((resolve) => {
|
||||
const image = new Image();
|
||||
@@ -5,7 +10,7 @@ export function loadImage(src: string): Promise<HTMLImageElement> {
|
||||
image.onload = () => resolve(image);
|
||||
image.onerror = (error) => {
|
||||
console.error(error);
|
||||
resolve(image);
|
||||
resolve(placeholder);
|
||||
};
|
||||
|
||||
image.src = src;
|
||||
|
||||
@@ -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 |
Reference in New Issue
Block a user