Start here

HTML-in-canvas lets a <canvas> draw its descendant elements with drawElementImage(). The canvas can transform, clip or filter the drawing, or upload it as a WebGL or WebGPU texture. The elements still take clicks and typing, their text can be selected, and they stay in the accessibility tree. This is the one tutorial on the site. It shows you how to turn the API on and draw one element.

Enable the API

The API is experimental and available only in Chromium browsers. In Chrome 148 or later, on desktop or Android, open chrome://flags/#canvas-draw-element, set it to Enabled and restart the browser. A site can enable it for its visitors with the html-in-canvas origin trial. I test the pages in Chromium 157 on desktop and Chrome 159 on Android.

Detect the API before using it, and keep the page usable as plain HTML without it:

const supported = 'drawElementImage' in CanvasRenderingContext2D.prototype;

Names have changed between Chrome versions. This site uses the names in Chromium 157: the canvas attribute content="drawable" (earlier versions used layoutsubtree, so the demos set both), the drawable attribute on each element to draw, texElementSubImage2D() for WebGL and drawElementImageToTexture() for WebGPU. See the explainer for the current specification.

A minimal page

The frame below runs the page listed under it. The card is a <form> drawn with a rotation and a canvas shadow. The input, the button and text selection work.

Source of the page above

Four steps

  1. Mark the canvas and the element

    Add content="drawable" to the canvas and put the element inside it. The browser lays out the canvas's children and keeps them in the accessibility tree, but doesn't paint them to the screen. Add the drawable attribute to each element you will draw.

    <canvas id="canvas" content="drawable" layoutsubtree>
      <form id="card" drawable> … </form>
    </canvas>
  2. Set the canvas size in device pixels

    canvas.width and canvas.height are separate from the CSS size. On a phone one CSS pixel covers two or three device pixels, so set them from devicePixelContentBoxSize. Otherwise text is blurred.

    new ResizeObserver(([entry]) => {
      const box = entry.devicePixelContentBoxSize[0];
      if (canvas.width !== box.inlineSize) canvas.width = box.inlineSize;
      if (canvas.height !== box.blockSize) canvas.height = box.blockSize;
      canvas.requestPaint();
    }).observe(canvas, { box: 'device-pixel-content-box' });
  3. Draw in the paint event

    The browser fires paint on the canvas when the rendering of a drawable child changes: typed text, a hover style, a focus ring. Call canvas.requestPaint() to request the event yourself, for an animation frame or after a resize.

    canvas.onpaint = () => {
      const dpr = canvas.width / canvas.clientWidth;
      ctx.reset();
      ctx.scale(dpr, dpr);          // draw in CSS pixels from here on
      ctx.translate(24, 30);
      ctx.rotate(-0.04);
      // …
    };
  4. Call drawElementImage()

    It draws the element the way drawImage() draws an image, with the context's current transform, clip, shadow and filter. It also sets the element's hit-test region to the drawn position, so pointer events reach the element where it appears. Pass the width and height: without them the element is drawn in device pixels.

    ctx.drawElementImage(card, 0, 0, card.offsetWidth, card.offsetHeight);

What keeps working and what doesn't

Works without extra code

  • Clicks, hover, focus and typing at the drawn position (2D context only)
  • Tab order, text selection, find-in-page
  • The accessibility tree: the elements are exposed as elements
  • CSS, animations, form state, scrolling inside the element
  • Text stays sharp when scaled, because the element is rasterised at the drawn size
  • getImageData() and toBlob(): the canvas isn't tainted

Not handled for you

  • The element must be a descendant of the canvas. Slots are a workaround
  • An element that isn't drawn is invisible but still focusable (accessibility audit)
  • WebGL and WebGPU drawing doesn't set the hit-test region (Shader CSS)
  • An element has one hit-test region even if it's drawn several times (dom-portal)
  • Cross-origin iframes inside the canvas are drawn blank (Across origins)
  • Browsers without the API: the markup must work as plain HTML

WebGL, hit testing and workers

The other demos on this site use three more calls.

  1. Upload an element as a texture

    In WebGL, texElementSubImage2D() uploads the element into a texture allocated at the element's size. In WebGPU the call is queue.drawElementImageToTexture(). Examples: Shader CSS and a form in a three.js scene.

    gl.bindTexture(gl.TEXTURE_2D, texture);
    gl.texElementSubImage2D(gl.TEXTURE_2D, 0, 0, 0, card);        // WebGL: level, x, y, element
    
    device.queue.drawElementImageToTexture({ source: card }, { texture });   // WebGPU
  2. Set the hit-test region

    When a shader positions the element, the browser doesn't know where it is on screen. Call updateElementGeometry() with a matrix to set the hit-test region. Examples: dom-portal moves the region between two copies, and Physical UI moves it across a mesh.

    canvas.updateElementGeometry(card, {
      canvasTransform: new DOMMatrix().translate(x, y).rotate(angle),
    });
  3. Capture a snapshot for a worker

    captureElementImage() returns an ElementImage, one frame of the element. It's transferable with postMessage(). A worker that holds the canvas (from transferControlToOffscreen()) can draw the snapshot on any number of frames. A snapshot draws only into the canvas it was captured from. Example: OffscreenCanvas.

    const image = canvas.captureElementImage(card);
    worker.postMessage({ image }, [image]);
    // in the worker: ctx.drawElementImage(image, x, y, width, height)

