forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiB5fcd955Burak Boduroğlu2 months ago730 commits

drawing-file.ts41 lines, 2.0 KiBHistoryRawDownload
1import { PAPER_CELL, paintPaper, parseScene, type BgKind, type DrawScene } from "./draw-stroke";
2import { embedPngText, extractPngText } from "./png-meta";
3
4/** tEXt keyword under which a drawing's editable stroke JSON is stored inside its PNG. */
5const DRAWING_KEYWORD = "hezarfen-drawing";
6
7/** Read the editable scene back out of a drawing PNG's bytes, or null for a plain image. */
8export function pngBytesToScene(bytes: Uint8Array): DrawScene | null {
9 return parseScene(extractPngText(bytes, DRAWING_KEYWORD));
10}
11
12/**
13 * Flatten a transparent pad canvas onto white and encode it. The pad layer is
14 * transparent so the eraser can cut through it; without the white fill dark
15 * strokes would vanish on dark backgrounds once exported. DOM glue — needs a
16 * document.
17 */
18export function canvasToImageBlob(source: HTMLCanvasElement, mime: string, bg: BgKind = "none"): Promise<Blob | null> {
19 const out = document.createElement("canvas");
20 out.width = source.width;
21 out.height = source.height;
22 const oc = out.getContext("2d");
23 if (!oc) return Promise.resolve(null);
24 oc.fillStyle = "#ffffff";
25 oc.fillRect(0, 0, out.width, out.height);
26 // Paper goes between the white fill and the transparent stroke layer, so erased
27 // spots (transparent in `source`) reveal the ruling instead of the strokes.
28 const dpr = window.devicePixelRatio || 1;
29 paintPaper(oc, bg, out.width, out.height, PAPER_CELL * dpr);
30 oc.drawImage(source, 0, 0);
31 return new Promise((resolve) => out.toBlob(resolve, mime));
32}
33
34/** Encode the pad as a PNG File that both displays as an image and carries its editable scene. */
35export async function sceneToPngFile(source: HTMLCanvasElement, scene: DrawScene, name: string): Promise<File> {
36 const blob = await canvasToImageBlob(source, "image/png", scene.bg ?? "none");
37 if (!blob) throw new Error("canvas PNG export failed");
38 const bytes = new Uint8Array(await blob.arrayBuffer());
39 const withScene = embedPngText(bytes, DRAWING_KEYWORD, JSON.stringify(scene));
40 return new File([withScene], name, { type: "image/png" });
41}