From 8bdd3158ea17f8a1e3257ec26b4676aba33fbb4f Mon Sep 17 00:00:00 2001 From: Tangent Wantwight Date: Fri, 12 Jan 2024 20:46:09 -0500 Subject: [PATCH] Factor out some html helpers --- island.ts | 11 ++++------- lib/html.ts | 22 ++++++++++++++++++++++ 2 files changed, 26 insertions(+), 7 deletions(-) create mode 100644 lib/html.ts diff --git a/island.ts b/island.ts index 43e0f6d..f2c79f7 100644 --- a/island.ts +++ b/island.ts @@ -1,17 +1,14 @@ +import { canvas2d } from "./lib/html"; + const BLOWUP = 4; const WIDTH = 240; const HEIGHT = 135; export function IslandApplet() { - const canvas = Object.assign(document.createElement("canvas"), { + const [canvas, cx] = canvas2d({ width: WIDTH * BLOWUP, height: HEIGHT * BLOWUP, - } satisfies Partial); - - const cx = canvas.getContext("2d"); - if (!cx) { - throw new Error("2D rendering context not supported"); - } + }); cx.scale(BLOWUP, BLOWUP); cx.fillStyle = "red"; diff --git a/lib/html.ts b/lib/html.ts new file mode 100644 index 0000000..92c34c7 --- /dev/null +++ b/lib/html.ts @@ -0,0 +1,22 @@ +export function h( + name: Name, + props: Partial, + ...children: Node[] +): HTMLElementTagNameMap[Name] { + const element = Object.assign(document.createElement(name), props); + element.append(...children); + return element; +} + +export function canvas2d( + props: Partial +): [HTMLCanvasElement, CanvasRenderingContext2D] { + const canvas = h("canvas", props); + + const cx = canvas.getContext("2d"); + if (!cx) { + throw new Error("2D rendering context not supported"); + } + + return [canvas, cx]; +}