Common errors

Error messages and symptoms, with the cause and the fix for each.

SymptomCauseFix
"Descendants passed to DrawElementImage must have the 'drawable' attribute"The element is missing drawable, or it isn't inside this canvas.Add the attribute. For content that lives elsewhere, use a slot: Just a slot in a canvas.
"No cached paint record for element"The browser hasn't painted the element yet: the first paint came early, the canvas is far off screen, or it is display: none or visibility: hidden.Catch it and call requestPaint() again a frame later. Hide a source canvas with opacity: 0, not visibility.
The element is drawn two or three times too big on a phoneWithout a width and height, drawElementImage(el, x, y) draws in device pixels.Always pass el.offsetWidth, el.offsetHeight. DevTools device emulation doesn't reproduce this. Test on a phone.
Blurred textThe canvas has fewer pixels than it covers on screen.Size it from devicePixelContentBoxSize (step 2 above).
The canvas goes blank when you resize itAssigning canvas.width or height clears it, even to the same value.Assign only when the number changed, then requestPaint().
A child is narrower than you expectedChildren of a drawable canvas shrink to fit their content.Give the element a width.
A <slot> inside the canvas does nothingSlots only project inside a shadow tree.Put the canvas in a shadow root; declarative shadow DOM needs no script. Just a slot in a canvas, plain HTML.
Clicks reach the element at its old position (WebGL, WebGPU)Only 2D drawElementImage() sets the hit-test region.Call updateElementGeometry() each frame. Shader CSS.
Two copies drawn, only one takes clicksAn element has one hit-test region, set by the last draw.Draw the interactive copy last, or set the region to the copy under the pointer. dom-portal.
Tab moves focus to a control that isn't visibleAn element in the canvas that you don't draw is still focusable.Draw it, or mark it inert or hidden. Accessibility audit.
"The source was captured from a different canvas"An ElementImage only draws into its own canvas, or that canvas transferred to a worker.To show DOM in another document, send pixels (ImageBitmap or video) and forward input events back. Across tabs, Transport lab.
A cross-origin iframe in the canvas is blankThe browser leaves out content the page may not read, which keeps the canvas readable.Have the other origin draw its own content and send the frames. Embeddable live cards, slot-view.

Where each call is used

The other pages are experiments: each one asks a question about the API, such as whether a <slot> works inside a canvas, and reports what worked and what did not. They have no reading order. To see a call in use, open one of these experiments and read its code listing.

CallWhat it doesUsed in

Glossary

Terms used on this site.

Drawable canvas
A <canvas content="drawable">. Its children are laid out but not painted to the screen. The canvas draws them.
Drawable element
A descendant of a drawable canvas with the drawable attribute. Only these can be passed to drawElementImage().
paint event
Fired on the canvas when a drawable element's rendering changes, and after requestPaint(). event.changedElements lists the elements that changed.
Paint record
The browser's stored drawing commands for an element. drawElementImage() replays them at the drawn size, so scaled text is sharp. Drawing fails until the browser has recorded one.
Hit-test region (element geometry)
The position the browser uses for an element's clicks, hover, focus ring and caret. 2D drawElementImage() sets it. updateElementGeometry() sets it explicitly.
ElementImage
A snapshot of one element from captureElementImage(). It can be transferred to a worker or another window. It draws only into the canvas it was captured from.
Light DOM, shadow root, slot
The light DOM is the page's own markup. A shadow root is a separate subtree attached to an element. A <slot> in a shadow root renders the host's light-DOM children at that point without moving them. With the canvas in the shadow root, light-DOM children count as its descendants for drawing.
Reprojection
Drawing an element somewhere other than its place in the page: a second position, a worker's canvas, another tab, another origin or a 3D surface.
Input forwarding
Sending pointer and key events from a document that shows an image of an element back to the document that owns it, where they are dispatched on the element.
Read-back-allowed rendering
The browser omits content the page may not read, such as cross-origin iframes and visited-link colours, from the drawing. The canvas is therefore never tainted.
Live checks
The pass/fail tables on each experiment. The tests run in your browser. Many failing rows record a limit of the API. The note in the row gives the reason.

All test results are in FINDINGS.md.