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
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:
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
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 |
|---|---|
color | Text color. |
font-family | Longhand 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
| Property | Notes |
|---|---|
color | |
background-color | |
font-family | Longhand. Web fonts must be loaded before render. |
font-size | |
font-weight | |
font-style | |
line-height | |
letter-spacing | |
text-align | |
padding / margin | Use padding-top for vertical positioning. |
border | Basic block borders. |
-webkit-text-stroke | Text stroke width and color. |
| Basic block flow | Block and inline elements, normal flow. |
Not Supported
| Property | Workaround |
|---|---|
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:
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 pattern | Bridge 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.
Presets (v0.2)
preset="meme|badge|banner|caption" applies sensible placement and typography defaults. Explicit per-layer attributes always win.
- meme — Impact/Anton, white fill + black stroke, uppercase;
text-1→top,text-2→bottom. - badge —
image-1avatar centered up top;text-1/text-2name/title; extraimage-Nauto-arranged in a centered row. - banner —
text-1name up top; allimage-Nin a centered bottom row. - caption — flattens a semantic
<figure><img><figcaption></figcaption></figure>into a full-width bottom caption band (the band background is the figcaption's ownbackground-color).
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)
- Cross-origin images: Without
crossorigin="anonymous", images will taint the canvas;toBlob()/toDataURL()will throw. Serve images from a CORS-enabled origin. - Theme re-render: Theme changes after first render are not re-observed. Mutate an attribute or slot to force a re-render with the new theme.
- No SSR / node-canvas: The element requires a browser environment with
HTMLCanvasElement. - No interactive editing: No caret, text selection, or cursor support.
- render-tag CSS surface: See CSS Support Inside Layers — position, flex, grid, transforms, and CSS variables are not supported inside layer HTML.
- render-tag version: Pinned to
^0.1.7.render-tagis pre-1.0; API may change.