Server-side PNG renderer for Quickdraw documents. Takes a snapshot from
store.getSnapshot() and returns a PNG Buffer — with no browser, no
Chromium, no Puppeteer/Playwright, no DOM. The drawing backend is
skia-canvas (native Skia), and
every shape is painted by the core engine's own drawShape(), so server
output tracks the editor instead of reimplementing it.
import { renderPng } from '@quickdrawjs/headless'
import { writeFile } from 'node:fs/promises'
const png = await renderPng(snapshot, {
width: 1920,
height: 1080,
theme: 'light',
background: 'transparent',
fit: 'content',
padding: 40,
})
await writeFile('output.png', png) // png is a Node.js BufferRequires Node.js 18+. skia-canvas ships prebuilt binaries for macOS,
Linux and Windows — no build step on supported platforms (see its docs for
missing-lib errors on minimal Linux images). The package also runs
unmodified under Bun 1.x (same code paths, byte-identical PNG output —
verified against Node on shapes, text, images, themes and error codes).
npm install @quickdrawjs/headlessCore version note: this package reuses the core drawing engine and needs
@quickdrawjs/core with the server-renderer exports (setShapePlatform,
sortShapesForRender, fontStackOf, setFontStacks — proposed upstream,
unreleased at the time of writing). Until a release includes them, point the
dependency at a build that has them:
# interim: install core from a tarball of a branch carrying the seam,
# then install this package from git
npm install /path/to/quickdrawjs-core-0.3.0.tgz
npm install github:calumk/quickdrawjs-headlessFrom a checkout of this repo:
npm install
npm run example # render examples/board.json -> examples/board.png
npm test # vitest, plain Node env (no jsdom)snapshot is the object returned by store.getSnapshot():
{ document: { store: { id: record } } }. Asset records for embedded images
must be included (they are, when the snapshot comes from the same store).
| Option | Default | Meaning |
|---|---|---|
width |
1920 |
Output pixels, integer 1–8192. |
height |
1080 |
Output pixels, integer 1–8192. |
theme |
'light' |
'light' or 'dark'. |
background |
'transparent' |
'transparent', 'theme' (paper color), or any CSS color ('#ff0000', 'white', …). |
fit |
'content' |
'content' fits every shape; 'viewport' fits viewport exactly. |
viewport |
— | { x, y, w, h } page-space rect. Required with fit: 'viewport', rejected otherwise. |
padding |
40 |
Output-pixel margin around the fitted rect (0 allowed). |
The promise resolves after every image asset is decoded and all drawing
is complete. Output dimensions always equal width × height.
- Content fit (default): the union of all shape bounds (rotation included), expanded by a 48-page-unit safety margin so strokes, arrowheads and shadows are never clipped, is scaled and centered into the padded output area. Content-fit zoom is capped at 8× so single-point drawings stay sensible. Negative coordinates, huge drawings and rotated shapes just work.
- Explicit viewport: the given page-space rect is fitted into the padded output area, even when shapes extend beyond it (they clip at the rect edge, as in the editor).
- Empty document (no shapes): renders a blank image — background only — at the exact requested size. This is the documented policy, not an error.
- Invalid input throws
RenderError(anErrorwith a stablecode):
| Code | Cause |
|---|---|
INVALID_SNAPSHOT |
Not a { document: { store } } envelope. |
INVALID_DIMENSIONS |
Bad width/height, or over 48M output pixels. |
INVALID_THEME |
Not 'light'/'dark'. |
INVALID_BACKGROUND |
Not 'transparent'/'theme'/valid CSS color. |
INVALID_FIT / INVALID_VIEWPORT / INVALID_PADDING |
Bad fit, viewport or padding. |
INVALID_COMPAT |
Bad compat option value. |
CORE_TOO_OLD |
Installed core lacks the server-renderer exports (strict mode). Upgrade core or use compat: 'monkeypatch'. |
SNAPSHOT_TOO_LARGE |
Over 100k records. |
ASSET_MISSING |
Image shape whose asset record is absent. |
ASSET_EXTERNAL_URL |
http(s)/non-data URI — never fetched. |
ASSET_INVALID |
Not an embedded data:image/… asset. |
ASSET_DECODE_FAILED |
Bytes Skia cannot decode. |
ASSET_TOO_LARGE / TOO_MANY_IMAGES |
Over 48MB per asset / 200 images. |
FONT_INVALID |
Bad family name or file list in registerFontFamily. |
FONT_FILE_MISSING |
A registered font file does not exist. |
External image URLs are never fetched — embed images as data URLs (exactly what the editor stores) to render them.
Everything the editor draws from the document: freehand pen strokes (with
pressure), highlighters, rectangles/ellipses/triangles/diamonds/hexagons/
stars/clouds, lines and bent arrows, text, sticky notes, embedded images —
including rotation, scaling, opacity, dash styles, patterned/semi/solid fills
and shadows. Stacking matches the editor: highlighters paint beneath other
shapes, each group ordered by z-index (shared sortShapesForRender helper,
so the two cannot drift). Editor-only chrome — selection handles, hover
states, the text editor, laser-pointer scribbles — is not in the snapshot and
is never drawn.
- Fonts. The hand face (
Quickdraw Hand/ Libre Baskerville, OFL 1.1) registers with Skia before measuring, so its wrapping and layout match the browser to 0.1px on probe strings. Thesans/serif/monostacks use system fonts as upstream (bundling them would silently restyle existing boards) — see "Custom fonts" to pin those down. Server packaging notes (one merged TTF, single-word alias heading the stack): skia-canvas cannot shape from woff2, multi-word family names never match inside font lists, and for a multi-file family only the last file serves text. Antialiasing differs slightly (Skia vs CoreGraphics/DirectWrite), so server text rasterizes a touch lighter than CoreText at the same weight. - Highlighters on transparency. Multiply blending is designed for paper;
on a transparent background the band composites against nothing, so it reads
denser than on the board. Prefer
background: 'theme'for paper-faithful highlights.
The core engine needed one small, backward-compatible seam
(packages/core/src/shapes.js, editor.js, index.js):
setShapePlatform({ Path2D, measureCtx, tileCanvas })— explicit backend injection. The browser never calls it, so its path is byte-for-byte unchanged; nowindow/document/Path2D/Imagemonkey-patching. Only stateless pieces are shared (path class, measure context, tile factory). Per-render state — decoded images, hatch-pattern cache — travels ondrawShape'sopts({ images, patternCache, Path2D }), so concurrent renders of different snapshots cannot contaminate each other.sortShapesForRender()— the highlighter-beneath ordering, now shared byEditor.shapesSorted()and the headless pass.drawShape()honorsopts.images(pre-decoded bitmaps, bypassing the browserImageloader) and per-render pattern caches.
The headless pass itself (packages/headless/src/):
render.js— validate →Store.loadSnapshot→ sort → decode assets → viewport transform →drawShapeloop → PNGBuffer.platform.js— installs the Skia backend once (idempotent).fonts.js— registers the bundled woff2 faces viaFontLibrary.assets.js— data-URL-only decoding with limits; clear errors otherwise.
The four style ids (draw, sans, serif, mono) are pluggable. A
developer remaps an id to any CSS stack once at startup, in the browser and
on the server alike:
import { setFontStacks } from '@quickdrawjs/core'
setFontStacks({
sans: "'Inter', system-ui, sans-serif",
mono: "'JetBrains Mono', ui-monospace, monospace",
})Measurement, drawing, the editing textarea and the toolbar previews all
resolve through the override; resetFontStacks() restores the bundled
faces. New ids work too: any font prop value resolves through the same
registry.
Server-side, register the files behind the names before rendering:
import { registerFontFamily } from '@quickdrawjs/headless'
registerFontFamily('Inter', ['/fonts/inter-500.ttf'])Three rules (skia-canvas quirks): TTF/OTF files, not woff2; one merged file
per family (a second file shadows the first); single-word family names —
a spaced name never matches inside a font list, so alias it, e.g. stack
"'MySans', 'My Sans', sans-serif" with both names registered against the
same files. In the browser, load the same faces with @font-face so both
sides shape identical outlines. Like the stacks, registration is
process-global: configure once at startup, not per request.
The default (compat: 'strict') needs a core release carrying the
server-renderer exports and throws CORE_TOO_OLD without them. Against a
stock core — including today's published @quickdrawjs/core — pass
compat: 'monkeypatch' to render anyway, via explicitly opt-in shims:
- missing browser globals (
Path2D,OffscreenCanvas,Image,document) are defined from Skia equivalents, only when absent; - helpers missing from core's exports are deep-imported from its files;
- paint order mirrors released core (highlighter-beneath, rest by z);
- the bundled hand face is pointed at through the mutable
FONTSobject.
Same shapes, same validation and error codes — with three documented differences: released-core (not layered) paint order, one process-wide image/pattern cache instead of per-render isolation, and no custom font stacks (those need the seam). The example script falls back to it automatically with a warning.
npm test # 38 tests, Node env (no jsdom)Coverage: blank snapshots, every shape type, z-order, highlighter-beneath,
wrapped text + notes, embedded images (pixels verified, not just “a buffer
was returned”), rotation/scale, pattern fills, negative coordinates,
content-fit centering, transparency, both themes, exact dimensions,
deterministic re-renders, concurrent renders, invalid-input codes — and a
clean-process test proving window/document/OffscreenCanvas/Image/
Path2D are all absent during rendering — plus the compat suite (mode
resolution, shims, shimmed image warming, monkeypatch renders and
strict/monkeypatch parity where the installed core allows it). The suite
runs green against both patched and stock core releases.
examples/ holds a generator, a realistic 12-record document and its render:
node examples/make-board.mjs # regenerate board.json
node examples/basic.mjs # render board.json -> board.pngbasic.mjs is the clean-install path: load snapshot JSON → renderPng →
write PNG.