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, Image,
} from "https://deno.land/x/canvas/mod.ts"; } from "https://deno.land/x/canvas/mod.ts";
import { CollageContext, CollageImage } from "../src/common/types.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 { export class ProxyImage implements CollageImage {
private image: Image; private filepath: string;
public readonly height: number; private _image: Image | undefined;
public readonly width: number;
constructor(image: Image) { constructor(filepath: string) {
this.image = image; this.filepath = filepath;
this.width = image.width();
this.height = image.height();
} }
public get(): Image { public get image(): Image {
return this.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, dw: number,
dh: number, dh: number,
): void { ): 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); shuffledFiles.splice(25, shuffledFiles.length - 25);
} }
const images: ProxyImage[] = (await Promise.all( const images: ProxyImage[] = shuffledFiles.map((file) => new ProxyImage(file));
shuffledFiles.map(async (imageURL) =>
canvasKit.MakeImageFromEncoded(await Deno.readFile(imageURL))
),
)).map((image) => new ProxyImage(image!));
const modes = new DenoCollageModes(); const modes = new DenoCollageModes();