Files
pihkaal-me/src/utils/loadImages.ts
2025-12-13 18:55:18 +01:00

53 lines
1.3 KiB
TypeScript

export function loadImage(src: string): Promise<HTMLImageElement> {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = reject;
img.src = src;
});
}
export async function loadImages(
...srcs: string[]
): Promise<HTMLImageElement[]> {
return Promise.all(srcs.map(loadImage));
}
export class ImageLoader {
private images: Map<string, HTMLImageElement> = new Map();
private loadPromise: Promise<void> | null = null;
constructor(imageSources: Record<string, string>) {
this.loadPromise = this.loadAll(imageSources);
}
private async loadAll(imageSources: Record<string, string>): Promise<void> {
const entries = Object.entries(imageSources);
const images = await loadImages(...entries.map(([_, src]) => src));
entries.forEach(([key], index) => {
this.images.set(key, images[index]);
});
}
public async ready(): Promise<void> {
await this.loadPromise;
}
public get isReady(): boolean {
return this.loadPromise !== null && this.images.size > 0;
}
public get(key: string): HTMLImageElement | undefined {
return this.images.get(key);
}
public require(key: string): HTMLImageElement {
const image = this.images.get(key);
if (!image) {
throw new Error(`Image not found: ${key}`);
}
return image;
}
}