Skip to content

Keep your coding agent up to date with the latest web best practices

Release v0.0.135

github-actions[bot]63499fbdba15
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
index 103b1fd..077688f 100644
--- a/.claude-plugin/marketplace.json
+++ b/.claude-plugin/marketplace.json
@@ -8,7 +8,7 @@
"name": "modern-web-guidance",
"source": "./",
"description": "Keep your coding agent up to date with the latest web best practices",
- "version": "0.0.134"
+ "version": "0.0.135"
}
]
}
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index cb11a1d..a8a1261 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "modern-web-guidance",
"description": "Keep your coding agent up to date with the latest web best practices",
- "version": "0.0.134",
+ "version": "0.0.135",
"author": {
"name": "Google Chrome"
}
diff --git a/.cursor-plugin/plugin.json b/.cursor-plugin/plugin.json
index cb11a1d..a8a1261 100644
--- a/.cursor-plugin/plugin.json
+++ b/.cursor-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "modern-web-guidance",
"description": "Keep your coding agent up to date with the latest web best practices",
- "version": "0.0.134",
+ "version": "0.0.135",
"author": {
"name": "Google Chrome"
}
diff --git a/README.md b/README.md
index 67e4e5c..c7c1248 100644
--- a/README.md
+++ b/README.md
@@ -26,7 +26,7 @@ Our content is evergrowing, we cover the bleeding edge of the web platform as we
### Core disciplines
-Here's a tiny sampling of the **113 use-case-centric guides**:
+Here's a tiny sampling of the **117 use-case-centric guides**:
* **User Experience**: Smooth and modern visual states: View Transitions, CSS `scrollbar-color` styling, high-contrast adaptation, entry/exit transition animations, parallax scrolling.
* **CSS layout:** container queries (both size and style queries), modern color spaces (`oklch`, `color-mix`) and `subgrid`, text-wrap tuning (`balance`, `pretty`), subgrid, and typography line height trimming (`text-box`)
@@ -36,10 +36,10 @@ Here's a tiny sampling of the **113 use-case-centric guides**:
* **Accessibility & Security**: accessible error announcements, keyboard focus management.
* **Built-in AI**: Leveraging local, on-device client models (native Language Detection, Summarization, and Translation APIs).
-#### Full Skill Coverage (v0.0.134)
+#### Full Skill Coverage (v0.0.135)
<details>
-<summary>Includes expert guidance across <strong>94 modern web features</strong></summary>
+<summary>Includes expert guidance across <strong>95 modern web features</strong></summary>
- [::backdrop](https://web-platform-dx.github.io/web-features-explorer/features/backdrop/)
- [:autofill](https://web-platform-dx.github.io/web-features-explorer/features/autofill/)
@@ -77,6 +77,7 @@ Here's a tiny sampling of the **113 use-case-centric guides**:
- [font-size-adjust](https://web-platform-dx.github.io/web-features-explorer/features/font-size-adjust/)
- [Form-associated WebMCP attributes](https://web-platform-dx.github.io/web-features-explorer/features/declarative-webmcp/)
- [hidden="until-found"](https://web-platform-dx.github.io/web-features-explorer/features/hidden-until-found/)
+- [HTML in canvas](https://web-platform-dx.github.io/web-features-explorer/features/canvas-html/)
- [image-set()](https://web-platform-dx.github.io/web-features-explorer/features/image-set/)
- [Individual transform properties](https://web-platform-dx.github.io/web-features-explorer/features/individual-transforms/)
- [inert](https://web-platform-dx.github.io/web-features-explorer/features/inert/)
@@ -138,7 +139,7 @@ Here's a tiny sampling of the **113 use-case-centric guides**:
</details>
<details>
-<summary>Covers <strong>113 real-world developer use cases</strong> with production-ready code patterns</summary>
+<summary>Covers <strong>117 real-world developer use cases</strong> with production-ready code patterns</summary>
<h3>accessibility</h3>
@@ -204,6 +205,7 @@ Here's a tiny sampling of the **113 use-case-centric guides**:
- **[animate-element-entry-exit](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/animate-element-entry-exit.md)**: Smoothly hide/show elements as they are added/removed from the DOM or as their display values are toggled.
- **[animate-to-from-top-layer](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/animate-to-from-top-layer.md)**: Animate elements such as dialogs, popovers, and tooltips as they're entering/exiting the top layer.
- **[animate-to-intrinsic-sizes](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/animate-to-intrinsic-sizes.md)**: Smoothly animate interactive components (like accordions, menus, and expanding cards) to and from their natural dimensions.
+- **[apply-webgl-shaders](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/apply-webgl-shaders.md)**: Apply custom visual effects with WebGL shaders to HTML content.
- **[browser-ui-color-theme](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/browser-ui-color-theme.md)**: Configure built-in browser UI (e.g. scrollbars, form controls, etc) to respect the user's light/dark theme preference.
- **[calculate-event-differentials](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/calculate-event-differentials.md)**: Calculate the duration and time remaining between dates and times.
- **[calculate-with-intrinsic-sizes](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/calculate-with-intrinsic-sizes.md)**: Calculate the size of an element based on its intrinsic size, while ensuring it fits within given design constraints.
@@ -223,12 +225,15 @@ Here's a tiny sampling of the **113 use-case-centric guides**:
- **[directional-navigation-transitions](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/directional-navigation-transitions.md)**: Animate visual state changes to reflect the direction of a user's navigational flow, such as sliding new content in from the right when advancing forward or from the left when returning to a previous screen.
- **[dynamic-sibling-animations](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/dynamic-sibling-animations.md)**: Stagger animation or transition timing across sibling elements so each one starts after a computed delay based on its position in the sibling list.
- **[dynamic-sibling-styling](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/dynamic-sibling-styling.md)**: Create dynamic visual spectrums or layout arrangements that automatically adapt to the number of elements in a group.
+- **[export-html-media-from-canvas](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/export-html-media-from-canvas.md)**: Capture and export dynamic HTML content as images or video frames from within canvas.
+- **[expose-canvas-content-to-browser-features](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/expose-canvas-content-to-browser-features.md)**: Expose content rendered in a canvas to browser features like assistive technologies, translation, or reading mode.
- **[flicker-free-client-side-ab-testing](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/flicker-free-client-side-ab-testing.md)**: Deliver and render A/B tests, multi-variate tests, or other experiments using client-side JavaScript to alter or inject HTML, CSS, and JavaScript without the original content showing first before flickering or flashing to show the experiment content.
- **[fluid-scaling](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/fluid-scaling.md)**: Scale items like font size, spacing, and media sizes smoothly based on the parent container's size rather than using fixed breakpoints
- **[format-human-readable-durations](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/format-human-readable-durations.md)**: Present elapsed time or durations to users in a readable, localized format, with the flexibility to display either detailed unit breakdowns (e.g., "1 hour and 30 minutes") or total unit counts (e.g., "90 minutes") depending on context.
- **[group-element-transitions](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/group-element-transitions.md)**: Transition a group of similar elements simultaneously using the same transition logic, such as removing a product from a shopping cart and having all the other products animate into their new positions.
- **[improve-text-layout-and-legibility](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/improve-text-layout-and-legibility.md)**: Improve the layout and legibility of short standalone text content, such as headings no longer than a few lines, by enabling the browser to apply evenly balanced line breaks when wrapping text.
- **[individual-transform-properties](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/individual-transform-properties.md)**: Animate or override individual CSS transform properties (e.g. translate, rotate, scale) independently of other transform properties on a single element.
+- **[interactive-content-in-3d-scenes](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/interactive-content-in-3d-scenes.md)**: Integrate interactive HTML elements into a 3D scene.
- **[interactive-content-reveal](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/interactive-content-reveal.md)**: Create interactive reveal effects, such as a spotlight that follows the user's pointer to uncover details within an image or UI section.
- **[interest-triggered-action-previews](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/interest-triggered-action-previews.md)**: Show a live preview of a button's effect when a user signals interest (e.g. hovering, focusing, or long-pressing) but before they commit to clicking.
- **[interest-triggered-tooltips](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/interest-triggered-tooltips.md)**: Show a tooltip or supplemental information when a user hovers over, focuses on, or long-presses an interactive element, without requiring a click.
diff --git a/gemini-extension.json b/gemini-extension.json
index cb11a1d..a8a1261 100644
--- a/gemini-extension.json
+++ b/gemini-extension.json
@@ -1,7 +1,7 @@
{
"name": "modern-web-guidance",
"description": "Keep your coding agent up to date with the latest web best practices",
- "version": "0.0.134",
+ "version": "0.0.135",
"author": {
"name": "Google Chrome"
}
diff --git a/package.json b/package.json
index f7dbf03..05b2784 100644
--- a/package.json
+++ b/package.json
@@ -2,7 +2,7 @@
"name": "modern-web-guidance",
"displayName": "Modern Web Guidance",
"description": "Keep your agent up to date on the latest web best practices.",
- "version": "0.0.134",
+ "version": "0.0.135",
"publisher": "GoogleChrome",
"engines": {
"vscode": "^1.90.0",
diff --git a/skills/modern-web-guidance/guides/user-experience/apply-webgl-shaders.md b/skills/modern-web-guidance/guides/user-experience/apply-webgl-shaders.md
new file mode 100644
index 0000000..b69fcff
--- /dev/null
+++ b/skills/modern-web-guidance/guides/user-experience/apply-webgl-shaders.md
@@ -0,0 +1,245 @@
+# Apply WebGL shaders to HTML content
+
+WebGL shaders provide powerful GPU-accelerated visual effects, enabling advanced capabilities like dynamic ripple distortions, lighting models, color grading, and custom vertex transformations. The HTML-in-Canvas API allows developers to apply WebGL textures to HTML content. This enables applying high-performance fragment and vertex shaders natively to fully interactive UI components, such as buttons, input fields, and rich text, while retaining native accessibility, text selection, and DOM event handling.
+
+## How to implement
+
+1. Check if HTML-in-Canvas is supported in the browser:
+
+```
+if ('requestPaint' in HTMLCanvasElement.prototype) {
+ // Use HTML in Canvas API
+} else {
+ // Use fallback strategy
+}
+```
+
+2. Add the `layoutsubtree` attribute to the `<canvas>` HTML element.
+3. Place your HTML content inside the `<canvas>` element with the `layoutsubtree` attribute.
+
+```html
+<canvas id="canvas" layoutsubtree>
+ <div id="html-content"></div>
+</canvas>
+```
+
+4. Scale your canvas grid to match the device scale factor to prevent blurriness:
+
+```js
+const observer = new ResizeObserver(([entry]) => {
+ const dpc = entry.devicePixelContentBoxSize;
+ canvas.width = dpc
+ ? dpc[0].inlineSize
+ : Math.round(entry.contentRect.width * window.devicePixelRatio);
+ canvas.height = dpc
+ ? dpc[0].blockSize
+ : Math.round(entry.contentRect.height * window.devicePixelRatio);
+});
+
+const supportsDevicePixelContentBox =
+ typeof ResizeObserverEntry !== "undefined" &&
+ "devicePixelContentBoxSize" in ResizeObserverEntry.prototype;
+const options = supportsDevicePixelContentBox
+ ? { box: "device-pixel-content-box" }
+ : {};
+observer.observe(canvas, options);
+```
+
+5. Render the HTML content to the canvas inside a `canvas.onpaint` event handler using the `texElementImage2D` method:
+
+```js
+canvas.onpaint = () => {
+ if (gl.texElementImage2D) {
+ gl.texElementImage2D(
+ gl.TEXTURE_2D,
+ 0,
+ gl.RGBA,
+ gl.RGBA,
+ gl.UNSIGNED_BYTE,
+ uiElement,
+ );
+ }
+};
+```
+
+ When using a `requestAnimationFrame` loop to render the scene, call `canvas.requestPaint()` within the loop to ensure that the HTML content is rendered to the canvas. Make sure you only re-render the canvas if there has been an update to the descendant HTML elements:
+
+ ```js
+ function render() {
+ // Request to update the canvas
+ canvas.requestPaint();
+ requestAnimationFrame(render);
+ }
+ requestAnimationFrame(render);
+
+ canvas.onpaint = (event) => {
+ if (event.changedElements && event.changedElements.length > 0) {
+ // Update the texture with texElementImage2D, and update the CSS transform as shown in step 6
+ }
+ };
+ ```
+
+6. Update the CSS transform.
+
+The browser needs to map from the 3D coordinate space into the CSS coordinate space using a viewport transform. To facilitate this, do the following:
+ - Convert WebGL MVP Matrix to DOM Matrix.
+ - Normalize the HTML element. HTML elements are sized in pixels (for example, 200px wide). WebGL, however, usually treats objects as "unit squares", for example, ranging from 0 to 1. If you don't normalize, your 200px button will look 200 times larger.
+ - Map to the canvas viewport. This step is the "re-scaling" phase: it stretches that unit-space math back out to match the actual pixel dimensions of your `<canvas>` element on the screen. It also flips the Y-axis, because in WebGL, up is positive, but in CSS, down is positive.
+ - Calculate the final transform. Multiply the matrices in order: Viewport * MVP * Normalization. Combining them into one final transform produces a "map" that tells the browser exactly where that HTML element layer should sit to align with the 3D drawing.
+ - Apply the transform to the HTML element. This moves the HTML element layer to sit directly on top of its rendered pixels. This ensures that when a user clicks a button or selects text, they are actually hitting the real HTML element.
+
+ ```js
+ if (canvas.getElementTransform) {
+ // 1. Convert WebGL MVP Matrix to DOM Matrix
+ const mvpDOM = new DOMMatrix(Array.from(htmlElementMVP));
+
+ // 2. Normalize the HTML element (Canvas Grid pixels -> WebGL Model Space)
+ const dprX = canvas.width / canvas.clientWidth;
+ const dprY = canvas.height / canvas.clientHeight;
+ const gridWidth = targetHTMLElement.offsetWidth * dprX;
+ const gridHeight = targetHTMLElement.offsetHeight * dprY;
+
+ const toGLModel = new DOMMatrix()
+ // Scale pixels to 1 unit, flip Y (as in CSS it points down, and in WebGL it points up)
+ .scale(1 / gridWidth, -1 / gridHeight, 1 / gridHeight)
+ // Center the origin: (0,0) becomes (-width/2, -height/2) before scaling
+ .translate(-gridWidth / 2, -gridHeight / 2);
+
+ // 3. Map to the canvas viewport
+ const clipToCanvasViewport = new DOMMatrix()
+ // Move center (0,0) to center of canvas
+ .translate(canvas.width / 2, canvas.height / 2)
+ // Scale normalized clip (-1..1) to viewport size
+ .scale(canvas.width / 2, -canvas.height / 2, canvas.height / 2);
+
+ // 4. Multiply: (Clip -> Pixels) * (MVP) * (pixels -> unit square)
+ const screenSpaceTransform = clipToCanvasViewport
+ .multiply(mvpDOM)
+ .multiply(toGLModel);
+
+ // 5. Apply to the transform
+ const computedTransform = canvas.getElementTransform(
+ targetHTMLElement,
+ screenSpaceTransform,
+ );
+ targetHTMLElement.style.transform = computedTransform.toString();
+ }
+ ```
+
+7. [Troubleshooting] If the developer is experiencing a mismatch in the DOM logical layout in 3D even after applying the CSS transform from step 5, check if the developer is experiencing the issue in Chromium 148 or earlier. If that's the case, check if `transform.is2D` is correctly set to false for a 3D DOMMatrix. If not, re-initialize the DOMMatrix which corrects `is2D` to be false before applying the transform to the target HTML element. This issue is fixed in Chromium 149+, and if the developer is experiencing it in newer Chromium versions, the is2D value is not the cause:
+
+```js
+if (transform.is2D) {
+ // Workaround for Chromium bug https://crbug.com/512171941
+ // affecting Chrome versions under 149 where `transform.is2D`
+ // is incorrectly true for a 3D DOMMatrix. The assignment
+ // below re-initializes the DOMMatrix which corrects is2D to be false.
+ transform = DOMMatrix.fromFloat64Array(transform.toFloat64Array());
+}
+targetHTMLElement.style.transform = computedTransform.toString();
+```
+
+## Example code
+
+```html
+<canvas id="canvas" layoutsubtree style="width: 400px; height: 400px;">
+ <div id="ui-element">
+ <p>WebGL UI Element</p>
+ <button>Action</button>
+ </div>
+</canvas>
+
+<script>
+ const canvas = document.getElementById("canvas");
+ const gl = canvas.getContext("webgl");
+ const uiElement = document.getElementById("ui-element");
+
+ // Setup WebGL texture...
+ const texture = gl.createTexture();
+ gl.bindTexture(gl.TEXTURE_2D, texture);
+
+ canvas.onpaint = () => {
+ // 1. Update texture with HTML content
+ if (gl.texElementImage2D) {
+ gl.texElementImage2D(
+ gl.TEXTURE_2D,
+ 0,
+ gl.RGBA,
+ gl.RGBA,
+ gl.UNSIGNED_BYTE,
+ uiElement,
+ );
+ }
+
+ // ... Render your 3D scene here, calculating htmlElementMVP matrix ...
+
+ // 2. Sync DOM position with 3D scene
+ if (canvas.getElementTransform) {
+ const mvpDOM = new DOMMatrix(Array.from(htmlElementMVP));
+
+ // Recalculate the DPR compensation mapping
+ const dprX = canvas.width / canvas.clientWidth;
+ const dprY = canvas.height / canvas.clientHeight;
+ const gridWidth = uiElement.offsetWidth * dprX;
+ const gridHeight = uiElement.offsetHeight * dprY;
+
+ const cssToUnitSpace = new DOMMatrix()
+ .scale(1 / gridWidth, -1 / gridHeight, 1 / gridHeight)
+ .translate(-gridWidth / 2, -gridHeight / 2);
+
+ const clipToCanvasViewport = new DOMMatrix()
+ .translate(canvas.width / 2, canvas.height / 2)
+ .scale(canvas.width / 2, -canvas.height / 2, canvas.height / 2);
+
+ const screenSpaceTransform = clipToCanvasViewport
+ .multiply(mvpDOM)
+ .multiply(cssToUnitSpace);
+
+ const computedTransform = canvas.getElementTransform(
+ uiElement,
+ screenSpaceTransform,
+ );
+ uiElement.style.transform = computedTransform.toString();
+ }
+ };
+</script>
+```
+
+## Best Practices
+
+- **MANDATORY**: Check browser support for the HTML-in-Canvas API before using it.
+- **MANDATORY**: Always add the `layoutsubtree` attribute to the `<canvas>` element.
+- **MANDATORY**: Use an `onpaint` event handler to render the HTML content to the canvas.
+- **MANDATORY**: Use the `texElementImage2D` method to render the HTML content to the canvas.
+- **MANDATORY**: Update the CSS transform of the HTML element to match the transform of the rendered content by setting the `style.transform` property of the HTML element.
+- **MANDATORY**: Use `ResizeObserver` to observe the screen size and update the canvas size to match device pixels.
+- **DO NOT** embed cross-origin content in a canvas, as it is not supported.
+- **DO NOT** initialize `ResizeObserver` within the `onpaint` event handler, as it may lead to memory leaks.
+
+### Fallback strategies
+
+HTML in canvas is not natively supported by any major browser yet.
+
+The HTML-in-Canvas API is not currently supported in all modern browsers, thus a fallback strategy is typically required.
+
+However, given the improved performance benefits of this API, HTML-in-Canvas should be used if the browser supports it.
+
+The fallback strategy depends on the use case. For example, for an interactive HTML content in canvas, if HTML-in-Canvas is not supported, place the HTML content on top of the canvas using CSS.
+
+### HTML-in-Canvas polyfill
+
+Use the following polyfill script to mimic the HTML-in-Canvas API in browsers that do not support it.
+
+1. Install or embed the library:
+
+```
+# Install
+npm install three-html-render
+```
+
+```
+# Embed
+<script src="https://cdn.jsdelivr.net/npm/three-html-render/dist/polyfill.js"></script>
+```
+
+2. Run the `installHtmlInCanvasPolyfill()` method to translate HTML-in-Canvas.
diff --git a/skills/modern-web-guidance/guides/user-experience/export-html-media-from-canvas.md b/skills/modern-web-guidance/guides/user-experience/export-html-media-from-canvas.md
new file mode 100644
index 0000000..8bb1806
--- /dev/null
+++ b/skills/modern-web-guidance/guides/user-experience/export-html-media-from-canvas.md
@@ -0,0 +1,249 @@
+# Export HTML content from canvas
+
+Web applications frequently need to capture and export rich HTML content—such as customized dashboards, styled documents, or interactive charts—as static images or video recordings. Historically, achieving this required bulky third-party libraries that manually parse DOM nodes and CSS properties to reconstruct a visual facsimile on a canvas. This approach is computationally expensive, error-prone, and frequently fails to support modern CSS layout features. With the HTML-in-Canvas API, developers can render real DOM elements directly into the canvas context. Because the browser's native rendering engine paints the HTML subtree with pixel-perfect accuracy, capturing the exact visual output as an image or video stream is highly efficient using built-in canvas methods like `toDataURL()`, `toBlob()`, or `captureStream()`.
+
+## How to implement
+
+1. Check if HTML-in-Canvas is supported in the browser:
+
+```
+if ('requestPaint' in HTMLCanvasElement.prototype) {
+ // Use HTML in Canvas API
+} else {
+ // Use fallback strategy
+}
+```
+
+2. Initialize the canvas to support rendering of descendant HTML elements by adding the `layoutsubtree` attribute to the `<canvas>` HTML element. Place your HTML content inside the `<canvas>` element with the `layoutsubtree` attribute:
+
+```html
+<canvas id="canvas" layoutsubtree>
+ <div id="html-content"></div>
+</canvas>
+```
+
+3. Scale your canvas grid to match the device scale factor to prevent blurriness:
+
+```js
+const observer = new ResizeObserver(([entry]) => {
+ const dpc = entry.devicePixelContentBoxSize;
+ canvas.width = dpc
+ ? dpc[0].inlineSize
+ : Math.round(entry.contentRect.width * window.devicePixelRatio);
+ canvas.height = dpc
+ ? dpc[0].blockSize
+ : Math.round(entry.contentRect.height * window.devicePixelRatio);
+});
+
+const supportsDevicePixelContentBox =
+ typeof ResizeObserverEntry !== "undefined" &&
+ "devicePixelContentBoxSize" in ResizeObserverEntry.prototype;
+const options = supportsDevicePixelContentBox
+ ? { box: "device-pixel-content-box" }
+ : {};
+observer.observe(canvas, options);
+```
+
+4. Render the HTML content to the canvas inside a `canvas.onpaint` event handler:
+
+- In 2D context, use the `drawElementImage` method:
+
+```js
+canvas.onpaint = () => {
+ ctx.reset();
+ // Draw the form element at x:0, y:0
+ let transform = ctx.drawElementImage(form_element, 0, 0);
+};
+```
+
+- In WebGL context, use the `texElementImage2D` method:
+
+```js
+canvas.onpaint = () => {
+ if (gl.texElementImage2D) {
+ gl.texElementImage2D(
+ gl.TEXTURE_2D,
+ 0,
+ gl.RGBA,
+ gl.RGBA,
+ gl.UNSIGNED_BYTE,
+ uiElement,
+ );
+ }
+};
+```
+
+- In WebGPU context, use the `copyElementImageToTexture` method:
+
+```js
+canvas.onpaint = () => {
+ root.device.queue.copyElementImageToTexture(valueElement, 512, 128, {
+ texture: targetTexture,
+ });
+};
+```
+
+
+When using a `requestAnimationFrame` loop to render the scene, call `canvas.requestPaint()` within the loop to ensure that the HTML content is rendered to the canvas. Make sure you only re-render the canvas if there has been an update to the descendant HTML elements:
+
+ ```js
+ function render() {
+ // Request to update the canvas
+ canvas.requestPaint();
+ requestAnimationFrame(render);
+ }
+ requestAnimationFrame(render);
+
+ canvas.onpaint = (event) => {
+ if (event.changedElements && event.changedElements.length > 0) {
+ // Update the texture with drawElementImage, texElementImage2D, or copyElementImageToTexture, and update the CSS transform as shown in step 5
+ }
+ };
+ ```
+
+5. Update the CSS transform.
+
+- For the 2D context case, apply the transform returned by the rendering call to the `style.transform` property:
+
+```js
+canvas.onpaint = () => {
+ ctx.reset();
+ // Draw the form element at x:0, y:0
+ let transform = ctx.drawElementImage(form_element, 0, 0);
+
+ // Sync the DOM location with the drawn location
+ form_element.style.transform = transform.toString();
+};
+```
+
+- For the 3D case with WebGL or WebGPU, the browser needs to map from the 3D coordinate space into the CSS coordinate space using a viewport transform. To facilitate this, do the following:
+ - Convert WebGL MVP Matrix to DOM Matrix.
+ - Normalize the HTML element. HTML elements are sized in pixels (for example, 200px wide). WebGL, however, usually treats objects as "unit squares", for example, ranging from 0 to 1. If you don't normalize, your 200px button will look 200 times larger.
+ - Map to the canvas viewport. This step is the "re-scaling" phase: it stretches that unit-space math back out to match the actual pixel dimensions of your `<canvas>` element on the screen. It also flips the Y-axis, because in WebGL, up is positive, but in CSS, down is positive.
+ - Calculate the final transform. Multiply the matrices in order: Viewport * MVP * Normalization. Combining them into one final transform produces a "map" that tells the browser exactly where that HTML element layer should sit to align with the 3D drawing.
+ - Apply the transform to the HTML element. This moves the HTML element layer to sit directly on top of its rendered pixels. This ensures that when a user clicks a button or selects text, they are actually hitting the real HTML element.
+
+ ```js
+ if (canvas.getElementTransform) {
+ // 1. Convert WebGL MVP Matrix to DOM Matrix
+ const mvpDOM = new DOMMatrix(Array.from(htmlElementMVP));
+
+ // 2. Normalize the HTML element (Canvas Grid pixels -> WebGL Model Space)
+ const dprX = canvas.width / canvas.clientWidth;
+ const dprY = canvas.height / canvas.clientHeight;
+ const gridWidth = targetHTMLElement.offsetWidth * dprX;
+ const gridHeight = targetHTMLElement.offsetHeight * dprY;
+
+ const toGLModel = new DOMMatrix()
+ // Scale pixels to 1 unit, flip Y (as in CSS it points down, and in WebGL it points up)
+ .scale(1 / gridWidth, -1 / gridHeight, 1 / gridHeight)
+ // Center the origin: (0,0) becomes (-width/2, -height/2) before scaling
+ .translate(-gridWidth / 2, -gridHeight / 2);
+
+ // 3. Map to the canvas viewport
+ const clipToCanvasViewport = new DOMMatrix()
+ // Move center (0,0) to center of canvas
+ .translate(canvas.width / 2, canvas.height / 2)
+ // Scale normalized clip (-1..1) to viewport size
+ .scale(canvas.width / 2, -canvas.height / 2, canvas.height / 2);
+
+ // 4. Multiply: (Clip -> Pixels) * (MVP) * (pixels -> unit square)
+ const screenSpaceTransform = clipToCanvasViewport
+ .multiply(mvpDOM)
+ .multiply(toGLModel);
+
+ // 5. Apply to the transform
+ const computedTransform = canvas.getElementTransform(
+ targetHTMLElement,
+ screenSpaceTransform,
+ );
+ targetHTMLElement.style.transform = computedTransform.toString();
+ }
+ ```
+
+6. [Troubleshooting] If the developer is experiencing a mismatch in the DOM logical layout in 3D even after applying the CSS transform from step 5, check if the developer is experiencing the issue in Chromium 148 or earlier. If that's the case, check if `transform.is2D` is correctly set to false for a 3D DOMMatrix. If not, re-initialize the DOMMatrix which corrects `is2D` to be false before applying the transform to the target HTML element. This issue is fixed in Chromium 149+, and if the developer is experiencing it in newer Chromium versions, the is2D value is not the cause:
+
+```js
+if (transform.is2D) {
+ // Workaround for Chromium bug https://crbug.com/512171941
+ // affecting Chrome versions under 149 where `transform.is2D`
+ // is incorrectly true for a 3D DOMMatrix. The assignment
+ // below re-initializes the DOMMatrix which corrects is2D to be false.
+ transform = DOMMatrix.fromFloat64Array(transform.toFloat64Array());
+}
+targetHTMLElement.style.transform = computedTransform.toString();
+```
+
+7. Use regular canvas export methods like `toDataURL()`, `toBlob()`, or `captureStream()`. The exported data will include the rendered HTML content.
+
+## Example code
+
+```html
+<body>
+ <canvas id="canvas" style="width: 400px; height: 200px;" layoutsubtree>
+ <input id="element">
+ </canvas>
+
+ <button id="download">Download Image</button>
+
+ <script>
+ const canvas = document.getElementById('canvas');
+ const ctx = canvas.getContext('2d');
+ const element = document.getElementById('element');
+ const download = document.getElementById('download');
+
+ canvas.onpaint = (event) => {
+ ctx.reset();
+ // Draw the element into the canvas
+ const transform = ctx.drawElementImage(element, 10, 10);
+ // Synchronize DOM position for hit testing (typing)
+ element.style.transform = transform.toString();
+ };
+
+ download.onclick = () => {
+ // Export the canvas content as an image
+ const dataURL = canvas.toDataURL('image/png');
+ const link = document.createElement('a');
+ link.download = 'exported-canvas.png';
+ link.href = dataURL;
+ link.click();
+ };
+
+ // Re-initialize canvas size on screen resize
+ const observer = new ResizeObserver(([entry]) => {
+ const dpc = entry.devicePixelContentBoxSize;
+ canvas.width = dpc ? dpc[0].inlineSize : Math.round(entry.contentRect.width * window.devicePixelRatio);
+ canvas.height = dpc ? dpc[0].blockSize : Math.round(entry.contentRect.height * window.devicePixelRatio);
+ canvas.requestPaint();
+ });
+ const supportsDevicePixelContentBox =
+ typeof ResizeObserverEntry !== 'undefined' &&
+ 'devicePixelContentBoxSize' in ResizeObserverEntry.prototype;
+ const options = supportsDevicePixelContentBox ? { box: 'device-pixel-content-box' } : {};
+ observer.observe(canvas, options);
+ </script>
+</body>
+```
+
+## Best Practices
+
+- **MANDATORY**: Check browser support for the HTML-in-Canvas API before using it.
+- **MANDATORY**: Always add the `layoutsubtree` attribute to the `<canvas>` element.
+- **MANDATORY**: Use an `onpaint` event handler to render the HTML content to the canvas.
+- **MANDATORY**: Use the `drawElementImage`, `texElementImage2D`, or `copyElementImageToTexture` methods to render the HTML content to the canvas.
+- **MANDATORY**: Update the CSS transform of the HTML element to match the transform of the rendered content by setting the `style.transform` property of the HTML element.
+- **MANDATORY**: Use `ResizeObserver` to observe the screen size and update the canvas size to match device pixels.
+- **DO NOT** embed cross-origin content in a canvas, as it is not supported.
+- **DO NOT** initialize `ResizeObserver` within the `onpaint` event handler, as it may lead to memory leaks.
+
+## Fallback strategies
+
+HTML in canvas is not natively supported by any major browser yet.
+
+The HTML-in-Canvas API is not currently supported in all modern browsers, thus a fallback strategy is typically required. However, given the improved performance benefits of this API, HTML-in-Canvas should be used if the browser supports it.
+
+For the use case where HTML content needs to be exported from a canvas, use libraries like `html2canvas`, `dom-to-image`, or `snapdom`.
+
+To capture HTML interactions frame by frame, for example, for streaming, capture DOM mutations using libraries like `rrweb`.
+
+Alternatively, implement a warning that HTML media export is not supported in the browser because it doesn't support HTML-in-Canvas.
\ No newline at end of file
diff --git a/skills/modern-web-guidance/guides/user-experience/expose-canvas-content-to-browser-features.md b/skills/modern-web-guidance/guides/user-experience/expose-canvas-content-to-browser-features.md
new file mode 100644
index 0000000..e46971a
--- /dev/null
+++ b/skills/modern-web-guidance/guides/user-experience/expose-canvas-content-to-browser-features.md
@@ -0,0 +1,389 @@
+# Expose canvas content to browser features
+
+Regular `<canvas>` content is not exposed to browser features such as screen readers, indexing, translation tools, accessibility assistive tools, find-in-page, print, etc. With `HTML in canvas`, you can render real DOM directly in a canvas element. Adding the `layoutsubtree` attribute to a `<canvas>` HTML element allows rendering descendant HTML elements within the canvas's rendering context. You can use it to style and lay out text in a canvas, expose canvas content to browser features (like accessibility, translation, or find-in-page), and apply 2D and 3D effects to HTML.
+
+## How to implement
+
+1. Check if HTML-in-Canvas is supported in the browser:
+
+```
+if ('requestPaint' in HTMLCanvasElement.prototype) {
+ // Use HTML in Canvas API
+} else {
+ // Use fallback strategy
+}
+```
+
+2. Add the `layoutsubtree` attribute to the `<canvas>` HTML element.
+3. Place your HTML content inside the `<canvas>` element with the `layoutsubtree` attribute.
+
+```html
+<canvas id="canvas" layoutsubtree>
+ <div id="html-content"></div>
+</canvas>
+```
+
+4. Scale your canvas grid to match the device scale factor to prevent blurriness:
+
+```js
+const observer = new ResizeObserver(([entry]) => {
+ const dpc = entry.devicePixelContentBoxSize;
+ canvas.width = dpc
+ ? dpc[0].inlineSize
+ : Math.round(entry.contentRect.width * window.devicePixelRatio);
+ canvas.height = dpc
+ ? dpc[0].blockSize
+ : Math.round(entry.contentRect.height * window.devicePixelRatio);
+});
+
+const supportsDevicePixelContentBox =
+ typeof ResizeObserverEntry !== "undefined" &&
+ "devicePixelContentBoxSize" in ResizeObserverEntry.prototype;
+const options = supportsDevicePixelContentBox
+ ? { box: "device-pixel-content-box" }
+ : {};
+observer.observe(canvas, options);
+```
+
+5. Render the HTML content to the canvas inside a `canvas.onpaint` event handler:
+
+- In 2D context, use the `drawElementImage` method:
+
+```js
+canvas.onpaint = () => {
+ ctx.reset();
+ // Draw the form element at x:0, y:0
+ let transform = ctx.drawElementImage(form_element, 0, 0);
+};
+```
+
+- In WebGL context, use the `texElementImage2D` method:
+
+```js
+canvas.onpaint = () => {
+ if (gl.texElementImage2D) {
+ gl.texElementImage2D(
+ gl.TEXTURE_2D,
+ 0,
+ gl.RGBA,
+ gl.RGBA,
+ gl.UNSIGNED_BYTE,
+ uiElement,
+ );
+ }
+};
+```
+
+- In WebGPU context, use the `copyElementImageToTexture` method:
+
+```js
+canvas.onpaint = () => {
+ root.device.queue.copyElementImageToTexture(valueElement, 512, 128, {
+ texture: targetTexture,
+ });
+};
+```
+
+When using a `requestAnimationFrame` loop to render the scene, call `canvas.requestPaint()` within the loop to ensure that the HTML content is rendered to the canvas. Make sure you only re-render the canvas if there has been an update to the descendant HTML elements:
+
+```js
+function render() {
+ // Request to update the canvas
+ canvas.requestPaint();
+ requestAnimationFrame(render);
+}
+requestAnimationFrame(render);
+
+canvas.onpaint = (event) => {
+ if (event.changedElements && event.changedElements.length > 0) {
+ // Update the texture with drawElementImage, texElementImage2D, or copyElementImageToTexture, and update the CSS transform as shown in step 6
+ }
+};
+```
+
+6. Update the CSS transform.
+
+- For the 2D context case, apply the transform returned by the rendering call to the `style.transform` property:
+
+```js
+canvas.onpaint = () => {
+ ctx.reset();
+ // Draw the form element at x:0, y:0
+ let transform = ctx.drawElementImage(form_element, 0, 0);
+
+ // Sync the DOM location with the drawn location
+ form_element.style.transform = transform.toString();
+};
+```
+
+- For the 3D case with WebGL or WebGPU, the browser needs to map from the 3D coordinate space into the CSS coordinate space using a viewport transform. To facilitate this, do the following:
+ - Convert WebGL MVP Matrix to DOM Matrix.
+ - Normalize the HTML element. HTML elements are sized in pixels (for example, 200px wide). WebGL, however, usually treats objects as "unit squares", for example, ranging from 0 to 1. If you don't normalize, your 200px button will look 200 times larger.
+ - Map to the canvas viewport. This step is the "re-scaling" phase: it stretches that unit-space math back out to match the actual pixel dimensions of your `<canvas>` element on the screen. It also flips the Y-axis, because in WebGL, up is positive, but in CSS, down is positive.
+ - Calculate the final transform. Multiply the matrices in order: Viewport _ MVP _ Normalization. Combining them into one final transform produces a "map" that tells the browser exactly where that HTML element layer should sit to align with the 3D drawing.
+ - Apply the transform to the HTML element. This moves the HTML element layer to sit directly on top of its rendered pixels. This ensures that when a user clicks a button or selects text, they are actually hitting the real HTML element.
+
+ ```js
+ if (canvas.getElementTransform) {
+ // 1. Convert WebGL MVP Matrix to DOM Matrix
+ const mvpDOM = new DOMMatrix(Array.from(htmlElementMVP));
+
+ // 2. Normalize the HTML element (Canvas Grid pixels -> WebGL Model Space)
+ const dprX = canvas.width / canvas.clientWidth;
+ const dprY = canvas.height / canvas.clientHeight;
+ const gridWidth = targetHTMLElement.offsetWidth * dprX;
+ const gridHeight = targetHTMLElement.offsetHeight * dprY;
+
+ const toGLModel = new DOMMatrix()
+ // Scale pixels to 1 unit, flip Y (as in CSS it points down, and in WebGL it points up)
+ .scale(1 / gridWidth, -1 / gridHeight, 1 / gridHeight)
+ // Center the origin: (0,0) becomes (-width/2, -height/2) before scaling
+ .translate(-gridWidth / 2, -gridHeight / 2);
+
+ // 3. Map to the canvas viewport
+ const clipToCanvasViewport = new DOMMatrix()
+ // Move center (0,0) to center of canvas
+ .translate(canvas.width / 2, canvas.height / 2)
+ // Scale normalized clip (-1..1) to viewport size
+ .scale(canvas.width / 2, -canvas.height / 2, canvas.height / 2);
+
+ // 4. Multiply: (Clip -> Pixels) * (MVP) * (pixels -> unit square)
+ const screenSpaceTransform = clipToCanvasViewport
+ .multiply(mvpDOM)
+ .multiply(toGLModel);
+
+ // 5. Apply to the transform
+ const computedTransform = canvas.getElementTransform(
+ targetHTMLElement,
+ screenSpaceTransform,
+ );
+ targetHTMLElement.style.transform = computedTransform.toString();
+ }
+ ```
+
+7. [Troubleshooting] If the developer is experiencing a mismatch in the DOM logical layout in 3D even after applying the CSS transform from step 5, check if the developer is experiencing the issue in Chromium 148 or earlier. If that's the case, check if `transform.is2D` is correctly set to false for a 3D DOMMatrix. If not, re-initialize the DOMMatrix which corrects `is2D` to be false before applying the transform to the target HTML element. This issue is fixed in Chromium 149+, and if the developer is experiencing it in newer Chromium versions, the is2D value is not the cause:
+
+```js
+if (transform.is2D) {
+ // Workaround for Chromium bug https://crbug.com/512171941
+ // affecting Chrome versions under 149 where `transform.is2D`
+ // is incorrectly true for a 3D DOMMatrix. The assignment
+ // below re-initializes the DOMMatrix which corrects is2D to be false.
+ transform = DOMMatrix.fromFloat64Array(transform.toFloat64Array());
+}
+targetHTMLElement.style.transform = computedTransform.toString();
+```
+
+## Example code
+
+### 2D Canvas
+
+```html
+<canvas id="canvas" layoutsubtree style="width: 400px; height: 200px;">
+ <div id="ui-element">
+ <p>
+ This text is rendered inside the canvas but is present in the DOM tree.
+ </p>
+ <input type="email" name="email" placeholder="enter your email" />
+ <button type="button">Submit</button>
+ </div>
+</canvas>
+
+<script>
+ const canvas = document.getElementById("canvas");
+ const ctx = canvas.getContext("2d");
+ const uiElement = document.getElementById("ui-element");
+
+ canvas.onpaint = () => {
+ ctx.reset();
+ // Draw the HTML element at x:0, y:0
+ const transform = ctx.drawElementImage(uiElement, 0, 0);
+
+ // Sync the DOM location with the drawn location
+ uiElement.style.transform = transform.toString();
+ };
+
+ // Handle resizing to match device pixels
+ const observer = new ResizeObserver(([entry]) => {
+ const dpc = entry.devicePixelContentBoxSize;
+ canvas.width = dpc
+ ? dpc[0].inlineSize
+ : Math.round(entry.contentRect.width * window.devicePixelRatio);
+ canvas.height = dpc
+ ? dpc[0].blockSize
+ : Math.round(entry.contentRect.height * window.devicePixelRatio);
+ canvas.requestPaint();
+ });
+
+ const supportsDevicePixelContentBox =
+ typeof ResizeObserverEntry !== "undefined" &&
+ "devicePixelContentBoxSize" in ResizeObserverEntry.prototype;
+ const options = supportsDevicePixelContentBox
+ ? { box: "device-pixel-content-box" }
+ : {};
+ observer.observe(canvas, options);
+</script>
+```
+
+### WebGL Canvas
+
+```html
+<canvas id="canvas" layoutsubtree style="width: 400px; height: 400px;">
+ <div id="ui-element">
+ <p>WebGL UI Element</p>
+ <button>Action</button>
+ </div>
+</canvas>
+
+<script>
+ const canvas = document.getElementById("canvas");
+ const gl = canvas.getContext("webgl");
+ const uiElement = document.getElementById("ui-element");
+
+ // Setup WebGL texture...
+ const texture = gl.createTexture();
+ gl.bindTexture(gl.TEXTURE_2D, texture);
+
+ canvas.onpaint = () => {
+ // 1. Update texture with HTML content
+ if (gl.texElementImage2D) {
+ gl.texElementImage2D(
+ gl.TEXTURE_2D,
+ 0,
+ gl.RGBA,
+ gl.RGBA,
+ gl.UNSIGNED_BYTE,
+ uiElement,
+ );
+ }
+
+ // ... Render your 3D scene here, calculating htmlElementMVP matrix ...
+
+ // 2. Sync DOM position with 3D scene
+ if (canvas.getElementTransform) {
+ const mvpDOM = new DOMMatrix(Array.from(htmlElementMVP));
+
+ // Recalculate the DPR compensation mapping
+ const dprX = canvas.width / canvas.clientWidth;
+ const dprY = canvas.height / canvas.clientHeight;
+ const gridWidth = uiElement.offsetWidth * dprX;
+ const gridHeight = uiElement.offsetHeight * dprY;
+
+ const cssToUnitSpace = new DOMMatrix()
+ .scale(1 / gridWidth, -1 / gridHeight, 1 / gridHeight)
+ .translate(-gridWidth / 2, -gridHeight / 2);
+
+ const clipToCanvasViewport = new DOMMatrix()
+ .translate(canvas.width / 2, canvas.height / 2)
+ .scale(canvas.width / 2, -canvas.height / 2, canvas.height / 2);
+
+ const screenSpaceTransform = clipToCanvasViewport
+ .multiply(mvpDOM)
+ .multiply(cssToUnitSpace);
+
+ const computedTransform = canvas.getElementTransform(
+ uiElement,
+ screenSpaceTransform,
+ );
+ uiElement.style.transform = computedTransform.toString();
+ }
+ };
+</script>
+```
+
+### WebGPU Canvas
+
+```html
+<canvas id="canvas" layoutsubtree style="width: 400px; height: 400px;">
+ <div id="ui-element">
+ <p>WebGPU UI Element</p>
+ </div>
+</canvas>
+
+<script>
+ const canvas = document.getElementById("canvas");
+ const context = canvas.getContext("webgpu");
+ const uiElement = document.getElementById("ui-element");
+
+ // Setup WebGPU...
+ // const device = ...
+ // const targetTexture = ...
+
+ canvas.onpaint = () => {
+ // 1. Copy HTML content to texture
+ if (device.queue.copyElementImageToTexture) {
+ device.queue.copyElementImageToTexture(uiElement, width, height, {
+ texture: targetTexture,
+ });
+ }
+
+ // 2. Sync DOM position (same matrix math as WebGL)
+ if (canvas.getElementTransform) {
+ const mvpDOM = new DOMMatrix(Array.from(htmlElementMVP));
+
+ // Recalculate the DPR compensation mapping
+ const dprX = canvas.width / canvas.clientWidth;
+ const dprY = canvas.height / canvas.clientHeight;
+ const gridWidth = uiElement.offsetWidth * dprX;
+ const gridHeight = uiElement.offsetHeight * dprY;
+
+ const cssToUnitSpace = new DOMMatrix()
+ .scale(1 / gridWidth, -1 / gridHeight, 1 / gridHeight) // Retain Z scale
+ .translate(-gridWidth / 2, -gridHeight / 2);
+
+ const clipToCanvasViewport = new DOMMatrix()
+ .translate(canvas.width / 2, canvas.height / 2)
+ .scale(canvas.width / 2, -canvas.height / 2, canvas.height / 2); // Retain Z scale
+
+ const screenSpaceTransform = clipToCanvasViewport
+ .multiply(mvpDOM)
+ .multiply(cssToUnitSpace);
+
+ const computedTransform = canvas.getElementTransform(
+ uiElement,
+ screenSpaceTransform,
+ );
+ uiElement.style.transform = computedTransform.toString();
+ }
+ };
+</script>
+```
+
+## Best Practices
+
+- **MANDATORY**: Check browser support for the HTML-in-Canvas API before using it.
+- **MANDATORY**: Always add the `layoutsubtree` attribute to the `<canvas>` element.
+- **MANDATORY**: Use an `onpaint` event handler to render the HTML content to the canvas.
+- **MANDATORY**: Use the `drawElementImage`, `texElementImage2D`, or `copyElementImageToTexture` methods to render the HTML content to the canvas.
+- **MANDATORY**: Update the CSS transform of the HTML element to match the transform of the rendered content by setting the `style.transform` property of the HTML element.
+- **MANDATORY**: Use `ResizeObserver` to observe the screen size and update the canvas size to match device pixels.
+- **DO NOT** embed cross-origin content in a canvas, as it is not supported.
+- **DO NOT** initialize `ResizeObserver` within the `onpaint` event handler, as it may lead to memory leaks.
+
+## Fallback strategies
+
+HTML in canvas is not natively supported by any major browser yet.
+
+The HTML-in-Canvas API is not currently supported in all modern browsers, thus a fallback strategy is typically required.
+
+However, given the improved performance benefits of this API, HTML-in-Canvas should be used if the browser supports it.
+
+The fallback strategy depends on the use case. For example, for an interactive HTML content in canvas, if HTML-in-Canvas is not supported, place the HTML content on top of the canvas using CSS.
+
+### HTML-in-Canvas polyfills
+
+Use the following polyfill script to mimic the HTML-in-Canvas API in browsers that do not support it.
+
+1. Install or embed the library:
+
+```
+# Install
+npm install three-html-render
+```
+
+```
+# Embed
+<script src="https://cdn.jsdelivr.net/npm/three-html-render/dist/polyfill.js"></script>
+```
+
+2. Run the `installHtmlInCanvasPolyfill()` method to translate HTML-in-Canvas.
diff --git a/skills/modern-web-guidance/guides/user-experience/interactive-content-in-3d-scenes.md b/skills/modern-web-guidance/guides/user-experience/interactive-content-in-3d-scenes.md
new file mode 100644
index 0000000..74b8b33
--- /dev/null
+++ b/skills/modern-web-guidance/guides/user-experience/interactive-content-in-3d-scenes.md
@@ -0,0 +1,371 @@
+# Enable interactive HTML content in 3D scenes
+
+The HTML-in-Canvas API allows rendering real DOM directly inside a canvas element. When applied to 3D rendering contexts like WebGL, WebGPU, or Three.js, adding the `layoutsubtree` attribute enables descendant HTML elements to be seamlessly projected into the 3D scene. Crucially, because the HTML elements remain part of the active DOM layout tree, they retain full interactivity—allowing users to click buttons, select text, and trigger focus states natively without requiring complex raycasting or custom event handling.
+
+## How to implement
+
+### WebGL and WebGPU
+When using WebGL or WebGPU, follow these steps:
+
+1. Check if HTML-in-Canvas is supported in the browser:
+
+```
+if ('requestPaint' in HTMLCanvasElement.prototype) {
+ // Use HTML in Canvas API
+} else {
+ // Use fallback strategy
+}
+```
+
+2. Initialize `<canvas>` to support descendant HTML elements by adding the `layoutsubtree` attribute to the `<canvas>` HTML element. Place your HTML content inside the `<canvas>` element with the `layoutsubtree` attribute.
+
+```html
+<canvas id="canvas" layoutsubtree>
+ <div id="html-content"></div>
+</canvas>
+```
+
+3. Scale your canvas grid to match the device scale factor to prevent blurriness:
+
+```js
+const observer = new ResizeObserver(([entry]) => {
+ const dpc = entry.devicePixelContentBoxSize;
+ canvas.width = dpc
+ ? dpc[0].inlineSize
+ : Math.round(entry.contentRect.width * window.devicePixelRatio);
+ canvas.height = dpc
+ ? dpc[0].blockSize
+ : Math.round(entry.contentRect.height * window.devicePixelRatio);
+});
+
+const supportsDevicePixelContentBox =
+ typeof ResizeObserverEntry !== "undefined" &&
+ "devicePixelContentBoxSize" in ResizeObserverEntry.prototype;
+const options = supportsDevicePixelContentBox
+ ? { box: "device-pixel-content-box" }
+ : {};
+observer.observe(canvas, options);
+```
+
+4. Render the HTML content to the canvas inside a `canvas.onpaint` event handler:
+
+- In WebGL context, use the `texElementImage2D` method:
+
+```js
+canvas.onpaint = () => {
+ if (gl.texElementImage2D) {
+ gl.texElementImage2D(
+ gl.TEXTURE_2D,
+ 0,
+ gl.RGBA,
+ gl.RGBA,
+ gl.UNSIGNED_BYTE,
+ uiElement,
+ );
+ }
+};
+```
+
+- In WebGPU context, use the `copyElementImageToTexture` method:
+
+```js
+canvas.onpaint = () => {
+ root.device.queue.copyElementImageToTexture(valueElement, 512, 128, {
+ texture: targetTexture,
+ });
+};
+```
+
+When using a `requestAnimationFrame` loop to render the scene, call `canvas.requestPaint()` within the loop to ensure that the HTML content is rendered to the canvas. Make sure you only re-render the canvas if there has been an update to the descendant HTML elements:
+
+```js
+function render() {
+ // Request to update the canvas
+ canvas.requestPaint();
+ requestAnimationFrame(render);
+}
+requestAnimationFrame(render);
+
+canvas.onpaint = (event) => {
+ if (event.changedElements && event.changedElements.length > 0) {
+ // Update the texture with texElementImage2D, and update the CSS transform as shown in step 6
+ }
+};
+```
+
+6. Update the CSS transform.
+
+The browser needs to map from the 3D coordinate space into the CSS coordinate space using a viewport transform. To facilitate this, do the following:
+
+- Convert the MVP Matrix to DOM Matrix.
+- Normalize the HTML element. HTML elements are sized in pixels (for example, 200px wide). WebGL, however, usually treats objects as "unit squares", for example, ranging from 0 to 1. If you don't normalize, your 200px button will look 200 times larger.
+- Map to the canvas viewport. This step is the "re-scaling" phase: it stretches that unit-space math back out to match the actual pixel dimensions of your `<canvas>` element on the screen. It also flips the Y-axis, because in WebGL, up is positive, but in CSS, down is positive.
+- Calculate the final transform. Multiply the matrices in order: Viewport * MVP * Normalization. Combining them into one final transform produces a "map" that tells the browser exactly where that HTML element layer should sit to align with the 3D drawing.
+- Apply the transform to the HTML element. This moves the HTML element layer to sit directly on top of its rendered pixels. This ensures that when a user clicks a button or selects text, they are actually hitting the real HTML element.
+
+```js
+if (canvas.getElementTransform) {
+ // 1. Convert WebGL MVP Matrix to DOM Matrix
+ const mvpDOM = new DOMMatrix(Array.from(htmlElementMVP));
+
+ // 2. Normalize the HTML element (Canvas Grid pixels -> WebGL Model Space)
+ const dprX = canvas.width / canvas.clientWidth;
+ const dprY = canvas.height / canvas.clientHeight;
+ const gridWidth = targetHTMLElement.offsetWidth * dprX;
+ const gridHeight = targetHTMLElement.offsetHeight * dprY;
+
+ const toGLModel = new DOMMatrix()
+ // Scale pixels to 1 unit, flip Y (as in CSS it points down, and in WebGL it points up)
+ .scale(1 / gridWidth, -1 / gridHeight, 1 / gridHeight)
+ // Center the origin: (0,0) becomes (-width/2, -height/2) before scaling
+ .translate(-gridWidth / 2, -gridHeight / 2);
+
+ // 3. Map to the canvas viewport
+ const clipToCanvasViewport = new DOMMatrix()
+ // Move center (0,0) to center of canvas
+ .translate(canvas.width / 2, canvas.height / 2)
+ // Scale normalized clip (-1..1) to viewport size
+ .scale(canvas.width / 2, -canvas.height / 2, canvas.height / 2);
+
+ // 4. Multiply: (Clip -> Pixels) * (MVP) * (pixels -> unit square)
+ const screenSpaceTransform = clipToCanvasViewport
+ .multiply(mvpDOM)
+ .multiply(toGLModel);
+
+ // 5. Apply to the transform
+ const computedTransform = canvas.getElementTransform(
+ targetHTMLElement,
+ screenSpaceTransform,
+ );
+ targetHTMLElement.style.transform = computedTransform.toString();
+}
+```
+
+7. [Troubleshooting] If the developer is experiencing a mismatch in the DOM logical layout in 3D even after applying the CSS transform from step 5, check if the developer is experiencing the issue in Chromium 148 or earlier. If that's the case, check if `transform.is2D` is correctly set to false for a 3D DOMMatrix. If not, re-initialize the DOMMatrix which corrects `is2D` to be false before applying the transform to the target HTML element. This issue is fixed in Chromium 149+, and if the developer is experiencing it in newer Chromium versions, the is2D value is not the cause:
+
+```js
+if (transform.is2D) {
+ // Workaround for Chromium bug https://crbug.com/512171941
+ // affecting Chrome versions under 149 where `transform.is2D`
+ // is incorrectly true for a 3D DOMMatrix. The assignment
+ // below re-initializes the DOMMatrix which corrects is2D to be false.
+ transform = DOMMatrix.fromFloat64Array(transform.toFloat64Array());
+}
+targetHTMLElement.style.transform = computedTransform.toString();
+```
+
+### Three.js
+
+1. Check if HTML-in-Canvas is supported in the browser:
+
+```
+if ('requestPaint' in HTMLCanvasElement.prototype) {
+ // Use HTML in Canvas API
+} else {
+ // Use fallback strategy
+}
+```
+
+2. Create a custom geometry and material for the HTML content.
+
+3. Pass the DOM element into THREE.HTMLTexture:
+```js
+ material.map = new THREE.HTMLTexture(element);
+ mesh = new THREE.Mesh( geometry, material );
+ scene.add( mesh );
+```
+
+## Example code
+
+### WebGL Canvas
+
+```html
+<canvas id="canvas" layoutsubtree style="width: 400px; height: 400px;">
+ <div id="ui-element">
+ <p>WebGL UI Element</p>
+ <button>Action</button>
+ </div>
+</canvas>
+
+<script>
+ const canvas = document.getElementById("canvas");
+ const gl = canvas.getContext("webgl");
+ const uiElement = document.getElementById("ui-element");
+
+ // Setup WebGL texture...
+ const texture = gl.createTexture();
+ gl.bindTexture(gl.TEXTURE_2D, texture);
+
+ canvas.onpaint = () => {
+ // 1. Update texture with HTML content
+ if (gl.texElementImage2D) {
+ gl.texElementImage2D(
+ gl.TEXTURE_2D,
+ 0,
+ gl.RGBA,
+ gl.RGBA,
+ gl.UNSIGNED_BYTE,
+ uiElement,
+ );
+ }
+
+ // ... Render your 3D scene here, calculating htmlElementMVP matrix ...
+
+ // 2. Sync DOM position with 3D scene
+ if (canvas.getElementTransform) {
+ const mvpDOM = new DOMMatrix(Array.from(htmlElementMVP));
+
+ // Recalculate the DPR compensation mapping
+ const dprX = canvas.width / canvas.clientWidth;
+ const dprY = canvas.height / canvas.clientHeight;
+ const gridWidth = uiElement.offsetWidth * dprX;
+ const gridHeight = uiElement.offsetHeight * dprY;
+
+ const cssToUnitSpace = new DOMMatrix()
+ .scale(1 / gridWidth, -1 / gridHeight, 1 / gridHeight)
+ .translate(-gridWidth / 2, -gridHeight / 2);
+
+ const clipToCanvasViewport = new DOMMatrix()
+ .translate(canvas.width / 2, canvas.height / 2)
+ .scale(canvas.width / 2, -canvas.height / 2, canvas.height / 2);
+
+ const screenSpaceTransform = clipToCanvasViewport
+ .multiply(mvpDOM)
+ .multiply(cssToUnitSpace);
+
+ const computedTransform = canvas.getElementTransform(
+ uiElement,
+ screenSpaceTransform,
+ );
+ uiElement.style.transform = computedTransform.toString();
+ }
+ };
+</script>
+```
+
+### WebGPU Canvas
+
+```html
+<canvas id="canvas" layoutsubtree style="width: 400px; height: 400px;">
+ <div id="ui-element">
+ <p>WebGPU UI Element</p>
+ </div>
+</canvas>
+
+<script>
+ const canvas = document.getElementById("canvas");
+ const context = canvas.getContext("webgpu");
+ const uiElement = document.getElementById("ui-element");
+
+ // Setup WebGPU...
+ // const device = ...
+ // const targetTexture = ...
+
+ canvas.onpaint = () => {
+ // 1. Copy HTML content to texture
+ if (device.queue.copyElementImageToTexture) {
+ device.queue.copyElementImageToTexture(uiElement, width, height, {
+ texture: targetTexture,
+ });
+ }
+
+ // 2. Sync DOM position (same matrix math as WebGL)
+ if (canvas.getElementTransform) {
+ const mvpDOM = new DOMMatrix(Array.from(htmlElementMVP));
+
+ // Recalculate the DPR compensation mapping
+ const dprX = canvas.width / canvas.clientWidth;
+ const dprY = canvas.height / canvas.clientHeight;
+ const gridWidth = uiElement.offsetWidth * dprX;
+ const gridHeight = uiElement.offsetHeight * dprY;
+
+ const cssToUnitSpace = new DOMMatrix()
+ .scale(1 / gridWidth, -1 / gridHeight, 1 / gridHeight) // Retain Z scale
+ .translate(-gridWidth / 2, -gridHeight / 2);
+
+ const clipToCanvasViewport = new DOMMatrix()
+ .translate(canvas.width / 2, canvas.height / 2)
+ .scale(canvas.width / 2, -canvas.height / 2, canvas.height / 2); // Retain Z scale
+
+ const screenSpaceTransform = clipToCanvasViewport
+ .multiply(mvpDOM)
+ .multiply(cssToUnitSpace);
+
+ const computedTransform = canvas.getElementTransform(
+ uiElement,
+ screenSpaceTransform,
+ );
+ uiElement.style.transform = computedTransform.toString();
+ }
+ };
+</script>
+```
+
+### Three.js
+
+```js
+// 1. Initialize Three.js camera, scene, renderer, mesh, interactions;
+
+// 2. Ensure HTML-in-Canvas feature support
+if (!('requestPaint' in HTMLCanvasElement.prototype)) {
+ // Use a fallback strategy
+}
+
+// 3. Initialize the source HTML DOM element
+const element = document.createElement('div');
+element.innerHTML = '<h1>Hello World</h1>';
+
+// 4. Create geometry and material
+const geometry = new RoundedBoxGeometry( 100, 100, 100, 10, 10 );
+const material = new THREE.MeshStandardMaterial( { roughness: 0, metalness: 0.5 } );
+
+// 5. Pass the DOM element into THREE.HTMLTexture
+material.map = new THREE.HTMLTexture(element);
+
+mesh = new THREE.Mesh( geometry, material );
+scene.add( mesh );
+
+// 6. Render Loop
+function animate() {
+ renderer.render(scene, camera);
+}
+```
+
+## Best Practices
+
+- **MANDATORY**: Check browser support for the HTML-in-Canvas API before using it.
+- **MANDATORY**: When using WebGL or WebGPU, always add the `layoutsubtree` attribute to the `<canvas>` element.
+- **MANDATORY**: When using WebGL or WebGPU, use an `onpaint` event handler to render the HTML content to the canvas.
+- **MANDATORY**: Use the `texElementImage2D` for WebGL, or `copyElementImageToTexture` for WebGPU methods to render the HTML content to the canvas.
+- **MANDATORY**: When using WebGL or WebGPU, update the CSS transform of the HTML element to match the transform of the rendered content by setting the `style.transform` property of the HTML element.
+- **MANDATORY**: Observe the screen size and update the canvas size to match device pixels, for example, by using `ResizeObserver`.
+- **DO NOT** embed cross-origin content in a canvas, as it is not supported.
+- **DO NOT** initialize `ResizeObserver` within the `onpaint` event handler, as it may lead to memory leaks.
+
+### Fallback strategies
+
+HTML in canvas is not natively supported by any major browser yet.
+
+The HTML-in-Canvas API is not currently supported in all modern browsers, thus a fallback strategy is typically required.
+
+However, given the improved performance benefits of this API, HTML-in-Canvas should be used if the browser supports it.
+
+The fallback strategy depends on the use case. For example, for an interactive HTML content in canvas, if HTML-in-Canvas is not supported, place the HTML content on top of the canvas using CSS.
+
+### HTML-in-Canvas polyfill
+
+Use the following polyfill script to mimic the HTML-in-Canvas API in browsers that do not support it.
+
+1. Install or embed the library:
+
+```
+# Install
+npm install three-html-render
+```
+
+```
+# Embed
+<script src="https://cdn.jsdelivr.net/npm/three-html-render/dist/polyfill.js"></script>
+```
+
+2. Run the `installHtmlInCanvasPolyfill()` method to translate HTML-in-Canvas.