export function loadImage(src: string): Promise { 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 { return Promise.all(srcs.map(loadImage)); } export class ImageLoader { private images: Map = new Map(); private loadPromise: Promise | null = null; constructor(imageSources: Record) { this.loadPromise = this.loadAll(imageSources); } private async loadAll(imageSources: Record): Promise { 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 { 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; } }