<canvas-text>

API Reference

Complete documentation for the <canvas-text> custom element.

Element Overview

<canvas-text> composites z-ordered image and text layers onto an internal <canvas>. Text layers are rasterized via render-tag; image layers are drawn with ctx.drawImage. The element owns the canvas; consumers interact through slots, attributes, properties, and methods.

The element is light-DOM only — no Shadow DOM. Slotted HTML remains accessible to screen readers. See Accessibility.

Install: npm install @profpowell/canvas-text render-tag

Slot Grammar

Children are identified by their slot attribute. Each slot maps to a z-order position in the composite stack. See Layered demo and Z-order demo.

Slot Type z-order Notes
background image (<img>) 0 Bottom of the stack. Height auto-derives from this image's aspect ratio when height is omitted.
background-N image (<img>) N (integer) Integer suffix; higher N paints above lower N.
text-N rich HTML N (integer) Rendered above background-N at the same N. Use padding-top for vertical placement — position:absolute is not supported by render-tag.
(no slot=, default slot) rich HTML ∞ Always painted last, on top of all other layers. Also used by compose="text-only".

Tie-breaking: At the same N, the image (background-N) paints before the text (text-N).

Image layers: The element calls img.decode() before drawing. Add crossorigin="anonymous" on <img> elements served from CORS-enabled origins, otherwise toBlob() / toDataURL() will throw a tainted-canvas error.

Attributes

All attributes are observed; mutations trigger a coalesced re-render.

Attribute Type Default Description
width number 600 Canvas width in CSS pixels.
height number auto Canvas height in CSS pixels. If omitted and a background image is present, height is derived from the image's intrinsic aspect ratio. Otherwise auto from text layout.
theme "inherit" | "none" | "inline" "inherit" Theme bridge mode. See Theme Bridge.
compose "slots" | "text-only" "slots" "slots" runs the full layer pipeline. "text-only" skips slot scanning and renders the default-slot HTML as a single text layer — simpler and faster for plain text.
format "png" | "jpeg" | "webp" "png" Default MIME type used by toBlob() and toDataURL() when called without an explicit type argument.
dpr number | "auto" "auto" Device pixel ratio. "auto" reads window.devicePixelRatio. Override to a fixed value (e.g. "2") for consistent output regardless of screen.
accuracy "default" | "balanced" "default" Passed through to render-tag. "balanced" trades some speed for improved layout accuracy.
lang string host lang Reserved for future bidi/CJK hints. Currently forwarded to render-tag but not processed.
alt string — Plain-text description. Applied as aria-label on the canvas and suppresses the visually-hidden fallback DOM so AT reads the alt only.

Properties

Property Type Description
html (setter) string Replaces the host's unslotted (default-slot) children with the provided HTML string. Slotted layers (background, text-N) are untouched. Setting this property triggers a render.
html (getter) string Serialized HTML of the current unslotted children.

Usage

const el = document.querySelector('canvas-text'); // Set content imperatively el.html = '<strong>Updated!</strong>'; // Read current unslotted HTML console.log(el.html);

Methods

Method Signature Description
getCanvas() () => HTMLCanvasElement | null Returns the internal canvas element. Returns null before the element is connected to the DOM.
toDataURL() (type?: string, quality?: number) => string Synchronous export. Returns a base64-encoded data URL. Reflects the last completed render — call await el.render() first if you need fresh pixels after a mutation.
toBlob() (type?: string, quality?: number) => Promise<Blob> Async export. Same pixel source as toDataURL(). Preferred for large images (avoids holding base64 in memory). See Export demo.
render() () => Promise<void> Force a render; resolves after paint. Async because image layers must decode() before drawing. Useful in tests and after imperative mutations.

Notes

Both toDataURL() and toBlob() reflect the canvas as of the last completed render. If you have just mutated attributes or slots:

// Wait for the next render before exporting await el.render(); const blob = await el.toBlob('image/png');

