lazy load images in deno

This commit is contained in:
Tomáš Mládek 2021-09-19 11:46:49 +02:00
parent 7919e4fb7d
commit 7e6a761363
2 changed files with 26 additions and 15 deletions

View file

@ -4,20 +4,35 @@ import {
Image,
} from "https://deno.land/x/canvas/mod.ts";
import { CollageContext, CollageImage } from "../src/common/types.ts";
import { init } from "https://deno.land/x/canvas@v1.3.0/mod.ts";
const canvasKit = await init();
export class ProxyImage implements CollageImage {
private image: Image;
public readonly height: number;
public readonly width: number;
private filepath: string;
private _image: Image | undefined;
constructor(image: Image) {
this.image = image;
this.width = image.width();
this.height = image.height();
constructor(filepath: string) {
this.filepath = filepath;
}
public get(): Image {
return this.image;
public get image(): Image {
if (!this._image) {
const image = canvasKit.MakeImageFromEncoded(Deno.readFileSync(this.filepath))
if (!image) {
throw Error(`Failed loading ${this.filepath}!`);
}
this._image = image;
}
return this._image;
}
public get width(): number {
return this.image.width();
}
public get height(): number {
return this.image.height();
}
}
@ -39,6 +54,6 @@ export default class BrowserCollageModes
dw: number,
dh: number,
): void {
ctx.drawImage(image.get(), sx, sy, sw, sh, dx, dy, dw, dh);
ctx.drawImage(image.image, sx, sy, sw, sh, dx, dy, dw, dh);
}
}

View file

@ -62,11 +62,7 @@ if (shuffledFiles.length > 25) {
shuffledFiles.splice(25, shuffledFiles.length - 25);
}
const images: ProxyImage[] = (await Promise.all(
shuffledFiles.map(async (imageURL) =>
canvasKit.MakeImageFromEncoded(await Deno.readFile(imageURL))
),
)).map((image) => new ProxyImage(image!));
const images: ProxyImage[] = shuffledFiles.map((file) => new ProxyImage(file));
const modes = new DenoCollageModes();