### WebGL texElementSubImage2D Usage Example Source: https://github.com/wicg/html-in-canvas/blob/main/_autodocs/api-reference/webgl-tex-element-sub-image-2d.md A basic example showing how to call texElementSubImage2D after binding a texture. ```js // Bind the texture, then: gl.texElementSubImage2D(gl.TEXTURE_2D, level, xoffset, yoffset, form); ``` -------------------------------- ### Setup drawElementImage basic scenario Source: https://github.com/wicg/html-in-canvas/blob/main/_autodocs/tests/html-canvas-element-paint-basic.test.md Initializes the canvas and form elements, setting up the onpaint event handler to draw the form at specific coordinates. ```js // setup (README.md:60-65) const canvas = document.querySelector('canvas'); const form = document.querySelector('canvas form'); const ctx = canvas.getContext('2d'); canvas.onpaint = () => { ctx.reset(); ctx.drawElementImage(form, 100, 0, { preserveElementGeometry: true, // this demo opts out explicitly }); }; ``` -------------------------------- ### WebGPU jelly slider implementation Source: https://github.com/wicg/html-in-canvas/blob/main/_autodocs/api-reference/webgpu-draw-element-image-to-texture.md An example of using drawElementImageToTexture within an onpaint handler to update a texture from a slider element. ```ts // Examples/webgpu-jelly-slider/src/index.ts:773-782 (canvas as any).onpaint = () => { const sourceDict = { source: canvas.captureElementImage(sliderElement), sourceX: 0, sourceY: 0, sourceWidth: sliderElement.clientWidth, sourceHeight: sliderElement.clientHeight, }; const destDict = { texture: texture, size: [textureWidth, textureHeight], }; root.device.queue.drawElementImageToTexture(sourceDict, destDict as any); (canvas as any).requestPaint(); }; ``` -------------------------------- ### CanvasPaintEvent Handler Implementation Source: https://github.com/wicg/html-in-canvas/blob/main/_autodocs/api-reference/canvas-paint-event.md Example of handling the paint event to redraw changed elements on a 2D canvas context. ```js const canvas = document.querySelector('canvas'); const form = document.querySelector('canvas form'); const ctx = canvas.getContext('2d'); canvas.onpaint = (event) => { // `event.changedElements` lists which drawable descendants changed. ctx.reset(); if (event.changedElements.includes(form)) { ctx.drawElementImage(form, 100, 0); } // NOTE: drawing commands here appear in this rendering update. }; canvas.requestPaint(); // Ask for an initial paint event (README prose). ``` -------------------------------- ### Render HTML Form in Canvas Source: https://github.com/wicg/html-in-canvas/blob/main/_autodocs/README.md Demonstrates how to use the 'drawable' content attribute on a canvas element to render an embedded form. The example includes a ResizeObserver to ensure the canvas resolution matches the device pixel scale. ```html
``` -------------------------------- ### Draw ElementImage into a texture Source: https://github.com/wicg/html-in-canvas/blob/main/_autodocs/tests/webgpu-draw-element-image-to-texture.test.md Example of using drawElementImageToTexture to draw an element into a texture within a test environment. ```js test('drawElementImageToTexture draws an ElementImage into a texture', async () => { const values = document.getElementById('values'); const dst = { texture: t, size: [w, h] }; const src = { source: img, sourceWidth: values.offsetWidth * dpr, sourceHeight: values.offsetHeight * dpr }; queue.drawElementImageToTexture(src, dst); }); ``` -------------------------------- ### HTML Setup for drawable canvas Source: https://github.com/wicg/html-in-canvas/blob/main/_autodocs/tests/basic-2d-draw-element-image.test.md The canvas element must have the content="drawable" attribute, and the child elements intended for drawing must have the drawable attribute. ```html
``` -------------------------------- ### Initialize WebGL Context and Shaders Source: https://github.com/wicg/html-in-canvas/blob/main/Examples/webGL.html Sets up the WebGL2 context, compiles vertex and fragment shaders, and initializes buffers and textures. ```javascript function setupGL() { const canvas = document.querySelector('#gl-canvas'); // Initialize the GL context const gl = canvas.getContext('webgl2'); // Only continue if WebGL is available and working if (gl === null) { alert( 'Unable to initialize WebGL. Your browser or machine may not support it.', ); return; } // Vertex shader program const vsSource = ` attribute vec4 aVertexPosition; attribute vec2 aTextureCoord; uniform mat4 uModelViewMatrix; uniform mat4 uProjectionMatrix; varying highp vec2 vTextureCoord; void main(void) { gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition; vTextureCoord = aTextureCoord; } `; // Fragment shader program const fsSource = ` varying highp vec2 vTextureCoord; uniform sampler2D uSampler; void main(void) { gl_FragColor = texture2D(uSampler, vTextureCoord); } `; const shaderProgram = initShaderProgram(gl, vsSource, fsSource); const programInfo = { program: shaderProgram, attribLocations: { vertexPosition: gl.getAttribLocation(shaderProgram, 'aVertexPosition'), textureCoord: gl.getAttribLocation(shaderProgram, 'aTextureCoord'), }, uniformLocations: { projectionMatrix: gl.getUniformLocation(shaderProgram, 'uProjectionMatrix'), modelViewMatrix: gl.getUniformLocation(shaderProgram, 'uModelViewMatrix'), uSampler: gl.getUniformLocation(shaderProgram, 'uSampler'), }, }; const buffers = initBuffers(gl); // Initialize textures without drawing immediately, waiting for onpaint to fill them const texture_checkboxes = createEmptyTexture(gl); const texture_choice = createEmptyTexture(gl); // Flip image pixels into the bottom-to-top order that WebGL expects. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true); render_context = { gl: gl, program: programInfo, buffers: buffers, texture_checkboxes: texture_checkboxes, texture_choice: texture_choice, }; } ``` -------------------------------- ### Worker updateElementGeometry usage Source: https://github.com/wicg/html-in-canvas/blob/main/_autodocs/api-reference/offscreen-canvas.md Example of updating element geometry from a worker thread using a transferred ElementImage. ```js // slider-worker.js let queue = new Map(); self.onmessage = async ({ data }) => { if (data.type === 'geom') { // ElementImage transferred from the main thread. offscreen.updateElementGeometry(data.img, { canvasTransform: data.transform, }); } }; ``` -------------------------------- ### Basic HTML in Canvas implementation Source: https://github.com/wicg/html-in-canvas/blob/main/README.md Demonstrates how to define a drawable canvas containing a form and use the onpaint event to render the form element onto the canvas context. ```html
``` -------------------------------- ### Worker getElementImageDefaultSize usage Source: https://github.com/wicg/html-in-canvas/blob/main/_autodocs/api-reference/offscreen-canvas.md Example of retrieving the default size of an element in a worker thread to pre-size a destination rectangle before drawing. ```js // worker const { width, height } = offscreen.getElementImageDefaultSize(img); // Pre-size a destination rect before drawing. ctx.drawElementImage(img, 0, 0, width, height); ``` -------------------------------- ### Crop drawable snapshot with source rect Source: https://github.com/wicg/html-in-canvas/blob/main/_autodocs/tests/webgpu-draw-element-image-to-texture.test.md Shows how to use sourceX, sourceY, sourceWidth, and sourceHeight to crop the captured element image. ```js test('source rect crops the drawable snapshot', () => { const config = { source, sourceX: 10, sourceY: 10, sourceWidth: 50, sourceHeight: 50 }; queue.drawElementImageToTexture(config, { texture: t, size: [50, 50] }); }); ``` -------------------------------- ### Error handling and waiting for first snapshot Source: https://github.com/wicg/html-in-canvas/blob/main/_autodocs/api-reference/canvas-draw-element-image.md Illustrates how to use the onpaint event to ensure drawing only occurs after the first snapshot is ready. ```js // Before the first onpaint, capture/draw throws. Use the paint event to know // when drawing becomes legal. let ready = false; canvas.onpaint = () => { ready = true; ctx.drawElementImage(form, 0, 0); }; // Later, from other code: if (ready) { ctx.drawElementImage(spanish, 10, 10); } else { canvas.requestPaint(); // Request the next paint event. } ``` -------------------------------- ### Preserving semantics in canvas with drawable elements Source: https://github.com/wicg/html-in-canvas/blob/main/README.md An example demonstrating how to preserve the semantics of a figure, image, and caption while drawing them separately on a canvas. ```html
image alt text
A caption
``` -------------------------------- ### Texture upload using paint event Source: https://github.com/wicg/html-in-canvas/blob/main/_autodocs/tests/webgl-tex-element-sub-image-2d.test.md Demonstrates initializing a texture and updating it within the canvas onpaint event handler. ```js test('paint event + texElementSubImage2D updates a WebGL texture', async () => { const canvas = document.querySelector('#gl-canvas'); const form = document.querySelector('#choice'); const gl = canvas.getContext('webgl2'); // README.md:319-323 — init textures once, refresh during `paint`. let texture = createEmptyTexture(glapse); canvas.onpaint = () => { gl.bindTexture(gl.TEXTURE_2D, texture); updateTexture(gl, texture, form); // calls texElementSubImage2D canvas.getElementImageDefaultSize(form); // README:139-140, 159-162 }; canvas.requestPaint(); // README:117 — fire paint during next rendering update }); ``` -------------------------------- ### Options & Dictionaries Source: https://github.com/wicg/html-in-canvas/blob/main/_autodocs/README.md Configuration types used across the API. ```APIDOC ## Options & Dictionaries ### Description Configuration types used across the HTML in Canvas API. ### Types - `UpdateElementGeometryOptions` - `DrawElementImageOptions` - `WebGLCopyElementImageConfig` - GPU dictionaries ### Reference [types](types.md) ``` -------------------------------- ### Worker Geometry Update Event Source: https://github.com/wicg/html-in-canvas/blob/main/_autodocs/tests/offscreen-canvas-worker-geometry.test.md Example of posting geometry updates from a worker and handling the resulting elementgeometryupdate event on the main thread. ```js test('worker updateElementGeometry fires elementgeometryupdate', async () => { const img = canvas.captureElementImage(form); worker.postMessage({ cmd: 'update', img, transform }, [img]); await new Promise(resolve => { canvas.onelementgeometryupdate = (ev) => { assert.include(ev.elements, form); assert.deepEqual(canvas.getElementTransform(form), transform); resolve(); }; }); }); ``` -------------------------------- ### OffscreenCanvas worker thread implementation Source: https://github.com/wicg/html-in-canvas/blob/main/README.md This example captures a canvas child form as an ElementImage in the paint event and transfers it to a worker thread for rendering. ```html
``` -------------------------------- ### WebGLCopyElementImageConfig Source: https://github.com/wicg/html-in-canvas/blob/main/_autodocs/configuration.md Options dictionary for WebGLRenderingContext.texElementSubImage2D(). ```APIDOC ## WebGLCopyElementImageConfig ### Description Options for copying an element image to a WebGL texture. ### Members - **sx** (GLfloat) - Optional - Source x coordinate of the element to copy. - **sy** (GLfloat) - Optional - Source y coordinate of the element to copy. - **swidth** (GLfloat) - Optional - Source width for clipping/ink overflow. - **sheight** (GLfloat) - Optional - Source height for clipping/ink overflow. - **width** (GLsizei) - Optional - Destination texture width in texels. - **height** (GLsizei) - Optional - Destination texture height in texels. ### IDL ```idl dictionary WebGLCopyElementImageConfig { GLfloat sx; GLfloat sy; GLfloat swidth; GLfloat sheight; GLsizei width; GLsizei height; }; ``` ``` -------------------------------- ### Onpaint loop with drawElementImageToTexture Source: https://github.com/wicg/html-in-canvas/blob/main/_autodocs/tests/webgpu-draw-element-image-to-texture.test.md Demonstrates calling the draw method inside an onpaint handler and scheduling the next paint. ```js test('onpaint draws to texture, requestPaint continues the loop', () => { canvas.onpaint = () => { queue.drawElementImageToTexture(src, dst); canvas.requestPaint(); // loop like README.md:60-63, 726-724 }; }); ``` -------------------------------- ### JavaScript for Drawing Pie Chart with HTML in Canvas Source: https://github.com/wicg/html-in-canvas/blob/main/Examples/pie-chart.html Uses the canvas onpaint event to draw the pie chart. It centers the coordinate system, creates radial gradients for each slice, draws wedges using Path2D, and renders label elements with drawElementImage. It also draws a focus ring for the active label and requests an initial paint. A ResizeObserver adjusts the canvas size based on device pixel ratio. ```javascript const canvas = document.querySelector('canvas'); const ctx = canvas.getContext('2d'); canvas.onpaint = () => { ctx.reset(); // 1. Center the coordinate system. const radius = 0.95 * Math.min(canvas.width, canvas.height) / 2; ctx.translate(canvas.width / 2, canvas.height / 2); let angle = 0; let focusedPath = null; for (const label of canvas.children) { const slice = Number(label.dataset.val) * Math.PI * 2; // 2. Draw the wedge. const grad = ctx.createRadialGradient(0, 0, 0, 0, 0, radius); grad.addColorStop(0, `color-mix(${label.dataset.color}, white 40%)`); grad.addColorStop(1, label.dataset.color); ctx.fillStyle = grad; const path = new Path2D(); path.moveTo(0, 0); path.arc(0, 0, radius, angle, angle + slice); path.closePath(); ctx.fill(path); if (document.activeElement === label) focusedPath = path; // 3. Draw the label element, and update its transform. const mid = angle + slice / 2; const label_width = label.offsetWidth * devicePixelRatio; const label_height = label.offsetHeight * devicePixelRatio; const x = Math.cos(mid) * radius * 0.60 - label_width / 2; const y = Math.sin(mid) * radius * 0.60 - label_height / 2; ctx.drawElementImage(label, x, y); angle += slice; } // 4. Draw the focus ring on top of everything else. if (focusedPath) ctx.drawFocusIfNeeded(focusedPath, document.activeElement); }; canvas.requestPaint(); // Request an initial paint event. // Setup a resize observer to resize the canvas in response to dpr changes. new ResizeObserver(([entry]) => { const box = entry.devicePixelContentBoxSize[0]; canvas.width = box.inlineSize; canvas.height = box.blockSize; }).observe(canvas, {box: ['device-pixel-content-box']}); ``` -------------------------------- ### CanvasPaintEventInit dictionary Source: https://github.com/wicg/html-in-canvas/blob/main/_autodocs/api-reference/canvas-paint-event.md Initialization dictionary for the CanvasPaintEvent constructor, containing a changedElements sequence. ```APIDOC ## CanvasPaintEventInit dictionary ### Description Used to initialize a CanvasPaintEvent. Contains a sequence of Element objects representing changed elements. ### Members - **changedElements** (sequence) - Optional - Default: [] - The list of changed drawable descendant elements. ### Example const init = { changedElements: [element1, element2] }; const event = new CanvasPaintEvent('paint', init); ``` -------------------------------- ### Geometry Update Batching Source: https://github.com/wicg/html-in-canvas/blob/main/_autodocs/tests/offscreen-canvas-worker-geometry.test.md Demonstrates how multiple geometry updates are coalesced into a single event per frame via microtasks. ```js test('geometry batching publishes one elementgeometryupdate per frame', async () => { const updates = 4; let notified = 0, events = 0; canvas.onelementgeometryupdate = () => events++; for (let k = 0; k < updates; k++) offscreen.updateElementGeometry(img, { preserveElementGeometry: true }); await microtaskFlush(); assert.ok(events <= 1, 'microtask batches the four updates'); assert.equal(notified, updates); // all elements listed in the single event }); ``` -------------------------------- ### Test conventions for pseudo-code assertions Source: https://github.com/wicg/html-in-canvas/blob/main/_autodocs/tests/offscreen-canvas-and-worker.test.md Conventions used in this file since the repo has no test runner. Tests are marked with expect(...) or assert.* pseudo-code. ```javascript // conventions used in this file (repo has no runner; tests are marked with // `expect(...)` / `assert.*` pseudo-code — see tests/README.md): expect(canvas.onelementgeometryupdate).toBeInstanceOf(Function); // EventHandler ptr canvas.onpaint = () => {}; expect(canvas.onpaint).toBe(canvas.onpaint); ``` -------------------------------- ### Basic rectangle draw with auto geometry sync Source: https://github.com/wicg/html-in-canvas/blob/main/_autodocs/api-reference/canvas-draw-element-image.md Demonstrates a simple drawElementImage call within the canvas onpaint event. ```js canvas.onpaint = () => { ctx.reset(); ctx.drawElementImage(form, 100, 0onti); }; ``` -------------------------------- ### Test canvas layout and paint events Source: https://github.com/wicg/html-in-canvas/blob/main/_autodocs/tests/basic-2d-draw-element-image.test.md Tests the initial layout of the drawable subtree, the requirement for an initial snapshot, and the triggering of the paint event. ```js test('canvas with content="drawable" lays out its drawable subtree', async () => { const canvas = document.querySelector('canvas'); const form = canvas.querySelector('form'); const ctx = canvas.getContext('2d'); // 1. `content="drawable"` blockifies and lays out immediate descendants // (README.md:27-30). `form` participates in layout with static // positioning. assert.equal(canvas.content, 'drawable'); // reflected attribute assert.equal(form.getAttribute('drawable'), ''); // present, empty value // 2. Initially no geometry is known; capture throws or no `paint` yet // (README.md:38-40, 43-44: must have an initial snapshot). await assert.rejects( new Promise((resolve) => canvas.onpaint = resolve), // not fired yet ); assert.throws(() => ctx.drawElementImage(form, 100, 0), /snapshot/i); // 3. `requestPaint` schedules a `paint` event for the next rendering // opportunity even with no changes (README.md:36-37, IDL 117). const paintPromise = new Promise((resolve) => (canvas.onpaint = resolve)); canvas.requestPaint(); const paintEvent = await paintPromise; assert.equal(paintEvent.type, 'paint'); assert.ok(paintEvent instanceof CanvasPaintEvent); assert.ok(paintEvent.changedElements.includes(form), 'initial paint reports the drawable descendants changed'); // 4. Drawing inside `onpaint` writes into the canvas for this rendering // update; DOM mutations happen next update (README.md:34-35). }); ``` -------------------------------- ### GPUDrawElementImageSource and GPUDrawElementImageDestination Source: https://github.com/wicg/html-in-canvas/blob/main/_autodocs/configuration.md Options dictionaries for GPUQueue.drawElementImageToTexture(). ```APIDOC ## GPUDrawElementImageSource ### Description Source options for drawing an element image to a GPU texture. ### Members - **source** (Element or ElementImage) - Required - The source element or image. - **sourceX** (float) - Optional - Source x coordinate. - **sourceY** (float) - Optional - Source y coordinate. - **sourceWidth** (float) - Optional - Source width. - **sourceHeight** (float) - Optional - Source height. ### IDL ```idl dictionary GPUDrawElementImageSource { required (Element or ElementImage) source; float sourceX; float sourceY; float sourceWidth; float sourceHeight; }; ``` ## GPUDrawElementImageDestination ### Description Destination options for drawing an element image to a GPU texture. ### Members - **size** (GPUExtent3D) - Optional - Destination size. ### IDL ```idl dictionary GPUDrawElementImageDestination : GPUImageCopyTextureTagged { GPUExtent3D size; }; ``` ``` -------------------------------- ### Canvas Paint Event Handler Source: https://github.com/wicg/html-in-canvas/blob/main/Examples/webGL.html Main event loop that initializes WebGL on the first paint and updates textures when elements change. ```javascript onload = () => { const canvas = document.querySelector('#gl-canvas'); let initialized_gl = false; let lastLangId = null; // The main paint event loop. canvas.onpaint = (event) => { if (!initialized_gl) { setupGL(); initialized_gl = true; } if (event.changedElements && event.changedElements.length) { // Convert elements into an array if they are not already to safely use array methods const changedArray = Array.from(event.changedElements); const choiceEl = document.getElementById("choice"); const checkedLang = document.querySelector('input[name="language"]:checked'); const langId = checkedLang ? checkedLang.value : "english"; const langEl = document.getElementById(langId); // Update the checkboxes texture if the choice element changed if (changedArray.includes(choiceEl)) { updateTexture(render_context.gl, render_context.texture_checkboxes, choiceEl); } // Update the choice texture if its content changed, or if the user selected a new language if (changedArray.includes(langEl) || langId !== lastLangId) { updateTexture(render_context.gl, render_context.texture_choice, langEl); lastLangId = langId; } } render(); // Loop to continuously fire canvas paint events. ``` -------------------------------- ### drawElementImage(sx, sy, swidth, sheight, dx, dy, dwidth, dheight, options) Source: https://github.com/wicg/html-in-canvas/blob/main/_autodocs/api-reference/canvas-draw-element-image.md Draws the element snapshot using a source rectangle (sx, sy, swidth, sheight) and a destination rectangle (dx, dy, dwidth, dheight). This overload matches the fourth CanvasImageSource.drawImage overload. ```APIDOC ## drawElementImage(sx, sy, swidth, sheight, dx, dy, dwidth, dheight, options) ### Description Draws the last snapshot of the element and its drawable subtree into the canvas, using a source rectangle to select a portion of the element and scaling it to the destination rectangle. ### Method Canvas method ### Parameters #### Source Rect - **sx** (number) - Required - The x-coordinate of the source rectangle. - **sy** (number) - Required - The y-coordinate of the source rectangle. - **swidth** (number) - Required - The width of the source rectangle. - **sheight** (number) - Required - The height of the source rectangle. #### Destination Rect - **dx** (number) - Required - The x-coordinate of the destination position. - **dy** (number) - Required - The y-coordinate of the destination position. - **dwidth** (number) - Required - The width of the destination rectangle. - **dheight** (number) - Required - The height of the destination rectangle. #### Options - **preserveElementGeometry** (boolean) - Optional - Default false. If false, automatically runs updateElementGeometry with a canvasTransform mapping the element's border-box to the drawn position. If true, prevents the automatic geometry update. ### Notes - The source rect reference frame uses full canvas grid coordinates of the drawn element; can apply outsets for clipping or to include ink overflow beyond the border box. - Rendering starts at the element's border box, before CSS transforms. ``` -------------------------------- ### updateTexture implementation Source: https://github.com/wicg/html-in-canvas/blob/main/_autodocs/tests/webgl-tex-element-sub-image-2d.test.md Shows the sequence of binding a texture and calling texElementSubImage2D to update the texture content. ```js gl.tgenerateint = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, t); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texElementSubImage2D(gl.TEXTURE_2D, 0, 0, 0, form); ``` -------------------------------- ### drawElementImage(sx, sy, swidth, sheight, dx, dy, options) Source: https://github.com/wicg/html-in-canvas/blob/main/_autodocs/api-reference/canvas-draw-element-image.md Draws the element snapshot using a source rectangle (sx, sy, swidth, sheight) and a destination position (dx, dy) at native size. This overload matches the third CanvasImageSource.drawImage overload. ```APIDOC ## drawElementImage(sx, sy, swidth, sheight, dx, dy, options) ### Description Draws the last snapshot of the element and its drawable subtree into the canvas, using a source rectangle to select a portion of the element and drawing it at the given destination position at native size. ### Method Canvas method ### Parameters #### Source Rect - **sx** (number) - Required - The x-coordinate of the source rectangle. - **sy** (number) - Required - The y-coordinate of the source rectangle. - **swidth** (number) - Required - The width of the source rectangle. - **sheight** (number) - Required - The height of the source rectangle. #### Destination Rect - **dx** (number) - Required - The x-coordinate of the destination position. - **dy** (number) - Required - The y-coordinate of the destination position. #### Options - **preserveElementGeometry** (boolean) - Optional - Default false. If false, automatically runs updateElementGeometry with a canvasTransform mapping the element's border-box to the drawn position. If true, prevents the automatic geometry update. ### Notes - The source rect reference frame uses full canvas grid coordinates of the drawn element; can apply outsets for clipping or to include ink overflow beyond the border box. - Rendering starts at the element's border box, before CSS transforms. ``` -------------------------------- ### Resize canvas with ResizeObserver and requestPaint Source: https://github.com/wicg/html-in-canvas/blob/main/Examples/webGL.html Use this snippet to keep a canvas element's backing store size in sync with its CSS size, accounting for device pixel ratio. It observes the canvas with the 'device-pixel-content-box' option and calls requestPaint after resizing. ```javascript canvas.requestPaint(); } canvas.requestPaint(); const observer = new ResizeObserver(([entry]) => { canvas.width = entry.devicePixelContentBoxSize[0].inlineSize; canvas.height = entry.devicePixelContentBoxSize[0].blockSize; canvas_css_width = entry.contentBoxSize[0].inlineSize; canvas_css_height = entry.contentBoxSize[0].blockSize; }); observer.observe(canvas, {box: 'device-pixel-content-box'}); } ``` -------------------------------- ### requestPaint schedules fresh paint events Source: https://github.com/wicg/html-in-canvas/blob/main/_autodocs/tests/webgl-tex-element-sub-image-2d.test.md Verifies that calling requestPaint schedules paint events to fire during the next rendering opportunity, even without DOM changes. ```js test('requestPaint schedules fresh paint events even without DOM change', () => { let paints = 0; canvas.onpaint = () => paints++; canvas.requestPaint(); // fires once per rendering update (32, 36-37) assert.equal(paints, 1); canvas.requestPaint(); assert.equal(paints, 2); }); ``` -------------------------------- ### CanvasPaintEvent constructor Source: https://github.com/wicg/html-in-canvas/blob/main/_autodocs/api-reference/canvas-paint-event.md Creates a new CanvasPaintEvent instance with the given type and optional initialization dictionary. ```APIDOC ## CanvasPaintEvent constructor ### Description Creates a new CanvasPaintEvent object. The event is used to notify the page which drawable canvas descendants have changed snapshots. ### Syntax new CanvasPaintEvent(type, eventInitDict) ### Parameters - **type** (DOMString) - Required - The event type, typically 'paint'. - **eventInitDict** (CanvasPaintEventInit) - Optional - An initialization dictionary with a changedElements sequence of Element objects. Defaults to {}. ### Example const event = new CanvasPaintEvent('paint', { changedElements: [element] }); ``` -------------------------------- ### Capture, transfer, and draw ElementImage from a worker Source: https://github.com/wicg/html-in-canvas/blob/main/_autodocs/api-reference/element-image.md Demonstrates capturing an element image on the main thread, transferring it to a worker, and drawing it onto an OffscreenCanvas context before closing the snapshot. ```js // main thread const img = canvas.captureElementImage(form); worker.postMessage({ img }, [img]); // [Transferable] // worker let ctx = offscreen.getContext('2d'); self.onmessage = (e) => { if (e.data.img) { ctx.reset(); ctx.drawElementImage(e.data.img, 100, 0); e.data.img.close(); } }; ``` -------------------------------- ### drawElementImage(element, dx, dy, options) Source: https://github.com/wicg/html-in-canvas/blob/main/_autodocs/api-reference/canvas-draw-element-image.md Draws the snapshot of the given element or ElementImage at the specified destination coordinates (dx, dy) with its intrinsic size. This is the first overload of the drawElementImage method. ```APIDOC ## drawElementImage(element, dx, dy, options) ### Description Draws the snapshot of the given element or ElementImage at the specified destination coordinates (dx, dy) with its intrinsic size. ### Method void drawElementImage((Element or ElementImage) element, unrestricted double dx, unrestricted double dy, optional DrawElementImageOptions options = {}) ### Parameters - **element** ((Element or ElementImage)) - Required - The element or ElementImage whose snapshot is to be drawn. - **dx** (unrestricted double) - Required - The x-coordinate in the canvas at which to place the top-left corner of the snapshot. - **dy** (unrestricted double) - Required - The y-coordinate in the canvas at which to place the top-left corner of the snapshot. - **options** (DrawElementImageOptions) - Optional - An optional dictionary with the following field: - **preserveElementGeometry** (boolean) - Optional - 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. Default is false. ### Return Value void ``` -------------------------------- ### WebGLRenderingContext.texElementSubImage2D(target, level, xoffset, yoffset, element, config) Source: https://github.com/wicg/html-in-canvas/blob/main/_autodocs/README.md Uploads an HTML element as a texture sub-image in WebGL. ```APIDOC ## WebGLRenderingContext.texElementSubImage2D(target, level, xoffset, yoffset, element, config) ### Description Uploads an HTML element as a texture sub-image in WebGL. ### Method `texElementSubImage2D(target, level, xoffset, yoffset, element, config)` ### Parameters - `target` - Texture target. - `level` - Mipmap level. - `xoffset`, `yoffset` - Offset in the texture. - `element` - HTML element to upload. - `config` - Configuration object (`WebGLCopyElementImageConfig`). ### Applies To `WebGLRenderingContext` partial ### Reference [webgl-tex-element-sub-image-2d](api-reference/webgl-tex-element-sub-image-2d.md) ```