# HTML-in-Canvas This is a proposal for using 2D and 3D `` to customize the rendering of HTML content. ## Status This is a living explainer which is continuously updated as we receive feedback. ## Motivation There is no web API to easily render complex layouts of text and other content into a ``. As a result, ``-based content suffers in accessibility, internationalization, performance, and quality. ### Use cases * **Styled, Laid Out Content in Canvas.** There’s a strong need for better styled text support in Canvas. Examples include chart components (legend, axes, etc.), rich content boxes in creative tools, and in-game menus. * **Accessibility Improvements.** Maintaining accessible `` experiences requires manually synchronizing auxiliary DOM subtrees with canvas draw calls. * **Composing HTML Elements with Effects.** A limited set of CSS effects, such as filters, backdrop-filter, and mix-blend-mode are already available, but there is a desire to use general WebGL shaders with HTML. * **HTML Rendering in a 3D Context.** 3D aspects of sites and games need to render rich 2D content into surfaces within a 3D scene. * **Media Export.** There's a need to export HTML content as images or video. ## Proposed solution The solution introduces five primitives to manage canvas layout, drawing capabilities, rendering events for DOM-to-canvas synchronization, and geometry update capabilities for canvas-to-DOM synchronization. ### 1. The canvas `content` attribute The `content` attribute on a `` element takes two values: `fallback` (default) for treating canvas descendants as fallback content, and `drawable` for opting in canvas descendants to layout. The canvas element blockifies immediate descendants and they are laid out with static positioning. In terms of accessibility, `content=drawable` canvas descendants work like regular DOM content and respect CSS/HTML primitives like `aria-hidden="true"`, but initially do not have geometry information (for more information, see [Accessibility](#accessibility)). In terms of hit testing, `content=drawable` canvas descendants are initially not hit testable. ### 2. The `drawable` attribute The `drawable` attribute on `` descendant elements is required for drawing, and implies `isolation: isolate` as well as being a containing block for all descendants. `drawable` elements can be nested, and a _drawable subtree_ includes a drawable element and its descendants, excluding `drawable` descendants and their subtrees. ### 3. The `paint` event The `paint` event enables synchronizing the DOM with canvas. A snapshot of the rendering commands of all `drawable` elements, including their drawable subtrees, is recorded on every rendering update, and the updated snapshots are available to paint in the `paint` event. The canvas `paint` event must fire if an element's snapshot would be drawn differently. This event fires just after intersection observer steps have run during [update-the-rendering](https://html.spec.whatwg.org/#update-the-rendering). Implementations may fire the `paint` event when an element's snapshot has not changed, but should avoid doing so. The event contains a list of the canvas `drawable` descendants which have changed. Canvas drawing commands made in the `paint` event will appear in the current rendering update, but DOM changes made in the `paint` event will not show up until the subsequent rendering update. To ensure descendants paint before ancestors, `paint` events fire in _reverse_ document order (child frames before their parent documents), and in _reverse_ tree order within each document. To support application patterns which update continuously, a new `requestPaint()` function is added which will cause the `paint` event to fire once during the next rendering opportunity, even if no canvas descendants have changed (analogous to `requestAnimationFrame()`). ### 4. `drawElementImage` (and WebGL: `texElementSubImage2D`, WebGPU: `drawElementImageToTexture`) The `drawElementImage()` method draws the last snapshot of a `drawable` element, and its drawable subtree, into the 2D canvas, and similar APIs are provided for WebGL and WebGPU to draw into a texture. The rendering starts at the element's border box, before CSS transformations. Similar to the 2D [drawImage](https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-drawimage-dev), and similar WebGL/WebGPU APIs, optional source and destination rect parameters can be provided. The source rect parameters can be used to apply outsets to the drawn element, either for clipping or to include ink overflow extending beyond the element's border box. The destination rect parameters can be used to position and scale the drawn element. An exception is thrown if `drawElementImage()` is called with an element without the `drawable` attribute, before an initial snapshot has been recorded, or for elements with other canvas ancestors. A reference to the most recent snapshot of a `drawable` element can be acquired as an `ElementImage` using `captureElementImage`. These objects can be transferred to a worker and drawn to an `OffscreenCanvas`. ### 5. Synchronizing the DOM and drawing The `updateElementGeometry` method enables synchronizing the element's canvas drawing with the DOM: * Hit test order can be set to the top or left unmodified with `preserveHitTestOrder`. The canvas maintains an ordered list of drawable descendants to hit test, and hit testing proceeds straight from the canvas element to each descendant, skipping intervening clips and transforms. * The DOM position of a `drawable` element can be set with a canvas element transform, which is a DOMMatrix that transforms the element's border-box, before CSS transformations, to the drawn location in the canvas. The canvas element transform is not used for rendering, so changes to it do not cause the `paint` event to fire in the next rendering update. When the canvas element transform is set, the element's accessibility information is updated to include geometry information (for more information, see [Accessibility](#accessibility)). * The hit test clipping of a `drawable` element can be set with a canvas element clip, which is a DOMRect in the coordinate space of the canvas element transform. This is useful for cases where only a portion of an element is drawn. The canvas element clip is not used for rendering, so changes to it do not cause the `paint` event to fire in the next rendering update. The `clearElementGeometry` method clears the above state. `updateElementGeometry` is automatically run when drawing an element into a 2D context using `drawElementImage`. This behavior can be customized with `DrawElementImageOptions` by passing `{ preserveElementGeometry: true }` to `drawElementImage` to disable automatic geometry updates. 3D contexts must call `updateElementGeometry` because, unlike 2D contexts, the transform from the element's drawn location in a texture to the canvas's CSS coordinates is not available in the canvas API. On worker threads there is no synchronous access to DOM APIs. When updating element geometry for an `OffscreenCanvas` (note that only `ElementImage` references may be passed from a worker), the updates are added to an internal pending notification queue, and a microtask is queued to batch them. On a worker thread, this microtask asynchronously posts a task to the main thread. Main-thread `OffscreenCanvas` geometry updates are similarly batched via a microtask. When the main-thread updates complete, the elements synchronously apply their geometry changes, and an `elementgeometryupdate` event is fired on the associated `HTMLCanvasElement` with a list of the elements that were updated. If an element no longer exists when the event fires, it is omitted from the list. This batching approach, as opposed to issuing a stand-alone update for each drawing API call, is similar to existing "observer" APIs and ensures that updates are applied atomically without other tasks interleaving. ### Basic Example a screenshot showing a form element with a blinking cursor ```html
``` ### IDL changes ```idl dictionary UpdateElementGeometryOptions { // Controls how the canvas's hit testing order stack should be modified. // If this is true and the element is already in the canvas's hit testing // stack, do nothing. In all other cases, place the element at the top of // the canvas's hit testing stack. boolean preserveHitTestOrder = false; // Sets the element's canvas clip used for hit testing, evaluated in the // coordinate space of `canvasTransform`. If omitted, the pre-existing // value of the element's canvas clip is preserved. DOMRectInit canvasClip; // Sets the element's canvas transform which maps the element's border // box, before CSS transforms, to the canvas. If omitted, the // pre-existing value of the element's canvas transform is preserved. DOMMatrixInit canvasTransform; }; dictionary ElementImageDefaultSize { double width; double height; }; partial interface HTMLCanvasElement { [CEReactions, Reflect, ReflectOnly=("fallback", "drawable"), ReflectMissing="fallback", ReflectInvalid="fallback"] attribute DOMString content; attribute EventHandler onpaint; void requestPaint(); ElementImage captureElementImage(Element element); // Allows manual geometry updates (primarily for WebGL/WebGPU). void updateElementGeometry( (Element or ElementImage) element, optional UpdateElementGeometryOptions options = {}); void clearElementGeometry((Element or ElementImage) element); // Returns the current transform applied to the Element to map its border // box, before CSS transforms, to the canvas coordinate space, or an // identity DOMMatrix if no transform has been set. Updated with // `updateElementGeometry` and cleared with `clearElementGeometry`. [NewObject] DOMMatrix getElementTransform(Element element); // Fired when the browser completes applying geometry updates originating // from an OffscreenCanvas. attribute EventHandler onelementgeometryupdate; // The default size of the element in canvas grid coordinates. ElementImageDefaultSize getElementImageDefaultSize( (Element or ElementImage) element); }; partial interface OffscreenCanvas { // Updates the element's geometry. When called from a worker thread, // only `ElementImage` may be passed. Worker-thread updates are batched // via a microtask and asynchronously posted to the main thread. // Main-thread updates are also batched via a microtask. When the // main-thread updates of element geometry complete, an // `elementgeometryupdate` event is fired on the associated // HTMLCanvasElement. void updateElementGeometry( (Element or ElementImage) element, optional UpdateElementGeometryOptions options = {}); // Clears the element's geometry and fires `elementgeometryupdate` like // `updateElementGeometry`. void clearElementGeometry((Element or ElementImage) element); // The default size of the element in canvas grid coordinates. ElementImageDefaultSize getElementImageDefaultSize( (Element or ElementImage) element); }; dictionary DrawElementImageOptions { // If true, prevents the automatic update of the Element's geometry. // If false, automatically updates the Element's geometry by calling // `updateElementGeometry` with a `canvasTransform` that maps the // element's border-box to the drawn position in the canvas. boolean preserveElementGeometry = false; }; interface mixin CanvasDrawElementImage { void drawElementImage( (Element or ElementImage) element, unrestricted double dx, unrestricted double dy, optional DrawElementImageOptions options = {}); void drawElementImage( (Element or ElementImage) element, unrestricted double dx, unrestricted double dy, unrestricted double dwidth, unrestricted double dheight, optional DrawElementImageOptions options = {}); void drawElementImage( (Element or ElementImage) element, unrestricted double sx, unrestricted double sy, unrestricted double swidth, unrestricted double sheight, unrestricted double dx, unrestricted double dy, optional DrawElementImageOptions options = {}); void drawElementImage( (Element or ElementImage) element, unrestricted double sx, unrestricted double sy, unrestricted double swidth, unrestricted double sheight, unrestricted double dx, unrestricted double dy, unrestricted double dwidth, unrestricted double dheight, optional DrawElementImageOptions options = {}); }; CanvasRenderingContext2D includes CanvasDrawElementImage; OffscreenCanvasRenderingContext2D includes CanvasDrawElementImage; dictionary WebGLCopyElementImageConfig { GLfloat sx; GLfloat sy; GLfloat swidth; GLfloat sheight; GLsizei width; GLsizei height; }; partial interface WebGLRenderingContext { void texElementSubImage2D( GLenum target, GLint level, GLint xoffset, GLint yoffset, (Element or ElementImage) element, optional WebGLCopyElementImageConfig config = {}); }; // Note: `GPUImageCopyTextureTagged` extends `GPUTexelCopyTextureInfo` which // has a required `GPUTexture texture` member for the destination texture. dictionary GPUDrawElementImageDestination : GPUImageCopyTextureTagged { GPUExtent3D size; }; dictionary GPUDrawElementImageSource { required (Element or ElementImage) source; float sourceX; float sourceY; float sourceWidth; float sourceHeight; }; partial interface GPUQueue { void drawElementImageToTexture( GPUDrawElementImageSource source, GPUDrawElementImageDestination destination); }; [Exposed=Window] interface CanvasPaintEvent : Event { constructor(DOMString type, optional CanvasPaintEventInit eventInitDict); [SameObject] readonly attribute FrozenArray changedElements; }; dictionary CanvasPaintEventInit : EventInit { sequence changedElements = []; }; [Exposed=(Window,Worker), Transferable] interface ElementImage { undefined close(); }; // OffscreenCanvas element geometry update notifications. [Exposed=Window] interface ElementGeometryUpdateEvent : Event { constructor( DOMString type, optional ElementGeometryUpdateEventInit eventInitDict = {}); [SameObject] readonly attribute FrozenArray elements; }; dictionary ElementGeometryUpdateEventInit : EventInit { sequence elements = []; }; ``` ## Demos #### [Live demo](https://wicg.github.io/html-in-canvas/Examples/complex-text.html) ([source](Examples/complex-text.html)) using the `drawElementImage` API to draw rotated complex text. screenshot showing rotated, complex text drawn into canvas #### [Live demo](https://wicg.github.io/html-in-canvas/Examples/pie-chart.html) ([source](Examples/pie-chart.html)) using the `drawElementImage` API to draw a pie chart with multi-line labels. screenshot showing a pie chart #### [Live demo](https://wicg.github.io/html-in-canvas/Examples/webgpu-jelly-slider/) ([source](Examples/webgpu-jelly-slider)) using the WebGPU `drawElementImageToTexture` API to draw a div under a jelly slider. screenshot showing a range slider with a jelly effect #### [Live demo](https://wicg.github.io/html-in-canvas/Examples/webGL.html) ([source](Examples/webGL.html)) using the WebGL `texElementSubImage2D` API to draw HTML onto a 3D card. screenshot showing html content on a 3D card A demo of the same thing using an experimental extension of [three.js](https://threejs.org/) is [here](https://raw.githack.com/mrdoob/three.js/htmltexture/examples/webgl_materials_texture_html.html). Further instructions and context are [here](https://github.com/mrdoob/three.js/pull/31233). #### [Live demo](https://wicg.github.io/html-in-canvas/Examples/nested-sparkles.html) ([source](Examples/nested-sparkles.html)) of nested drawable elements. screenshot showing the roses are red poem ## Read-back-allowed rendering The `drawElementImage()` method and any other methods that draw element image snapshots, as well as the paint event, must not reveal any security- or privacy-sensitive information that isn't otherwise observable to author code. This concept is called read-back-allowed rendering because it makes it possible to allow pixel read-back, which is always possible with WebGL and WebGPU. Both painting (via canvas pixel readbacks or timing attacks) and invalidation (via `onpaint`) have the potential to leak sensitive information, and this is prevented by excluding sensitive information when painting and invalidating. Sensitive information includes: * Cross-origin data in [embedded content](https://html.spec.whatwg.org/#embedded-content-category) (e.g., `