Cross-origin images without crossorigin="anonymous" will taint the canvas and cause toBlob() / toDataURL() to throw. The canvas-text:layer-error event fires for per-layer failures.

Events

All events bubble and are dispatched on the <canvas-text> element.

Event Detail payload When
canvas-text:rendered { width: number, height: number, durationMs: number } After each successful render cycle completes. durationMs is wall-clock time including image decode.
canvas-text:error { error: Error } Render aborted — e.g. render-tag throws on every text layer. Composition did not produce output.
canvas-text:layer-error { slot: string, error: Error } A single layer failed (e.g. broken image, render-tag error on one layer). Composition continues with the remaining layers. slot is the slot name of the failing layer.

Usage

const el = document.querySelector('canvas-text'); el.addEventListener('canvas-text:rendered', ({ detail }) => { console.log(`Rendered ${detail.width}x${detail.height} in ${detail.durationMs}ms`); }); el.addEventListener('canvas-text:layer-error', ({ detail }) => { console.warn(`Layer "${detail.slot}" failed:`, detail.error); });

Theme Bridge

When theme="inherit" (default), the element reads a small allowlist of computed CSS properties from the host element and inlines them on each text layer before it is passed to render-tag. This lets Vanilla Breeze themes (or any tokenized CSS system) automatically flow into the rasterized output.

The bridge runs once per render. Theme changes after first render are not re-applied in v0.1 — re-render is triggered by attribute/slot mutations, not by CSS changes.

Allowlist

CSS property Notes
colorText color.
font-familyLonghand only — font: shorthand is not parsed by render-tag.
font-size
font-weight
font-style
line-height
letter-spacing
text-align
background-color

Modes

Value Behavior
theme="inherit" (default) Copy allowlist from getComputedStyle(host). Inline as a wrapper style= around each text layer's HTML before render-tag.
theme="none" Pass layers to render-tag with its built-in defaults only. No styles from the host.
theme="inline" Assume the author has already inlined all styles on the slotted HTML. Pass through unchanged.

See Theme Bridge demo for a side-by-side comparison.

CSS Support Inside Layers

Text layers are rasterized by render-tag, which implements a limited CSS surface — it is a layout/raster engine, not a full browser. Authors who try to use unsupported properties will get no effect or unexpected layout.

Supported

PropertyNotes
color
background-color
font-familyLonghand. Web fonts must be loaded before render.
font-size
font-weight
font-style
line-height
letter-spacing
text-align
padding / marginUse padding-top for vertical positioning.
borderBasic block borders.
-webkit-text-strokeText stroke width and color.
Basic block flowBlock and inline elements, normal flow.

Not Supported

PropertyWorkaround
position, top / right / bottom / left, inset Use padding-top / padding-left to offset text within the full-canvas layer box.
Flexbox (display:flex, align-items, justify-content) Use block flow with padding.
CSS Grid Use block flow with padding.
CSS transforms (transform, rotate, etc.) Not available.
CSS custom properties (var(--x)) inside layer HTML Resolve values before setting them on the slotted element — render-tag does not resolve CSS variables.

font: shorthand caveat

The font: shorthand (e.g. font: bold 48px Impact) is not parsed by render-tag. Use the longhands font-size, font-weight, and font-family separately:

<!-- Wrong: shorthand silently fails --> <div style="font: bold 48px Impact;">TEXT</div> <!-- Correct: use longhands --> <div style="font-size: 48px; font-weight: bold; font-family: Impact, sans-serif;">TEXT</div>

Accessibility

The slotted HTML stays in the light DOM, visually hidden via clip-path: inset(50%), so screen readers consume it as normal HTML. The canvas element is marked aria-hidden="true".

Behavior with and without alt

alt set?AT behavior
No (default) Slotted children are AT-readable as normal light DOM. Canvas is aria-hidden. Background <img> alt values are also available.
Yes Canvas gets aria-label set to the alt value. The visually-hidden fallback is suppressed so AT reads the alt string only — no double announcement.

