kollagen/cli/collages.ts

95 lines
2.2 KiB
TypeScript
Raw Normal View History

2021-09-15 21:19:03 +02:00
import { CollageModes } from "../src/common/collages.ts";
import {
CanvasRenderingContext2D,
EmulatedCanvas2D,
2021-09-15 21:19:03 +02:00
Image,
} from "https://deno.land/x/canvas/mod.ts";
2021-09-20 22:41:00 +02:00
import { CollageImage } from "../src/common/types.ts";
2021-09-19 11:46:49 +02:00
import { init } from "https://deno.land/x/canvas@v1.3.0/mod.ts";
const canvasKit = await init();
export class ProxyImage implements CollageImage {
private filepath: string | null;
2021-09-19 11:46:49 +02:00
private _image: Image | undefined;
constructor(input: string | Image) {
if (typeof input === "string") {
this.filepath = input;
} else {
this.filepath = null;
this._image = input;
}
2021-09-19 11:46:49 +02:00
}
public get image(): Image {
if (!this._image) {
const image = canvasKit.MakeImageFromEncoded(
Deno.readFileSync(this.filepath!),
);
2021-09-19 11:46:49 +02:00
if (!image) {
throw Error(`Failed loading ${this.filepath}!`);
}
this._image = image;
}
return this._image;
}
public get width(): number {
return this.image.width();
2021-09-15 21:19:03 +02:00
}
2021-09-19 11:46:49 +02:00
public get height(): number {
return this.image.height();
2021-09-15 21:19:03 +02:00
}
}
declare module "https://deno.land/x/canvas/mod.ts" {
interface HTMLCanvasElement {
width: number;
height: number;
2021-09-20 22:41:00 +02:00
getContext(x: "2d"): CanvasRenderingContext2D;
}
}
2021-09-20 22:41:00 +02:00
export class DenoCollageModes extends CollageModes<
CanvasRenderingContext2D,
ProxyImage,
EmulatedCanvas2D
2021-09-20 22:41:00 +02:00
> {
createCanvas(w: number, h: number): EmulatedCanvas2D {
const canvas = canvasKit.MakeCanvas(Math.round(w), Math.round(h));
if (!canvas) {
throw Error("Error initializing canvas.");
}
return canvas;
}
canvasToImage(canvas: EmulatedCanvas2D): PromiseLike<ProxyImage> {
const image = canvasKit.MakeImageFromEncoded(
canvas.toBuffer(),
);
if (!image) {
throw Error("Something went wrong converting canvas to image.");
}
return Promise.resolve(new ProxyImage(image));
}
2021-09-15 21:19:03 +02:00
drawImage(
ctx: CanvasRenderingContext2D,
2021-09-15 21:19:03 +02:00
image: ProxyImage,
sx: number,
sy: number,
sw: number,
sh: number,
dx: number,
dy: number,
dw: number,
dh: number,
): void {
2021-09-19 11:46:49 +02:00
ctx.drawImage(image.image, sx, sy, sw, sh, dx, dy, dw, dh);
2021-09-15 21:19:03 +02:00
}
}
export const denoCollageModes = new DenoCollageModes();