canvas → slot, nothing else

The markup you would want to write: a <slot> inside a normal <canvas>, and normal elements elsewhere with a matching slot attribute. No template, no shadow root, no custom element.

Native: just the markup With one script: light-slots.js

This paragraph sits between the canvas and the slotted elements, in the normal document flow.

slot="first"
A normal element in the page.
slot="second"
checking…
<canvas id="stage" content="drawable">
  <slot name="first"></slot>
  <slot name="second"></slot>
</canvas>

<section slot="first">…</section>
<section slot="second">…</section>

<script type="module">
  const stage = document.getElementById('stage');
  const ctx = stage.getContext('2d');

  stage.onpaint = () => {
    ctx.reset();
    let x = 20;
    for (const slot of stage.querySelectorAll('slot'))
      for (const el of slot.assignedElements()) {
        // Always pass a size: without one the element is drawn in canvas pixels,
        // which is too big once the canvas is sized for a high-density screen.
        ctx.drawElementImage(el, x, 20, el.offsetWidth, el.offsetHeight);
        x += el.offsetWidth + 20;
      }
  };
</script>

What is going on

How light-slots.js works, step by step

Read the pictures top to bottom. Each one is the DOM tree of this page at that moment, and the code next to it is the part of light-slots.js that made the change. Orange outlines mark what is new in each step. The trees leave out this page's heading and text, which are treated just like the <p>.

On the “With one script” tab this line checks the pictures against the real page.

  1. Before What you write, and what the browser does with it

    <main><canvas id="stage"><slot name="first">inert<slot name="second">inert<p><section slot="first"><section slot="second">

    The canvas, its two <slot>s, a paragraph and two sections are all ordinary children of <main>. A <slot> outside a shadow tree projects nothing, so the canvas has nothing to draw and the sections stay in the page flow.

    canvas: nothing to drawslot="first"slot="second"still in the page flow
    On screen
    <canvas id="stage" content="drawable" layoutsubtree>
      <slot name="first"></slot>
      <slot name="second"></slot>
    </canvas>
    <p>…</p>
    <section slot="first">…</section>
    <section slot="second">…</section>
  2. 1 Attach a shadow root to the canvas’s parent

    <main>#shadow-rootnew, manual<slot>new<canvas id="stage"><slot name="first"><slot name="second"><p><section slot="first"><section slot="second">

    Slots only work inside a shadow tree, so the script gives the parent of the canvas one. It is in manual slot mode, so the script decides which child goes into which slot. It starts with one unnamed slot, and copies the page’s CSS rules in so your canvas styles still apply. Nothing has moved yet. Because the parent now has a shadow root, its children stop rendering until step 3 assigns them, all within the same frame.

    const host = canvas.parentElement;
    root = host.attachShadow({ mode: 'open', slotAssignment: 'manual' });
    copyDocumentStyles(root);
    const first = document.createElement('slot');
    first.dataset.flow = '';
    root.append(first);
  3. 2 Move the canvas into the shadow root, and leave a marker

    <main>#shadow-root<slot><canvas id="stage">moved here<slot name="first"><slot name="second"><slot>new<!-- canvas moved -->marker<p><section slot="first"><section slot="second">

    The same canvas element moves (your references and its 2D context stay valid). Its slots are now inside a shadow tree, so they are real slots. A comment stays behind to remember where the canvas was, and a second unnamed slot goes after the canvas for everything that follows it.

    const marker = document.createComment('canvas moved to shadow root by light-slots');
    canvas.replaceWith(marker);
    const after = document.createElement('slot');
    after.dataset.flow = '';
    // anon[region] is the unnamed slot for the content before the marker
    anon[region].after(canvas, after);
  4. 3 Assign every child of the parent to a slot

    <main>#shadow-root<slot>whatever came before the canvas<canvas id="stage"><slot name="first"><slot name="second"><slot><!-- canvas moved --><p><section slot="first" drawable><section slot="second" drawable>

    The script walks the parent’s children in order. A child whose slot="…" matches a slot in the canvas is assigned to that slot and gets the drawable attribute. Every other child is assigned to the unnamed slot for its side of the marker, so it renders exactly where it did before. A MutationObserver repeats this step whenever children or slot attributes change.

    for (const node of host.childNodes) {
      const m = markers.indexOf(node);
      if (m !== -1) { region = m + 1; continue; }
      const name = node.nodeType === 1 ? node.getAttribute('slot') : null;
      if (name && named.has(name)) {
        if (!node.hasAttribute('drawable')) node.setAttribute('drawable', '');
        named.get(name).nodes.push(node);
      } else if (node.nodeType === 1 || node.nodeType === 3) {
        flow[region].push(node);
      }
    }
    anon.forEach((slot, i) => slot.assign(...flow[i]));
    for (const { slot, nodes } of named.values()) slot.assign(...nodes);
    for (const canvas of state.canvases) canvas.requestPaint?.();
  5. After Your paint handler draws what was slotted

    canvas: your paint handler draws themslot="first"slot="second"

    The script stops there. It does not draw anything. The sections are now laid out as children of the canvas, slot.assignedElements() returns them, and your own paint handler decides where each one goes. They stay real elements, so the button and the input keep working where they are drawn.

    stage.onpaint = () => {
      ctx.reset();
      let x = 20;
      for (const slot of stage.querySelectorAll('slot'))
        for (const el of slot.assignedElements()) {
          ctx.drawElementImage(el, x, 20, el.offsetWidth, el.offsetHeight);
          x += el.offsetWidth + 20;
        }
    };

With slots="document" on the canvas there is one step before step 1: elements anywhere in the page whose slot matches are appended to the canvas’s parent, because only children of the shadow host can be assigned.

The source of light-slots.js

All of it. Use it with <script type="module" src="/lib/light-slots.js"></script>, or import upgrade(canvas) from /lib/light-slots.js?manual and call it yourself.

light-slots.js

← back to the declarative shadow DOM version and the live tests