See Accessibility demo. Axe-core must pass clean against all shipped examples.

Gotchas

Pragmatic notes about real interactions between render-tag, the theme bridge, and common authoring patterns. Read this before opening an issue.

Theme bridge auto-skips for self-styled layers

The theme bridge inherits host CSS tokens onto rich-text layers — but it also detects "self-styled" layers and skips the wrapper for them. A layer is treated as self-styled when its inline style attribute declares any of: font-family, font-size, font-weight, font-style, color, or -webkit-text-stroke. This matches the meme/OG-card pattern where every text layer is fully styled, and prevents the wrapper's inherited font-family from disrupting render-tag's -webkit-text-stroke rendering (which used to produce thin slashes through closed-bowl glyphs like P, B, M, X).

In short: you don't have to set theme="none" on stylized meme layers — the bridge handles it for you.

Layer patternBridge behavior under theme="inherit"
Default-slot text (no inline style): <p>Hello</p> Wrapped — picks up host color/font/etc.
Slotted layer with only layout styles: <div slot="text-1" style="padding-top:20px">… Wrapped — author hasn't claimed typographic ownership.
Slotted layer with typographic styles: <div slot="text-1" style="font-size:52px; color:white; -webkit-text-stroke:2px black">… Skipped — render-tag uses its defaults and the author's explicit declarations.

To force-skip the wrapper for any reason, use theme="none". To trust your own inline styles without further wrapping, use theme="inline".

Also note: line-height is intentionally absent from the bridge's allowlist. getComputedStyle resolves line-height: 1.6 to an absolute pixel value (e.g. 25.6px) which would inherit verbatim into 52px-font layers and collapse their baseline. If you need specific leading inside a layer, set line-height on the layer itself.

position: absolute doesn't work inside layers

render-tag is a layout/raster engine, not a full browser. position, top/right/bottom/left, inset, and flexbox alignment are not honored inside a layer's HTML. For vertical placement, use padding-top against the full canvas height. See CSS Support Inside Layers.

font: shorthand is not parsed

Use font-size, font-weight, font-family as individual longhand declarations. The shorthand form is silently ignored by render-tag.

Cross-origin images taint the canvas

Set crossorigin="anonymous" on any <img> you intend to composite, and serve the image from a CORS-enabled origin. Without it, toBlob() / toDataURL() will throw a SecurityError at export time.

Export reflects the last completed render

toDataURL is synchronous; toBlob is async. Both read the current canvas pixels. If you've just mutated attributes or slots, the next render is queued on the upcoming animation frame — you need to await el.render() (or listen for canvas-text:rendered) before reading.

Placement (v0.2)

Any layer accepts placement attributes to control its position within the canvas:

Attribute Values Default
place top-left … bottom-right, center, plus aliases top / bottom / left / right center
offset-x / offset-y px (40) or % (10%); +x→right, +y→down 0
fit cover | contain | fill (images only) cover for background; contain for image-N

New slot: image-N is a placed image (sized to itself), distinct from background (full-bleed). background now defaults to fit="cover" (was an unconditional stretch); pass fit="fill" for the old behavior.

<canvas-text width="600" height="600"> <img slot="background" src="banner.png" fit="cover"> <h2 slot="text-1" place="top-center" offset-y="40">ProfPowell</h2> <img slot="image-1" src="a.png" place="bottom-center" offset-x="-80" offset-y="-40"> <img slot="image-2" src="b.png" place="bottom-center" offset-y="-40"> <img slot="image-3" src="c.png" place="bottom-center" offset-x="80" offset-y="-40"> </canvas-text>

Presets (v0.2)

preset="meme|badge|banner|caption" applies sensible placement and typography defaults. Explicit per-layer attributes always win.

Fonts

<canvas-text> waits for document.fonts.ready before drawing, so webfonts never render as fallback. Load OFL faces (e.g. Anton) yourself via @font-face / Google Fonts.

Known Limitations (v0.1)