feat(utils): image loader
This commit is contained in:
52
src/utils/loadImages.ts
Normal file
52
src/utils/loadImages.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user