Slotting DOM into a canvas

HTML-in-canvas only draws elements that are descendants of the <canvas>. A shadow root lets the canvas live in the shadow tree while your content stays in the light DOM: each named <slot> inside the canvas pulls in the matching child, and that child is drawn with drawElementImage(). I didn't want to put all of my content inside the canvas, so this was the first thing I tried. The text below is ordinary DOM. Select it, tab to the input and type.

Light-DOM content

This card is a child of <canvas-slot>, not of the canvas. A <slot name="note"> inside the shadow canvas reprojects it.
“The slot is display: contents, so the slotted element becomes the canvas's layout child.”
The smallest complete page that does this

Re-slotting: move content in and out of the canvas

An element is drawn by the canvas when two things are true: it's a child of <canvas-slot>, and it has a slot="…" name. Make both true to move it in. Undo them to move it out. It's the same element the whole time, so what you typed into it and its event listeners come along.

// Move in
card.setAttribute('slot', 'current');
stage.append(card);              // stage is the <canvas-slot>

// Move out
card.removeAttribute('slot');
shelf.append(card);              // anywhere outside the <canvas-slot>

// Draw whatever is in the slot. This runs again by itself after every change.
stage.onrender = ({ draw }) => draw('current', 12, 12);

Try it. Tap a card to move it into the canvas, and tap it in the canvas to send it back. Type in the Kiwi input before and after.

The complete page for this demo (paste it into a blank .html file)

If the element is already a child of <canvas-slot>, changing only its slot attribute is enough: an element with no slot name isn't drawn and not shown, and one with a name is. If you draw the same element more than once, draw the copy people should interact with last, because the last draw decides where taps land.

Content that lives outside the element

Content written anywhere on the page can be drawn in the canvas, but something has to bring it in. The browser rule is that a <slot> only takes children of the element that owns the shadow root, and HTML-in-canvas only draws elements that are laid out inside the canvas. So an element elsewhere on the page is out of reach until it becomes a child of that element, or until that element is made big enough to already contain it. These are all the routes I tried, including the ones that fail. Each is checked live in the table further down.

The complete page for this demo, using route 3 (paste it into a blank .html file)
  1. Just give it a slot name ✗ does nothing

    This is the markup I hoped would work. The slot is in <canvas-slot>'s shadow root, and the footer's child isn't a child of <canvas-slot>, so it's never assigned. It stays where it is as ordinary HTML.

    <canvas-slot id="stage"></canvas-slot>
    <footer>
      <aside slot="promo">…</aside>      <!-- not a child of canvas-slot: ignored -->
    </footer>
  2. Move it in yourself ✓ works

    It takes two lines. The element is moved (it isn't copied). This is what the re-slotting demo above does.

    const stage = document.getElementById('stage');
    const promo = document.querySelector('footer aside');
    
    promo.setAttribute('slot', 'promo');
    stage.append(promo);                          // in
    
    promo.removeAttribute('slot');
    document.querySelector('footer').append(promo);   // and back out
  3. Point <canvas-slot> at it: from="…" ✓ works

    New in canvas-slot.js. from is a CSS selector; whatever matches is brought in when the page loads, and its slot name is its slot attribute or else its id. In script, stage.adopt(element) does the same for one element and stage.release(element) puts it back exactly where it was (a comment node marks the spot). It's route 2 with a selector, because there's no way to draw the element without moving it. It uses moveBefore() where the browser has it, so focus and running animations survive the move.

    <canvas-slot id="stage" from="#promo"></canvas-slot>
    <footer>
      <aside id="promo">…</aside>
    </footer>
    
    <script type="module">
      const stage = document.getElementById('stage');
      stage.onrender = ({ draw }) => draw('promo', 16, 16);
    
      stage.release(document.getElementById('promo'));   // back to the footer
      stage.adopt('#promo');                             // in again
    </script>

    Routes 2 and 3 have a cost: the element has a new parent while it is in the canvas, so CSS that reached it through its old ancestors (footer > aside) stops matching. Style it by class or id.

  4. Make the host bigger: a shadow root on <body> ✓ works

    If the shadow root is on <body>, every top-level element of the page is a child of the host. Any of them can opt in with only slot="stage", and nothing is moved. Everything else flows through a default <slot> as before. The limit: only direct children of <body> can opt in. See it running.

    <body>
      <p>Normal content.</p>
      <aside slot="stage" drawable>I opted in.</aside>
      <p>More normal content.</p>
    
      <script type="module">
        const root = document.body.attachShadow({ mode: 'open' });
        root.innerHTML = `
          <canvas content="drawable" layoutsubtree style="display:block;width:100%;height:130px">
            <slot name="stage"></slot>
          </canvas>
          <slot></slot>`;                    // everything else, in its normal place
        const canvas = root.querySelector('canvas');
        const ctx = canvas.getContext('2d');
        canvas.onpaint = () => {
          ctx.reset();
          let x = 20;
          for (const el of root.querySelector('slot[name=stage]').assignedElements()) {
            ctx.drawElementImage(el, x, 20, el.offsetWidth, el.offsetHeight);
            x += el.offsetWidth + 20;
          }
        };
      </script>
    </body>
  5. Plain <canvas><slot> plus one script: light-slots.js ✓ works

    This one has no custom element. You write a <slot> inside a normal <canvas>, and the script puts a shadow root on the canvas's parent so that the canvas's siblings can be slotted. Add slots="document" to the canvas and matching elements anywhere in the page are moved next to it first. See it running, and see how it works, step by step, in pictures.

    <script type="module" src="/lib/light-slots.js"></script>
    
    <canvas id="stage" content="drawable" layoutsubtree slots="document">
      <slot name="promo"></slot>
    </canvas>
    <footer>
      <aside slot="promo">…</aside>
    </footer>
    The whole of light-slots.js
  6. No component at all: a <slot> as a mount point ✓ works

    The pattern from Extensible Web Apps: a <slot name="…"> in the light DOM isn't a real slot, it's a named place that script appends things to. Put one inside a plain <canvas> and it works as a mount point with no custom element and no shadow root. A comment node remembers where the element came from. See it running.

    <canvas id="stage" content="drawable" layoutsubtree>
      <slot name="main"></slot>
    </canvas>
    <aside id="card" drawable>…</aside>
    
    <script type="module">
      const canvas = document.getElementById('stage');
      const ctx = canvas.getContext('2d');
      const slot = canvas.querySelector('slot[name="main"]');
      const card = document.getElementById('card');
      const mark = document.createComment('card was here');
    
      // In: leave a marker, move the card into the slot.
      card.before(mark);
      slot.moveBefore(card, null);          // keeps focus and state; append() also works
      canvas.requestPaint();
    
      // Out: back to the marker.
      // mark.parentNode.moveBefore(card, mark); mark.remove(); canvas.requestPaint();
    
      canvas.onpaint = () => {
        ctx.reset();
        for (const el of slot.children)
          ctx.drawElementImage(el, 16, 16, el.offsetWidth, el.offsetHeight);
      };
    </script>
  7. Assign it by hand with slot.assign() ✗ does nothing

    I thought manual slot assignment would get round the rule. It has the same rule: assign() silently ignores any node that isn't a child of the host.

    const root = host.attachShadow({ mode: 'open', slotAssignment: 'manual' });
    root.innerHTML = '<canvas content="drawable" layoutsubtree><slot></slot></canvas>';
    const slot = root.querySelector('slot');
    
    slot.assign(document.querySelector('footer aside'));
    slot.assignedElements();   // [] : it is not a child of host
  8. Leave it where it is and draw it twice: <dom-portal> ✓ works, differently

    <dom-portal for="promo"> shows a second live picture of an element somewhere else on the page. It doesn't bring the element into your canvas: it wraps the element where it sits and stretches one canvas over both places. It's for showing a second copy. It doesn't let you draw the element yourself. See /portal/.

    <script type="module" src="/lib/dom-portal.js"></script>
    
    <aside id="promo">…</aside>
    …
    <dom-portal for="promo" scale="0.5"></dom-portal>

Two things would remove the need for all of this: letting a <canvas content="drawable"> treat its own <slot> children as real slots for elements in the same document, or giving slots a way to reference an element by id. Neither exists yet.

A drawable wrapper around the slot

<canvas-slot> asks you to name each child with slot="…" and draws them one by one. The other pattern leaves the author's markup alone: inside the canvas there is one real element marked drawable that wraps a default <slot>. Everything the author wrote lands in that wrapper and is drawn as a single image with one call. The children still take input, so the button below works.

<canvas content="drawable" layoutsubtree>   <!-- in the shadow root -->
  <div drawable id="wrapper">
    <slot></slot>                           <!-- all the author's children -->
  </div>
</canvas>

ctx.drawElementImage(wrapper, 0, 0, wrapper.offsetWidth, wrapper.offsetHeight);
The complete page for this demo (paste it into a blank .html file)

The wrapper has to be a real element. Marking the <slot> itself drawable fails, because a slot has no box to paint (see the table below).

What works with slots (live, in your browser)

Each test builds a small canvas, draws into it and checks the result. The picture in a row is what that test drew.

ResultExperimentDetail

Findings

Every point links to where it is shown working, or failing, on this page.