From 9955f751b3a2e3dc3bfb8a0641d6f26fa505d345 Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Fri, 23 Oct 2026 14:36:56 +0100 Subject: [PATCH 01/12] Add HTML-in-canvas demos --- html-in-canvas/2d-context-example/index.html | 24 ++ html-in-canvas/2d-context-example/index.js | 27 ++ .../2d-context-example/pointer-distort.js | 122 ++++++ html-in-canvas/2d-context-example/style.css | 34 ++ html-in-canvas/README.md | 7 + html-in-canvas/webgl-example/draw-scene.js | 136 +++++++ html-in-canvas/webgl-example/index.html | 30 ++ html-in-canvas/webgl-example/init-buffers.js | 139 +++++++ html-in-canvas/webgl-example/style.css | 41 ++ html-in-canvas/webgl-example/webgl-demo.js | 223 +++++++++++ html-in-canvas/webgpu-demo/index.html | 25 ++ html-in-canvas/webgpu-demo/style.css | 41 ++ html-in-canvas/webgpu-demo/webgpu-demo.js | 357 ++++++++++++++++++ 13 files changed, 1206 insertions(+) create mode 100644 html-in-canvas/2d-context-example/index.html create mode 100644 html-in-canvas/2d-context-example/index.js create mode 100644 html-in-canvas/2d-context-example/pointer-distort.js create mode 100644 html-in-canvas/2d-context-example/style.css create mode 100644 html-in-canvas/README.md create mode 100644 html-in-canvas/webgl-example/draw-scene.js create mode 100644 html-in-canvas/webgl-example/index.html create mode 100644 html-in-canvas/webgl-example/init-buffers.js create mode 100644 html-in-canvas/webgl-example/style.css create mode 100644 html-in-canvas/webgl-example/webgl-demo.js create mode 100644 html-in-canvas/webgpu-demo/index.html create mode 100644 html-in-canvas/webgpu-demo/style.css create mode 100644 html-in-canvas/webgpu-demo/webgpu-demo.js diff --git a/html-in-canvas/2d-context-example/index.html b/html-in-canvas/2d-context-example/index.html new file mode 100644 index 00000000..4955c3a5 --- /dev/null +++ b/html-in-canvas/2d-context-example/index.html @@ -0,0 +1,24 @@ + + + + + HTML-in-Canvas basic test + + + + + +
+
+ + +
+
+ + +
+ +
+
+ + diff --git a/html-in-canvas/2d-context-example/index.js b/html-in-canvas/2d-context-example/index.js new file mode 100644 index 00000000..242bf9b1 --- /dev/null +++ b/html-in-canvas/2d-context-example/index.js @@ -0,0 +1,27 @@ +import { createPointerDistort } from "./pointer-distort.js"; + +function main() { + const canvas = document.querySelector("canvas"); + const form = document.querySelector("canvas form"); + const ctx = canvas.getContext("2d", { willReadFrequently: true }); + + if (!ctx.drawElementImage) { + alert( + "CanvasRenderingContext2D.drawElementImage() is not available. HTML-in-Canvas is not supported.", + ); + return; + } + + const fx = createPointerDistort(canvas, { radius: 120 }); + + function loop(t) { + ctx.fillStyle = "#7D82B8"; + ctx.fillRect(0, 0, canvas.width, canvas.height); + ctx.drawElementImage(form, 100, 100); + fx.apply(t); + requestAnimationFrame(loop); + } + requestAnimationFrame(loop); +} + +main(); diff --git a/html-in-canvas/2d-context-example/pointer-distort.js b/html-in-canvas/2d-context-example/pointer-distort.js new file mode 100644 index 00000000..1155fcff --- /dev/null +++ b/html-in-canvas/2d-context-example/pointer-distort.js @@ -0,0 +1,122 @@ +/** + * Pointer distortion post-effect for an existing 2D canvas. + * Call fx.apply() once per frame, AFTER your scene has been drawn. + * Only pixels near the pointer are read and rewritten, so it stays cheap. + * + * const ctx = canvas.getContext('2d', { willReadFrequently: true }); + * const fx = createPointerDistort(canvas); + * function loop(t) { drawMyScene(ctx, t); fx.apply(t); requestAnimationFrame(loop); } + */ +export function createPointerDistort(canvas, options = {}) { + const o = { + radius: 140, // CSS pixels + swirl: 0.45, // radians of twist at the centre + magnify: 0.18, // 0 = none, higher = stronger lens + ripple: 0.015, // ripple amplitude + chroma: 4, // RGB split in CSS pixels + invert: 0.1, // blend toward inverted colour at centre + ease: 0.18, // pointer smoothing (1 = no lag) + ...options, + }; + const ctx = canvas.getContext("2d", { willReadFrequently: true }); + const m = { x: 0, y: 0, tx: 0, ty: 0, active: false }; + + function onMove(e) { + const r = canvas.getBoundingClientRect(); + const x = ((e.clientX - r.left) * canvas.width) / r.width; + const y = ((e.clientY - r.top) * canvas.height) / r.height; + if (!m.active) { + m.x = x; + m.y = y; + } // snap on entry so it doesn't slide in + m.tx = x; + m.ty = y; + m.active = true; + } + const onLeave = () => { + m.active = false; + }; + canvas.addEventListener("pointermove", onMove); + canvas.addEventListener("pointerleave", onLeave); + + function apply(timeMs = performance.now()) { + if (!m.active) return; + m.x += (m.tx - m.x) * o.ease; + m.y += (m.ty - m.y) * o.ease; + + // Convert CSS-pixel options to canvas pixels (handles devicePixelRatio / resized canvases) + const s = canvas.width / canvas.getBoundingClientRect().width || 1; + const R = o.radius * s, + CA = o.chroma * s, + time = timeMs / 1000; + const pad = Math.ceil(CA) + 2; + + // Fetch only a small box around the pointer + const x0 = Math.max(0, Math.floor(m.x - R - pad)); + const y0 = Math.max(0, Math.floor(m.y - R - pad)); + const x1 = Math.min(canvas.width, Math.ceil(m.x + R + pad)); + const y1 = Math.min(canvas.height, Math.ceil(m.y + R + pad)); + const bw = x1 - x0, + bh = y1 - y0; + if (bw <= 0 || bh <= 0) return; + + const img = ctx.getImageData(x0, y0, bw, bh); // throws if the canvas is tainted (see note below) + const src = img.data; + const dst = new Uint8ClampedArray(src); // copy; we read src, write dst + const mx = m.x - x0, + my = m.y - y0; // pointer in box coordinates + + const px = (x, y, c) => { + x = x < 0 ? 0 : x >= bw ? bw - 1 : x | 0; + y = y < 0 ? 0 : y >= bh ? bh - 1 : y | 0; + return src[(y * bw + x) * 4 + c]; + }; + + for (let y = 0; y < bh; y++) { + for (let x = 0; x < bw; x++) { + const dx = x - mx, + dy = y - my; + const d2 = dx * dx + dy * dy; + if (d2 >= R * R || d2 === 0) continue; + const d = Math.sqrt(d2); + const t = 1 - d / R; + const f = t * t * (3 - 2 * t); // smoothstep falloff + + const a = f * o.swirl, + cos = Math.cos(a), + sin = Math.sin(a); + const k = + 1 - + o.magnify * f + + o.ripple * f * Math.sin((d / s) * 0.14 - time * 3); + const sx = mx + (dx * cos - dy * sin) * k; + const sy = my + (dx * sin + dy * cos) * k; + + const ca = f * CA, + ux = dx / d, + uy = dy / d; + let r = px(sx + ux * ca, sy + uy * ca, 0); + let g = px(sx, sy, 1); + let b = px(sx - ux * ca, sy - uy * ca, 2); + + const inv = f * f * o.invert; + r += (255 - 2 * r) * inv; + g += (255 - 2 * g) * inv; + b += (255 - 2 * b) * inv; + + const i = (y * bw + x) * 4; + dst[i] = r; + dst[i + 1] = g; + dst[i + 2] = b; + } + } + ctx.putImageData(new ImageData(dst, bw, bh), x0, y0); + } + + function destroy() { + canvas.removeEventListener("pointermove", onMove); + canvas.removeEventListener("pointerleave", onLeave); + } + + return { apply, destroy, options: o }; +} diff --git a/html-in-canvas/2d-context-example/style.css b/html-in-canvas/2d-context-example/style.css new file mode 100644 index 00000000..f1c97779 --- /dev/null +++ b/html-in-canvas/2d-context-example/style.css @@ -0,0 +1,34 @@ +form div { + display: flex; + align-items: center; + gap: 10px; + font-family: Arial, Helvetica, sans-serif; + padding: 5px; + border: 4px solid #576490; + background: #d1d2f9; + border-radius: 5px; + margin-bottom: 10px; +} + +form input { + padding: 3px; + border: 2px solid #576490; + border-radius: 3px; +} + +form button { + background: #576490; + border: 4px solid transparent; + color: white; + padding: 10px 10px; + border-radius: 5px; + transition: 0.6s all; + cursor: pointer; +} + +form button:hover, +form button:focus { + background: #d1d2f9; + color: black; + border: 4px solid #576490; +} diff --git a/html-in-canvas/README.md b/html-in-canvas/README.md new file mode 100644 index 00000000..a122544d --- /dev/null +++ b/html-in-canvas/README.md @@ -0,0 +1,7 @@ +# MDN HTML-in-canvas examples + +This set of examples demonstrates usage of the [HTML-in-canvas API](https://github.com/WICG/html-in-canvas): + +- [Canvas 2D context example](2d-context-example/): Demonstrates how an HTML form can be rendered on a 2D canvas, have a pixel distortion effect applied to it on mouseover, but still remain accessible, interactive, and submittable ([run example live](https://mdn.github.io/dom-examples/html-in-canvas/2d-context-example/)). +- [WebGL example](webgl-example/): Adapted from our [WebGL 3D tutorial](https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Tutorial/Creating_3D_objects_using_WebGL), this example shows how to render an HTML form as a texture onto all six sides of a rotating 3D cube. Again, it still remains accessible, interactive, and submittable ([run example live](https://mdn.github.io/dom-examples/html-in-canvas/webgl-example/)). +- [WebGPU example](webgpu-example/): This example is the same as the WebGL example, only converted to use WebGPU instead ([run example live](https://mdn.github.io/dom-examples/html-in-canvas/webgpu-example/)). diff --git a/html-in-canvas/webgl-example/draw-scene.js b/html-in-canvas/webgl-example/draw-scene.js new file mode 100644 index 00000000..db7c2fa5 --- /dev/null +++ b/html-in-canvas/webgl-example/draw-scene.js @@ -0,0 +1,136 @@ +function drawScene(gl, programInfo, buffers, texture, cubeRotation) { + gl.clearColor(0.0, 0.0, 0.0, 1.0); // Clear to black, fully opaque + gl.clearDepth(1.0); // Clear everything + gl.enable(gl.DEPTH_TEST); // Enable depth testing + gl.depthFunc(gl.LEQUAL); // Near things obscure far things + + // Clear the canvas before we start drawing on it. + + gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); + + // Create a perspective matrix, a special matrix that is + // used to simulate the distortion of perspective in a camera. + // Our field of view is 45 degrees, with a width/height + // ratio that matches the display size of the canvas + // and we only want to see objects between 0.1 units + // and 100 units away from the camera. + + const fieldOfView = (45 * Math.PI) / 180; // in radians + const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight; + const zNear = 0.1; + const zFar = 100.0; + const projectionMatrix = mat4.create(); + + // note: glmatrix.js always has the first argument + // as the destination to receive the result. + mat4.perspective(projectionMatrix, fieldOfView, aspect, zNear, zFar); + + // Set the drawing position to the "identity" point, which is + // the center of the scene. + const modelViewMatrix = mat4.create(); + + // Now move the drawing position a bit to where we want to + // start drawing the square. + mat4.translate( + modelViewMatrix, // destination matrix + modelViewMatrix, // matrix to translate + [-0.0, 0.0, -6.0], + ); // amount to translate + + mat4.rotate( + modelViewMatrix, // destination matrix + modelViewMatrix, // matrix to rotate + cubeRotation, // amount to rotate in radians + [0, 0, 1], + ); // axis to rotate around (Z) + mat4.rotate( + modelViewMatrix, // destination matrix + modelViewMatrix, // matrix to rotate + cubeRotation * 0.7, // amount to rotate in radians + [0, 1, 0], + ); // axis to rotate around (Y) + mat4.rotate( + modelViewMatrix, // destination matrix + modelViewMatrix, // matrix to rotate + cubeRotation * 0.3, // amount to rotate in radians + [1, 0, 0], + ); // axis to rotate around (X) + + // Tell WebGL how to pull out the positions from the position + // buffer into the vertexPosition attribute. + setPositionAttribute(gl, buffers, programInfo); + + setTextureAttribute(gl, buffers, programInfo); + + // Tell WebGL which indices to use to index the vertices + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffers.indices); + + // Tell WebGL to use our program when drawing + gl.useProgram(programInfo.program); + + // Set the shader uniforms + gl.uniformMatrix4fv( + programInfo.uniformLocations.projectionMatrix, + false, + projectionMatrix, + ); + gl.uniformMatrix4fv( + programInfo.uniformLocations.modelViewMatrix, + false, + modelViewMatrix, + ); + + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, texture); + gl.uniform1i(programInfo.uniformLocations.uSampler, 0); + + { + const vertexCount = 36; + const type = gl.UNSIGNED_SHORT; + const offset = 0; + gl.drawElements(gl.TRIANGLES, vertexCount, type, offset); + } +} + +// Tell WebGL how to pull out the positions from the position +// buffer into the vertexPosition attribute. +function setPositionAttribute(gl, buffers, programInfo) { + const numComponents = 3; + const type = gl.FLOAT; // the data in the buffer is 32bit floats + const normalize = false; // don't normalize + const stride = 0; // how many bytes to get from one set of values to the next + // 0 = use type and numComponents above + const offset = 0; // how many bytes inside the buffer to start from + gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position); + gl.vertexAttribPointer( + programInfo.attribLocations.vertexPosition, + numComponents, + type, + normalize, + stride, + offset, + ); + gl.enableVertexAttribArray(programInfo.attribLocations.vertexPosition); +} + +// Tell WebGL how to pull out the texture +// into the vertex. +function setTextureAttribute(gl, buffers, programInfo) { + const num = 2; // every coordinate is 2 values (s, t) + const type = gl.FLOAT; + const normalize = false; + const stride = 0; + const offset = 0; + gl.bindBuffer(gl.ARRAY_BUFFER, buffers.textureCoord); + gl.vertexAttribPointer( + programInfo.attribLocations.textureCoord, + num, + type, + normalize, + stride, + offset, + ); + gl.enableVertexAttribArray(programInfo.attribLocations.textureCoord); +} + +export { drawScene }; diff --git a/html-in-canvas/webgl-example/index.html b/html-in-canvas/webgl-example/index.html new file mode 100644 index 00000000..772b0987 --- /dev/null +++ b/html-in-canvas/webgl-example/index.html @@ -0,0 +1,30 @@ + + + + + WebGL Demo + + + + + + + +
+
+ + +
+
+ + +
+ +
+
+ + diff --git a/html-in-canvas/webgl-example/init-buffers.js b/html-in-canvas/webgl-example/init-buffers.js new file mode 100644 index 00000000..a7cdeab6 --- /dev/null +++ b/html-in-canvas/webgl-example/init-buffers.js @@ -0,0 +1,139 @@ +function initBuffers(gl) { + const positionBuffer = initPositionBuffer(gl); + + const textureBuffer = initTextureBuffer(gl); + + const indexBuffer = initIndexBuffer(gl); + + return { + position: positionBuffer, + textureCoord: textureBuffer, + indices: indexBuffer, + }; +} + +function initPositionBuffer(gl) { + // Create a buffer for the square's positions. + const positionBuffer = gl.createBuffer(); + + // Select the positionBuffer as the one to apply buffer + // operations to from here out. + gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer); + + const positions = [ + // Front face + -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0, + + // Back face + -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0, -1.0, + + // Top face + -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0, + + // Bottom face + -1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, -1.0, 1.0, -1.0, -1.0, 1.0, + + // Right face + 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, + + // Left face + -1.0, -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0, + ]; + + // Now pass the list of positions into WebGL to build the + // shape. We do this by creating a Float32Array from the + // JavaScript array, then use it to fill the current buffer. + gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW); + + return positionBuffer; +} + +function initTextureBuffer(gl) { + const textureCoordBuffer = gl.createBuffer(); + gl.bindBuffer(gl.ARRAY_BUFFER, textureCoordBuffer); + + // Same 4 coords per face, in the same face order as the positions + // (front, back, top, bottom, right, left) + const textureCoordinates = [ + // Front + 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, + // Back + 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, + // Top + 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, + // Bottom + 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, + // Right + 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, + // Left + 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, + ]; + + gl.bufferData( + gl.ARRAY_BUFFER, + new Float32Array(textureCoordinates), + gl.STATIC_DRAW, + ); + + return textureCoordBuffer; +} + +function initIndexBuffer(gl) { + const indexBuffer = gl.createBuffer(); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer); + + // This array defines each face as two triangles, using the + // indices into the vertex array to specify each triangle's + // position. + + const indices = [ + 0, + 1, + 2, + 0, + 2, + 3, // front + 4, + 5, + 6, + 4, + 6, + 7, // back + 8, + 9, + 10, + 8, + 10, + 11, // top + 12, + 13, + 14, + 12, + 14, + 15, // bottom + 16, + 17, + 18, + 16, + 18, + 19, // right + 20, + 21, + 22, + 20, + 22, + 23, // left + ]; + + // Now send the element array to GL + + gl.bufferData( + gl.ELEMENT_ARRAY_BUFFER, + new Uint16Array(indices), + gl.STATIC_DRAW, + ); + + return indexBuffer; +} + +export { initBuffers }; diff --git a/html-in-canvas/webgl-example/style.css b/html-in-canvas/webgl-example/style.css new file mode 100644 index 00000000..a55b954d --- /dev/null +++ b/html-in-canvas/webgl-example/style.css @@ -0,0 +1,41 @@ +form { + width: 250px; + height: 150px; + padding: 10px; + background: white; +} + +form div { + display: flex; + align-items: center; + gap: 10px; + font-family: Arial, Helvetica, sans-serif; + padding: 5px; + border: 4px solid #576490; + background: #d1d2f9; + border-radius: 5px; + margin-bottom: 10px; +} + +form input { + padding: 3px; + border: 2px solid #576490; + border-radius: 3px; +} + +form button { + background: #576490; + border: 4px solid transparent; + color: white; + padding: 10px 10px; + border-radius: 5px; + transition: 0.6s all; + cursor: pointer; +} + +form button:hover, +form button:focus { + background: #d1d2f9; + color: black; + border: 4px solid #576490; +} diff --git a/html-in-canvas/webgl-example/webgl-demo.js b/html-in-canvas/webgl-example/webgl-demo.js new file mode 100644 index 00000000..ab9beef7 --- /dev/null +++ b/html-in-canvas/webgl-example/webgl-demo.js @@ -0,0 +1,223 @@ +import { initBuffers } from "./init-buffers.js"; +import { drawScene } from "./draw-scene.js"; + +let cubeRotation = 0.0; +let deltaTime = 0; +let raf; + +main(); + +// +// start here +// +function main() { + const canvas = document.querySelector("#glcanvas"); + const form = document.querySelector("canvas form"); + + // Initialize the GL context + const gl = canvas.getContext("webgl"); + + // 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; + } + + if (!gl.texElementSubImage2D) { + alert( + "WebGLRenderingContext.texElementSubImage2D() is not available. HTML-in-Canvas is not supported.", + ); + return; + } + + // Set clear color to black, fully opaque + gl.clearColor(1.0, 0.0, 0.0, 1.0); + // Clear the color buffer with specified clear color + gl.clear(gl.COLOR_BUFFER_BIT); + + // 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, vec2(1.0 - vTextureCoord.x, vTextureCoord.y)); + } + `; + + // Initialize a shader program; this is where all the lighting + // for the vertices and so forth is established. + const shaderProgram = initShaderProgram(gl, vsSource, fsSource); + + // Collect all the info needed to use the shader program. + // Look up which attributes our shader program is using + // for aVertexPosition, aVertexColor and also + // look up uniform locations. + 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"), + }, + }; + + // Here's where we call the routine that builds all the + // objects we'll be drawing. + const buffers = initBuffers(gl); + const texture = initTexture(gl); + let started = false; + + canvas.onpaint = () => { + const ok = updateTextureFromElement(gl, canvas, texture, form); + if (ok && !started) { + started = true; + requestAnimationFrame(render); + } + }; + canvas.requestPaint(); // make sure the first paint event fires + + let then = 0; + // Draw the scene repeatedly + function render(now) { + now *= 0.001; // convert to seconds + deltaTime = now - then; + then = now; + + drawScene(gl, programInfo, buffers, texture, cubeRotation); + cubeRotation += deltaTime; + + raf = requestAnimationFrame(render); + } + raf = requestAnimationFrame(render); +} + +// +// Initialize a shader program, so WebGL knows how to draw our data +// +function initShaderProgram(gl, vsSource, fsSource) { + const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource); + const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource); + + // Create the shader program + + const shaderProgram = gl.createProgram(); + gl.attachShader(shaderProgram, vertexShader); + gl.attachShader(shaderProgram, fragmentShader); + gl.linkProgram(shaderProgram); + + // If creating the shader program failed, alert + + if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) { + alert( + `Unable to initialize the shader program: ${gl.getProgramInfoLog( + shaderProgram, + )}`, + ); + return null; + } + + return shaderProgram; +} + +// +// creates a shader of the given type, uploads the source and +// compiles it. +// +function loadShader(gl, type, source) { + const shader = gl.createShader(type); + + // Send the source to the shader object + + gl.shaderSource(shader, source); + + // Compile the shader program + + gl.compileShader(shader); + + // See if it compiled successfully + + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { + alert( + `An error occurred compiling the shaders: ${gl.getShaderInfoLog(shader)}`, + ); + gl.deleteShader(shader); + return null; + } + + return shader; +} + +// Load texture + +function initTexture(gl) { + const texture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, texture); + // No mipmaps, so MIN_FILTER must not be a mipmap mode or the texture is incomplete. + 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); + return texture; +} + +let allocated = false; +let texWidth = 0; +let texHeight = 0; + +function updateTextureFromElement(gl, canvas, texture, element) { + // Ratio between the canvas's drawing buffer and its CSS size + const scale = canvas.width / canvas.clientWidth; + const w = Math.ceil(element.offsetWidth * scale); + const h = Math.ceil(element.offsetHeight * scale); + console.log("element size:", w, h); // temporary diagnostic + + if (!(w > 0 && h > 0)) return false; + + gl.bindTexture(gl.TEXTURE_2D, texture); + if (!allocated || w !== texWidth || h !== texHeight) { + gl.texImage2D( + gl.TEXTURE_2D, + 0, + gl.RGBA, + w, + h, + 0, + gl.RGBA, + gl.UNSIGNED_BYTE, + null, + ); + allocated = true; + texWidth = w; + texHeight = h; + } + gl.texElementSubImage2D(gl.TEXTURE_2D, 0, 0, 0, element); + return true; +} diff --git a/html-in-canvas/webgpu-demo/index.html b/html-in-canvas/webgpu-demo/index.html new file mode 100644 index 00000000..02d2e0c4 --- /dev/null +++ b/html-in-canvas/webgpu-demo/index.html @@ -0,0 +1,25 @@ + + + + + WebGPU HTML-in-Canvas demo + + + + + + +
+
+ + +
+
+ + +
+ +
+
+ + diff --git a/html-in-canvas/webgpu-demo/style.css b/html-in-canvas/webgpu-demo/style.css new file mode 100644 index 00000000..a55b954d --- /dev/null +++ b/html-in-canvas/webgpu-demo/style.css @@ -0,0 +1,41 @@ +form { + width: 250px; + height: 150px; + padding: 10px; + background: white; +} + +form div { + display: flex; + align-items: center; + gap: 10px; + font-family: Arial, Helvetica, sans-serif; + padding: 5px; + border: 4px solid #576490; + background: #d1d2f9; + border-radius: 5px; + margin-bottom: 10px; +} + +form input { + padding: 3px; + border: 2px solid #576490; + border-radius: 3px; +} + +form button { + background: #576490; + border: 4px solid transparent; + color: white; + padding: 10px 10px; + border-radius: 5px; + transition: 0.6s all; + cursor: pointer; +} + +form button:hover, +form button:focus { + background: #d1d2f9; + color: black; + border: 4px solid #576490; +} diff --git a/html-in-canvas/webgpu-demo/webgpu-demo.js b/html-in-canvas/webgpu-demo/webgpu-demo.js new file mode 100644 index 00000000..0aedee4e --- /dev/null +++ b/html-in-canvas/webgpu-demo/webgpu-demo.js @@ -0,0 +1,357 @@ +// A spinning cube with an HTML element as the texture on every face, +// using WebGPU and the HTML-in-Canvas proposal +// (https://github.com/WICG/html-in-canvas). +// +// Requires a Chromium build with HTML-in-Canvas enabled +// (chrome://flags/#canvas-draw-element, or the origin trial). + +main(); + +async function main() { + const canvas = document.querySelector("#gpu-canvas"); + const source = document.querySelector("form"); + + if (!navigator.gpu) { + alert("WebGPU is not supported by your browser."); + return; + } + if (!("drawElementImageToTexture" in GPUQueue.prototype)) { + alert( + "GPUQueue.drawElementImageToTexture() is not available. HTML-in-Canvas is not supported.", + ); + return; + } + + const adapter = await navigator.gpu.requestAdapter(); + if (!adapter) { + alert("Unable to get a WebGPU adapter."); + return; + } + const device = await adapter.requestDevice(); + + const context = canvas.getContext("webgpu"); + const canvasFormat = navigator.gpu.getPreferredCanvasFormat(); + context.configure({ device, format: canvasFormat, alphaMode: "opaque" }); + + // --------------------------------------------------------------------- + // Shaders (WGSL) + // --------------------------------------------------------------------- + const shaderModule = device.createShaderModule({ + code: ` + struct Uniforms { + mvp : mat4x4f, + }; + + @group(0) @binding(0) var uniforms : Uniforms; + @group(0) @binding(1) var texSampler : sampler; + @group(0) @binding(2) var faceTexture : texture_2d; + + struct VertexOutput { + @builtin(position) position : vec4f, + @location(0) uv : vec2f, + }; + + @vertex + fn vertexMain(@location(0) position : vec3f, + @location(1) uv : vec2f) -> VertexOutput { + var output : VertexOutput; + output.position = uniforms.mvp * vec4f(position, 1.0); + output.uv = uv; + return output; + } + + @fragment + fn fragmentMain(input : VertexOutput) -> @location(0) vec4f { + return textureSample(faceTexture, texSampler, input.uv); + } + `, + }); + + // --------------------------------------------------------------------- + // Geometry: interleaved position (vec3) + uv (vec2), plus an index buffer + // --------------------------------------------------------------------- + const { vertices, indices } = createCubeGeometry(); + + const vertexBuffer = device.createBuffer({ + size: vertices.byteLength, + usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST, + }); + device.queue.writeBuffer(vertexBuffer, 0, vertices); + + const indexBuffer = device.createBuffer({ + size: indices.byteLength, // 72 bytes: already a multiple of 4 + usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST, + }); + device.queue.writeBuffer(indexBuffer, 0, indices); + + const uniformBuffer = device.createBuffer({ + size: 64, // one mat4x4f + usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST, + }); + + // --------------------------------------------------------------------- + // Pipeline, sampler, depth buffer + // --------------------------------------------------------------------- + const pipeline = device.createRenderPipeline({ + layout: "auto", + vertex: { + module: shaderModule, + entryPoint: "vertexMain", + buffers: [ + { + arrayStride: 5 * 4, + attributes: [ + { shaderLocation: 0, offset: 0, format: "float32x3" }, + { shaderLocation: 1, offset: 3 * 4, format: "float32x2" }, + ], + }, + ], + }, + fragment: { + module: shaderModule, + entryPoint: "fragmentMain", + targets: [{ format: canvasFormat }], + }, + primitive: { topology: "triangle-list", cullMode: "back" }, + depthStencil: { + format: "depth24plus", + depthWriteEnabled: true, + depthCompare: "less", + }, + }); + + // No mipmaps: linear filtering with clamped edges. + const sampler = device.createSampler({ + magFilter: "linear", + minFilter: "linear", + addressModeU: "clamp-to-edge", + addressModeV: "clamp-to-edge", + }); + + const depthTexture = device.createTexture({ + size: [canvas.width, canvas.height], + format: "depth24plus", + usage: GPUTextureUsage.RENDER_ATTACHMENT, + }); + + // --------------------------------------------------------------------- + // The texture that receives the HTML element + // --------------------------------------------------------------------- + let elementTexture = null; + let bindGroup = null; + let texWidth = 0; + let texHeight = 0; + + // Copies the latest snapshot of the element into a GPU texture, + // (re)creating the texture if the element's size has changed. + // Returns false if the element has no usable size yet. + function updateElementTexture() { + // Size in canvas-grid pixels. + const scale = canvas.width / canvas.clientWidth; + const w = Math.ceil(source.offsetWidth * scale); + const h = Math.ceil(source.offsetHeight * scale); + if (!(w > 0 && h > 0)) return false; + + if (!elementTexture || w !== texWidth || h !== texHeight) { + elementTexture?.destroy(); + elementTexture = device.createTexture({ + size: [w, h], + format: "rgba8unorm", + usage: + GPUTextureUsage.TEXTURE_BINDING | + GPUTextureUsage.COPY_DST | + GPUTextureUsage.RENDER_ATTACHMENT, + }); + bindGroup = device.createBindGroup({ + layout: pipeline.getBindGroupLayout(0), + entries: [ + { binding: 0, resource: { buffer: uniformBuffer } }, + { binding: 1, resource: sampler }, + { binding: 2, resource: elementTexture.createView() }, + ], + }); + texWidth = w; + texHeight = h; + } + + device.queue.drawElementImageToTexture( + { source }, + { texture: elementTexture, size: { width: w, height: h } }, + ); + return true; + } + + // --------------------------------------------------------------------- + // Render loop + // --------------------------------------------------------------------- + const projection = perspective( + (45 * Math.PI) / 180, + canvas.width / canvas.height, + 0.1, + 100.0, + ); + const view = translation(0, 0, -6); + let rotation = 0; + let then = null; + + function render(nowMs) { + const now = nowMs * 0.001; + rotation += then === null ? 0 : now - then; + then = now; + + const model = multiply( + rotateZ(rotation), + multiply(rotateY(rotation * 0.7), rotateX(rotation * 0.3)), + ); + const mvp = multiply(projection, multiply(view, model)); + device.queue.writeBuffer(uniformBuffer, 0, mvp); + + const encoder = device.createCommandEncoder(); + const pass = encoder.beginRenderPass({ + colorAttachments: [ + { + view: context.getCurrentTexture().createView(), + clearValue: { r: 0, g: 0, b: 0, a: 1 }, + loadOp: "clear", + storeOp: "store", + }, + ], + depthStencilAttachment: { + view: depthTexture.createView(), + depthClearValue: 1.0, + depthLoadOp: "clear", + depthStoreOp: "store", + }, + }); + pass.setPipeline(pipeline); + pass.setBindGroup(0, bindGroup); + pass.setVertexBuffer(0, vertexBuffer); + pass.setIndexBuffer(indexBuffer, "uint16"); + pass.drawIndexed(indices.length); + pass.end(); + device.queue.submit([encoder.finish()]); + + requestAnimationFrame(render); + } + + // --------------------------------------------------------------------- + // HTML-in-Canvas wiring: upload in the `paint` event. No snapshot exists + // until the first paint, so only start rendering once an upload succeeds. + // --------------------------------------------------------------------- + let started = false; + canvas.onpaint = () => { + const ok = updateElementTexture(); + if (ok && !started) { + started = true; + requestAnimationFrame(render); + } + }; + canvas.requestPaint(); // make sure the first paint event fires +} + +// --- Cube geometry ------------------------------------------------------- +// Each face is described by its outward normal `n`, and the `r` (right) and +// `u` (up) directions as seen from outside the cube. Corners are generated +// as n + s*r + t*u, with uv (0,0) at the top-left of the face. WebGPU's +// texture origin is also top-left, so the element appears upright and +// un-mirrored on every face, with no flipping needed. +function createCubeGeometry() { + const faces = [ + { n: [0, 0, 1], r: [1, 0, 0], u: [0, 1, 0] }, // front + { n: [0, 0, -1], r: [-1, 0, 0], u: [0, 1, 0] }, // back + { n: [0, 1, 0], r: [1, 0, 0], u: [0, 0, -1] }, // top + { n: [0, -1, 0], r: [1, 0, 0], u: [0, 0, 1] }, // bottom + { n: [1, 0, 0], r: [0, 0, -1], u: [0, 1, 0] }, // right + { n: [-1, 0, 0], r: [0, 0, 1], u: [0, 1, 0] }, // left + ]; + // [s, t, u, v] for top-left, top-right, bottom-right, bottom-left + const corners = [ + [-1, 1, 0, 0], + [1, 1, 1, 0], + [1, -1, 1, 1], + [-1, -1, 0, 1], + ]; + + const vertices = []; + const indices = []; + faces.forEach(({ n, r, u }, f) => { + for (const [s, t, uu, vv] of corners) { + vertices.push( + n[0] + s * r[0] + t * u[0], + n[1] + s * r[1] + t * u[1], + n[2] + s * r[2] + t * u[2], + uu, + vv, + ); + } + const b = f * 4; + // Counter-clockwise as seen from outside: TL, BL, BR / TL, BR, TR + indices.push(b, b + 3, b + 2, b, b + 2, b + 1); + }); + + return { + vertices: new Float32Array(vertices), + indices: new Uint16Array(indices), + }; +} + +// --- Minimal column-major 4x4 matrix helpers ----------------------------- +// WebGPU clip space has z in [0, 1] (WebGL uses [-1, 1]), so the projection +// matrix differs from the one gl-matrix's perspective() produces. +function perspective(fovy, aspect, near, far) { + const f = 1 / Math.tan(fovy / 2); + const nf = 1 / (near - far); + return new Float32Array([ + f / aspect, + 0, + 0, + 0, + 0, + f, + 0, + 0, + 0, + 0, + far * nf, + -1, + 0, + 0, + far * near * nf, + 0, + ]); +} + +function translation(x, y, z) { + return new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1]); +} + +function rotateX(a) { + const c = Math.cos(a), + s = Math.sin(a); + return new Float32Array([1, 0, 0, 0, 0, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1]); +} + +function rotateY(a) { + const c = Math.cos(a), + s = Math.sin(a); + return new Float32Array([c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1]); +} + +function rotateZ(a) { + const c = Math.cos(a), + s = Math.sin(a); + return new Float32Array([c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); +} + +// Returns a * b (column-major). +function multiply(a, b) { + const out = new Float32Array(16); + for (let col = 0; col < 4; col++) { + for (let row = 0; row < 4; row++) { + let sum = 0; + for (let k = 0; k < 4; k++) sum += a[k * 4 + row] * b[col * 4 + k]; + out[col * 4 + row] = sum; + } + } + return out; +} From 7f39715774b07827fa03d19b95e2e26d77477ee7 Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Wed, 28 Oct 2026 20:30:33 +0000 Subject: [PATCH 02/12] Add nested canvases example --- .../2d-context-nested-canvases/index.html | 20 ++++++++++ .../2d-context-nested-canvases/index.js | 39 +++++++++++++++++++ .../2d-context-nested-canvases/style.css | 21 ++++++++++ html-in-canvas/README.md | 1 + 4 files changed, 81 insertions(+) create mode 100644 html-in-canvas/2d-context-nested-canvases/index.html create mode 100644 html-in-canvas/2d-context-nested-canvases/index.js create mode 100644 html-in-canvas/2d-context-nested-canvases/style.css diff --git a/html-in-canvas/2d-context-nested-canvases/index.html b/html-in-canvas/2d-context-nested-canvases/index.html new file mode 100644 index 00000000..5b002b13 --- /dev/null +++ b/html-in-canvas/2d-context-nested-canvases/index.html @@ -0,0 +1,20 @@ + + + + + HTML-in-Canvas basic test + + + + +

+ +
+ Parent element content + +
Child element content
+
+
+
+ + diff --git a/html-in-canvas/2d-context-nested-canvases/index.js b/html-in-canvas/2d-context-nested-canvases/index.js new file mode 100644 index 00000000..1aa142d1 --- /dev/null +++ b/html-in-canvas/2d-context-nested-canvases/index.js @@ -0,0 +1,39 @@ +function main() { + const parentCanvas = document.querySelector("#parent-canvas"); + const childCanvas = document.querySelector("#child-canvas"); + const parentElement = document.querySelector("#parent-element"); + const childElement = document.querySelector("#child-element"); + const btn = document.querySelector("button"); + + const pCtx = parentCanvas.getContext("2d"); + const cCtx = childCanvas.getContext("2d"); + + if (!pCtx.drawElementImage) { + alert( + "CanvasRenderingContext2D.drawElementImage() is not available. HTML-in-Canvas is not supported.", + ); + return; + } + + const colors = ["orange", "pink", "cyan"]; + let count = 0; + btn.addEventListener("click", () => { + const color = colors[count]; + childElement.style.backgroundColor = color; + count = (count + 1) % colors.length; + }); + + childCanvas.addEventListener("paint", () => { + cCtx.clearRect(0, 0, childCanvas.width, childCanvas.height); + cCtx.drawElementImage(childElement, 100, 100); + console.log("Child canvas paint fired"); + }); + + parentCanvas.addEventListener("paint", () => { + pCtx.clearRect(0, 0, parentCanvas.width, parentCanvas.height); + pCtx.drawElementImage(parentElement, 100, 100); + console.log("Parent canvas paint fired"); + }); +} + +main(); diff --git a/html-in-canvas/2d-context-nested-canvases/style.css b/html-in-canvas/2d-context-nested-canvases/style.css new file mode 100644 index 00000000..5274188c --- /dev/null +++ b/html-in-canvas/2d-context-nested-canvases/style.css @@ -0,0 +1,21 @@ +html { + font-family: sans-serif; +} + +canvas { + border: 3px dashed blue; +} + +#parent-element, +#child-element { + border: 3px solid black; + padding: 10px; +} + +#parent-element { + background-color: gray; +} + +#child-element { + background-color: cyan; +} diff --git a/html-in-canvas/README.md b/html-in-canvas/README.md index a122544d..a30358de 100644 --- a/html-in-canvas/README.md +++ b/html-in-canvas/README.md @@ -5,3 +5,4 @@ This set of examples demonstrates usage of the [HTML-in-canvas API](https://gith - [Canvas 2D context example](2d-context-example/): Demonstrates how an HTML form can be rendered on a 2D canvas, have a pixel distortion effect applied to it on mouseover, but still remain accessible, interactive, and submittable ([run example live](https://mdn.github.io/dom-examples/html-in-canvas/2d-context-example/)). - [WebGL example](webgl-example/): Adapted from our [WebGL 3D tutorial](https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Tutorial/Creating_3D_objects_using_WebGL), this example shows how to render an HTML form as a texture onto all six sides of a rotating 3D cube. Again, it still remains accessible, interactive, and submittable ([run example live](https://mdn.github.io/dom-examples/html-in-canvas/webgl-example/)). - [WebGPU example](webgpu-example/): This example is the same as the WebGL example, only converted to use WebGPU instead ([run example live](https://mdn.github.io/dom-examples/html-in-canvas/webgpu-example/)). +- [Canvas 2D context nested canvases example](2d-context-nested-canvases/): Demonstrates how the paint events fire in nested canvases ([run example live](https://mdn.github.io/dom-examples/html-in-canvas/2d-context-nested-canvases/)). From dc0bc3afab63581fbf59cdaddc0e4ab142a7e324 Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Tue, 3 Nov 2026 10:50:50 +0000 Subject: [PATCH 03/12] Replace rAF loops with paint/requestPaint --- html-in-canvas/2d-context-example/index.js | 9 +++--- html-in-canvas/webgl-example/webgl-demo.js | 32 ++++++++----------- .../index.html | 0 .../{webgpu-demo => webgpu-example}/style.css | 0 .../webgpu-demo.js | 31 +++++++----------- 5 files changed, 30 insertions(+), 42 deletions(-) rename html-in-canvas/{webgpu-demo => webgpu-example}/index.html (100%) rename html-in-canvas/{webgpu-demo => webgpu-example}/style.css (100%) rename html-in-canvas/{webgpu-demo => webgpu-example}/webgpu-demo.js (93%) diff --git a/html-in-canvas/2d-context-example/index.js b/html-in-canvas/2d-context-example/index.js index 242bf9b1..aea2faad 100644 --- a/html-in-canvas/2d-context-example/index.js +++ b/html-in-canvas/2d-context-example/index.js @@ -14,14 +14,13 @@ function main() { const fx = createPointerDistort(canvas, { radius: 120 }); - function loop(t) { + canvas.addEventListener("paint", () => { ctx.fillStyle = "#7D82B8"; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.drawElementImage(form, 100, 100); - fx.apply(t); - requestAnimationFrame(loop); - } - requestAnimationFrame(loop); + fx.apply(performance.now()); + canvas.requestPaint(); + }); } main(); diff --git a/html-in-canvas/webgl-example/webgl-demo.js b/html-in-canvas/webgl-example/webgl-demo.js index ab9beef7..c30ee037 100644 --- a/html-in-canvas/webgl-example/webgl-demo.js +++ b/html-in-canvas/webgl-example/webgl-demo.js @@ -33,7 +33,7 @@ function main() { } // Set clear color to black, fully opaque - gl.clearColor(1.0, 0.0, 0.0, 1.0); + gl.clearColor(0.0, 0.0, 0.0, 1.0); // Clear the color buffer with specified clear color gl.clear(gl.COLOR_BUFFER_BIT); @@ -94,30 +94,27 @@ function main() { // objects we'll be drawing. const buffers = initBuffers(gl); const texture = initTexture(gl); - let started = false; - canvas.onpaint = () => { + let then = performance.now() * 0.001; // seconds + let cubeRotation = 0; + + canvas.addEventListener("paint", () => { + // 1. Re-upload the form's current rendering into the texture const ok = updateTextureFromElement(gl, canvas, texture, form); - if (ok && !started) { - started = true; - requestAnimationFrame(render); - } - }; - canvas.requestPaint(); // make sure the first paint event fires + if (!ok) return; // same behaviour as before: stop if the update failed - let then = 0; - // Draw the scene repeatedly - function render(now) { - now *= 0.001; // convert to seconds - deltaTime = now - then; + // 2. Work out the time step + const now = performance.now() * 0.001; // convert to seconds + const deltaTime = now - then; then = now; + // 3. Draw the scene and advance the animation drawScene(gl, programInfo, buffers, texture, cubeRotation); cubeRotation += deltaTime; - raf = requestAnimationFrame(render); - } - raf = requestAnimationFrame(render); + // 4. Ask for the next paint event + canvas.requestPaint(); + }); } // @@ -197,7 +194,6 @@ function updateTextureFromElement(gl, canvas, texture, element) { const scale = canvas.width / canvas.clientWidth; const w = Math.ceil(element.offsetWidth * scale); const h = Math.ceil(element.offsetHeight * scale); - console.log("element size:", w, h); // temporary diagnostic if (!(w > 0 && h > 0)) return false; diff --git a/html-in-canvas/webgpu-demo/index.html b/html-in-canvas/webgpu-example/index.html similarity index 100% rename from html-in-canvas/webgpu-demo/index.html rename to html-in-canvas/webgpu-example/index.html diff --git a/html-in-canvas/webgpu-demo/style.css b/html-in-canvas/webgpu-example/style.css similarity index 100% rename from html-in-canvas/webgpu-demo/style.css rename to html-in-canvas/webgpu-example/style.css diff --git a/html-in-canvas/webgpu-demo/webgpu-demo.js b/html-in-canvas/webgpu-example/webgpu-demo.js similarity index 93% rename from html-in-canvas/webgpu-demo/webgpu-demo.js rename to html-in-canvas/webgpu-example/webgpu-demo.js index 0aedee4e..f481110c 100644 --- a/html-in-canvas/webgpu-demo/webgpu-demo.js +++ b/html-in-canvas/webgpu-example/webgpu-demo.js @@ -182,7 +182,7 @@ async function main() { } // --------------------------------------------------------------------- - // Render loop + // Render loop, driven by the `paint` event // --------------------------------------------------------------------- const projection = perspective( (45 * Math.PI) / 180, @@ -194,8 +194,15 @@ async function main() { let rotation = 0; let then = null; - function render(nowMs) { - const now = nowMs * 0.001; + canvas.addEventListener("paint", () => { + // No snapshot exists until the first paint, and the element may not have + // a usable size yet, so skip drawing but keep the loop alive. + if (!updateElementTexture()) { + canvas.requestPaint(); + return; + } + + const now = performance.now() * 0.001; // convert to seconds rotation += then === null ? 0 : now - then; then = now; @@ -231,22 +238,8 @@ async function main() { pass.end(); device.queue.submit([encoder.finish()]); - requestAnimationFrame(render); - } - - // --------------------------------------------------------------------- - // HTML-in-Canvas wiring: upload in the `paint` event. No snapshot exists - // until the first paint, so only start rendering once an upload succeeds. - // --------------------------------------------------------------------- - let started = false; - canvas.onpaint = () => { - const ok = updateElementTexture(); - if (ok && !started) { - started = true; - requestAnimationFrame(render); - } - }; - canvas.requestPaint(); // make sure the first paint event fires + canvas.requestPaint(); // request the next paint + }); } // --- Cube geometry ------------------------------------------------------- From d000c7dea1a11235c097592caa0830b44e2f971e Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Tue, 3 Nov 2026 11:44:41 +0000 Subject: [PATCH 04/12] remove willReadFrequently --- html-in-canvas/2d-context-example/index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/html-in-canvas/2d-context-example/index.js b/html-in-canvas/2d-context-example/index.js index aea2faad..214ee4c5 100644 --- a/html-in-canvas/2d-context-example/index.js +++ b/html-in-canvas/2d-context-example/index.js @@ -3,7 +3,7 @@ import { createPointerDistort } from "./pointer-distort.js"; function main() { const canvas = document.querySelector("canvas"); const form = document.querySelector("canvas form"); - const ctx = canvas.getContext("2d", { willReadFrequently: true }); + const ctx = canvas.getContext("2d"); if (!ctx.drawElementImage) { alert( From 3996f7a83d0f37c9c25b6377ea36eb1905c919ef Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Thu, 12 Nov 2026 11:55:37 +0000 Subject: [PATCH 05/12] update 3D demos to include rotation pausing and hit area setting --- html-in-canvas/README.md | 2 +- html-in-canvas/webgl-example/draw-scene.js | 136 ----- html-in-canvas/webgl-example/index.html | 9 +- html-in-canvas/webgl-example/init-buffers.js | 139 ----- html-in-canvas/webgl-example/webgl-demo.js | 558 +++++++++++++------ html-in-canvas/webgpu-example/webgpu-demo.js | 134 ++++- 6 files changed, 522 insertions(+), 456 deletions(-) delete mode 100644 html-in-canvas/webgl-example/draw-scene.js delete mode 100644 html-in-canvas/webgl-example/init-buffers.js diff --git a/html-in-canvas/README.md b/html-in-canvas/README.md index a30358de..76ea1a69 100644 --- a/html-in-canvas/README.md +++ b/html-in-canvas/README.md @@ -3,6 +3,6 @@ This set of examples demonstrates usage of the [HTML-in-canvas API](https://github.com/WICG/html-in-canvas): - [Canvas 2D context example](2d-context-example/): Demonstrates how an HTML form can be rendered on a 2D canvas, have a pixel distortion effect applied to it on mouseover, but still remain accessible, interactive, and submittable ([run example live](https://mdn.github.io/dom-examples/html-in-canvas/2d-context-example/)). -- [WebGL example](webgl-example/): Adapted from our [WebGL 3D tutorial](https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Tutorial/Creating_3D_objects_using_WebGL), this example shows how to render an HTML form as a texture onto all six sides of a rotating 3D cube. Again, it still remains accessible, interactive, and submittable ([run example live](https://mdn.github.io/dom-examples/html-in-canvas/webgl-example/)). +- [WebGL example](webgl-example/): This example shows how to render an HTML form as a texture onto all six sides of a rotating 3D cube. When the form is hovered or focused, the rotation pauses and you can interact with form on the front-most cube face as expected (clicking into it, etc.). Again, it still remains accessible, interactive, and submittable ([run example live](https://mdn.github.io/dom-examples/html-in-canvas/webgl-example/)). - [WebGPU example](webgpu-example/): This example is the same as the WebGL example, only converted to use WebGPU instead ([run example live](https://mdn.github.io/dom-examples/html-in-canvas/webgpu-example/)). - [Canvas 2D context nested canvases example](2d-context-nested-canvases/): Demonstrates how the paint events fire in nested canvases ([run example live](https://mdn.github.io/dom-examples/html-in-canvas/2d-context-nested-canvases/)). diff --git a/html-in-canvas/webgl-example/draw-scene.js b/html-in-canvas/webgl-example/draw-scene.js deleted file mode 100644 index db7c2fa5..00000000 --- a/html-in-canvas/webgl-example/draw-scene.js +++ /dev/null @@ -1,136 +0,0 @@ -function drawScene(gl, programInfo, buffers, texture, cubeRotation) { - gl.clearColor(0.0, 0.0, 0.0, 1.0); // Clear to black, fully opaque - gl.clearDepth(1.0); // Clear everything - gl.enable(gl.DEPTH_TEST); // Enable depth testing - gl.depthFunc(gl.LEQUAL); // Near things obscure far things - - // Clear the canvas before we start drawing on it. - - gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); - - // Create a perspective matrix, a special matrix that is - // used to simulate the distortion of perspective in a camera. - // Our field of view is 45 degrees, with a width/height - // ratio that matches the display size of the canvas - // and we only want to see objects between 0.1 units - // and 100 units away from the camera. - - const fieldOfView = (45 * Math.PI) / 180; // in radians - const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight; - const zNear = 0.1; - const zFar = 100.0; - const projectionMatrix = mat4.create(); - - // note: glmatrix.js always has the first argument - // as the destination to receive the result. - mat4.perspective(projectionMatrix, fieldOfView, aspect, zNear, zFar); - - // Set the drawing position to the "identity" point, which is - // the center of the scene. - const modelViewMatrix = mat4.create(); - - // Now move the drawing position a bit to where we want to - // start drawing the square. - mat4.translate( - modelViewMatrix, // destination matrix - modelViewMatrix, // matrix to translate - [-0.0, 0.0, -6.0], - ); // amount to translate - - mat4.rotate( - modelViewMatrix, // destination matrix - modelViewMatrix, // matrix to rotate - cubeRotation, // amount to rotate in radians - [0, 0, 1], - ); // axis to rotate around (Z) - mat4.rotate( - modelViewMatrix, // destination matrix - modelViewMatrix, // matrix to rotate - cubeRotation * 0.7, // amount to rotate in radians - [0, 1, 0], - ); // axis to rotate around (Y) - mat4.rotate( - modelViewMatrix, // destination matrix - modelViewMatrix, // matrix to rotate - cubeRotation * 0.3, // amount to rotate in radians - [1, 0, 0], - ); // axis to rotate around (X) - - // Tell WebGL how to pull out the positions from the position - // buffer into the vertexPosition attribute. - setPositionAttribute(gl, buffers, programInfo); - - setTextureAttribute(gl, buffers, programInfo); - - // Tell WebGL which indices to use to index the vertices - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffers.indices); - - // Tell WebGL to use our program when drawing - gl.useProgram(programInfo.program); - - // Set the shader uniforms - gl.uniformMatrix4fv( - programInfo.uniformLocations.projectionMatrix, - false, - projectionMatrix, - ); - gl.uniformMatrix4fv( - programInfo.uniformLocations.modelViewMatrix, - false, - modelViewMatrix, - ); - - gl.activeTexture(gl.TEXTURE0); - gl.bindTexture(gl.TEXTURE_2D, texture); - gl.uniform1i(programInfo.uniformLocations.uSampler, 0); - - { - const vertexCount = 36; - const type = gl.UNSIGNED_SHORT; - const offset = 0; - gl.drawElements(gl.TRIANGLES, vertexCount, type, offset); - } -} - -// Tell WebGL how to pull out the positions from the position -// buffer into the vertexPosition attribute. -function setPositionAttribute(gl, buffers, programInfo) { - const numComponents = 3; - const type = gl.FLOAT; // the data in the buffer is 32bit floats - const normalize = false; // don't normalize - const stride = 0; // how many bytes to get from one set of values to the next - // 0 = use type and numComponents above - const offset = 0; // how many bytes inside the buffer to start from - gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position); - gl.vertexAttribPointer( - programInfo.attribLocations.vertexPosition, - numComponents, - type, - normalize, - stride, - offset, - ); - gl.enableVertexAttribArray(programInfo.attribLocations.vertexPosition); -} - -// Tell WebGL how to pull out the texture -// into the vertex. -function setTextureAttribute(gl, buffers, programInfo) { - const num = 2; // every coordinate is 2 values (s, t) - const type = gl.FLOAT; - const normalize = false; - const stride = 0; - const offset = 0; - gl.bindBuffer(gl.ARRAY_BUFFER, buffers.textureCoord); - gl.vertexAttribPointer( - programInfo.attribLocations.textureCoord, - num, - type, - normalize, - stride, - offset, - ); - gl.enableVertexAttribArray(programInfo.attribLocations.textureCoord); -} - -export { drawScene }; diff --git a/html-in-canvas/webgl-example/index.html b/html-in-canvas/webgl-example/index.html index 772b0987..57ab8a43 100644 --- a/html-in-canvas/webgl-example/index.html +++ b/html-in-canvas/webgl-example/index.html @@ -2,18 +2,13 @@ - WebGL Demo + WebGL HTML-in-Canvas demo - - +
diff --git a/html-in-canvas/webgl-example/init-buffers.js b/html-in-canvas/webgl-example/init-buffers.js deleted file mode 100644 index a7cdeab6..00000000 --- a/html-in-canvas/webgl-example/init-buffers.js +++ /dev/null @@ -1,139 +0,0 @@ -function initBuffers(gl) { - const positionBuffer = initPositionBuffer(gl); - - const textureBuffer = initTextureBuffer(gl); - - const indexBuffer = initIndexBuffer(gl); - - return { - position: positionBuffer, - textureCoord: textureBuffer, - indices: indexBuffer, - }; -} - -function initPositionBuffer(gl) { - // Create a buffer for the square's positions. - const positionBuffer = gl.createBuffer(); - - // Select the positionBuffer as the one to apply buffer - // operations to from here out. - gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer); - - const positions = [ - // Front face - -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0, - - // Back face - -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0, -1.0, - - // Top face - -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0, - - // Bottom face - -1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, -1.0, 1.0, -1.0, -1.0, 1.0, - - // Right face - 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, - - // Left face - -1.0, -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0, - ]; - - // Now pass the list of positions into WebGL to build the - // shape. We do this by creating a Float32Array from the - // JavaScript array, then use it to fill the current buffer. - gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW); - - return positionBuffer; -} - -function initTextureBuffer(gl) { - const textureCoordBuffer = gl.createBuffer(); - gl.bindBuffer(gl.ARRAY_BUFFER, textureCoordBuffer); - - // Same 4 coords per face, in the same face order as the positions - // (front, back, top, bottom, right, left) - const textureCoordinates = [ - // Front - 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, - // Back - 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, - // Top - 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, - // Bottom - 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, - // Right - 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, - // Left - 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, - ]; - - gl.bufferData( - gl.ARRAY_BUFFER, - new Float32Array(textureCoordinates), - gl.STATIC_DRAW, - ); - - return textureCoordBuffer; -} - -function initIndexBuffer(gl) { - const indexBuffer = gl.createBuffer(); - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer); - - // This array defines each face as two triangles, using the - // indices into the vertex array to specify each triangle's - // position. - - const indices = [ - 0, - 1, - 2, - 0, - 2, - 3, // front - 4, - 5, - 6, - 4, - 6, - 7, // back - 8, - 9, - 10, - 8, - 10, - 11, // top - 12, - 13, - 14, - 12, - 14, - 15, // bottom - 16, - 17, - 18, - 16, - 18, - 19, // right - 20, - 21, - 22, - 20, - 22, - 23, // left - ]; - - // Now send the element array to GL - - gl.bufferData( - gl.ELEMENT_ARRAY_BUFFER, - new Uint16Array(indices), - gl.STATIC_DRAW, - ); - - return indexBuffer; -} - -export { initBuffers }; diff --git a/html-in-canvas/webgl-example/webgl-demo.js b/html-in-canvas/webgl-example/webgl-demo.js index c30ee037..1e50bcf2 100644 --- a/html-in-canvas/webgl-example/webgl-demo.js +++ b/html-in-canvas/webgl-example/webgl-demo.js @@ -1,219 +1,435 @@ -import { initBuffers } from "./init-buffers.js"; -import { drawScene } from "./draw-scene.js"; - -let cubeRotation = 0.0; -let deltaTime = 0; -let raf; +// A spinning cube with an HTML element as the texture on every face, +// using WebGL 2 and the HTML-in-Canvas proposal +// (https://github.com/WICG/html-in-canvas). +// +// Requires a Chromium build with HTML-in-Canvas enabled +// (chrome://flags/#canvas-draw-element, or the origin trial). main(); -// -// start here -// function main() { - const canvas = document.querySelector("#glcanvas"); - const form = document.querySelector("canvas form"); - - // Initialize the GL context - const gl = canvas.getContext("webgl"); + const canvas = document.querySelector("#gl-canvas"); + const source = document.querySelector("form"); - // Only continue if WebGL is available and working - if (gl === null) { - alert( - "Unable to initialize WebGL. Your browser or machine may not support it.", - ); + const gl = canvas.getContext("webgl2", { alpha: false }); + if (!gl) { + alert("WebGL 2 is not supported by your browser."); return; } - - if (!gl.texElementSubImage2D) { + if (typeof gl.texElementSubImage2D !== "function") { alert( - "WebGLRenderingContext.texElementSubImage2D() is not available. HTML-in-Canvas is not supported.", + "texElementSubImage2D() is not available. HTML-in-Canvas is not supported.", ); return; } - // Set clear color to black, fully opaque - gl.clearColor(0.0, 0.0, 0.0, 1.0); - // Clear the color buffer with specified clear color - gl.clear(gl.COLOR_BUFFER_BIT); - - // 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; + // --------------------------------------------------------------------- + // Shaders (GLSL ES 3.00) + // --------------------------------------------------------------------- + const vertexShaderSource = `#version 300 es + in vec3 aPosition; + in vec2 aUV; + uniform mat4 uMVP; + out vec2 vUV; + + void main() { + vUV = aUV; + gl_Position = uMVP * vec4(aPosition, 1.0); } `; - // Fragment shader program - - const fsSource = ` - varying highp vec2 vTextureCoord; - - uniform sampler2D uSampler; + const fragmentShaderSource = `#version 300 es + precision mediump float; + in vec2 vUV; + uniform sampler2D uTexture; + out vec4 outColor; - void main(void) { - gl_FragColor = texture2D(uSampler, vec2(1.0 - vTextureCoord.x, vTextureCoord.y)); + void main() { + outColor = texture(uTexture, vUV); } `; - // Initialize a shader program; this is where all the lighting - // for the vertices and so forth is established. - const shaderProgram = initShaderProgram(gl, vsSource, fsSource); - - // Collect all the info needed to use the shader program. - // Look up which attributes our shader program is using - // for aVertexPosition, aVertexColor and also - // look up uniform locations. - 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 program = createProgram(gl, vertexShaderSource, fragmentShaderSource); + const aPosition = gl.getAttribLocation(program, "aPosition"); + const aUV = gl.getAttribLocation(program, "aUV"); + const uMVP = gl.getUniformLocation(program, "uMVP"); + const uTexture = gl.getUniformLocation(program, "uTexture"); + + // --------------------------------------------------------------------- + // Geometry: interleaved position (vec3) + uv (vec2), plus an index buffer, + // captured in a vertex array object + // --------------------------------------------------------------------- + const { vertices, indices, faces } = createCubeGeometry(); + + const vao = gl.createVertexArray(); + gl.bindVertexArray(vao); + + const vertexBuffer = gl.createBuffer(); + gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW); + gl.enableVertexAttribArray(aPosition); + gl.vertexAttribPointer(aPosition, 3, gl.FLOAT, false, 5 * 4, 0); + gl.enableVertexAttribArray(aUV); + gl.vertexAttribPointer(aUV, 2, gl.FLOAT, false, 5 * 4, 3 * 4); + + const indexBuffer = gl.createBuffer(); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW); + + gl.bindVertexArray(null); + + // --------------------------------------------------------------------- + // Render state + // --------------------------------------------------------------------- + gl.enable(gl.DEPTH_TEST); + gl.depthFunc(gl.LESS); + gl.enable(gl.CULL_FACE); + gl.cullFace(gl.BACK); + gl.clearColor(0, 0, 0, 1); + + // --------------------------------------------------------------------- + // The texture that receives the HTML element + // --------------------------------------------------------------------- + const elementTexture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, elementTexture); + // No mipmaps: linear filtering with clamped edges (also required for + // non-power-of-two textures in WebGL 1). + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_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); - // Here's where we call the routine that builds all the - // objects we'll be drawing. - const buffers = initBuffers(gl); - const texture = initTexture(gl); + let texWidth = 0; + let texHeight = 0; + + // Copies the latest snapshot of the element into the texture, + // (re)allocating the texture storage if the element's size has changed. + // Returns false if the element has no usable size yet. + function updateElementTexture() { + // Size in canvas-grid pixels. + const scale = canvas.width / canvas.clientWidth; + const w = Math.ceil(source.offsetWidth * scale); + const h = Math.ceil(source.offsetHeight * scale); + if (!(w > 0 && h > 0)) return false; + + gl.bindTexture(gl.TEXTURE_2D, elementTexture); + + // texElementSubImage2D() doesn't allocate storage, so pre-allocate it + // (only when the size changes). + if (w !== texWidth || h !== texHeight) { + gl.texImage2D( + gl.TEXTURE_2D, + 0, + gl.RGBA8, + w, + h, + 0, + gl.RGBA, + gl.UNSIGNED_BYTE, + null, + ); + texWidth = w; + texHeight = h; + } + + gl.texElementSubImage2D(gl.TEXTURE_2D, 0, 0, 0, source); + return true; + } - let then = performance.now() * 0.001; // seconds - let cubeRotation = 0; + // --------------------------------------------------------------------- + // Pause the spin while the pointer is over the canvas or the form has focus + // --------------------------------------------------------------------- + let pointerOver = false; + canvas.addEventListener("pointerenter", () => { + pointerOver = true; + }); + canvas.addEventListener("pointerleave", () => { + pointerOver = false; + }); + const isPaused = () => pointerOver || source.matches(":focus-within"); + + // --------------------------------------------------------------------- + // Render loop, driven by the `paint` event + // --------------------------------------------------------------------- + const projection = perspective( + (45 * Math.PI) / 180, + canvas.width / canvas.height, + 0.1, + 100.0, + ); + const view = translation(0, 0, -6); + let rotation = 0; + let then = null; + let geometrySet = false; canvas.addEventListener("paint", () => { - // 1. Re-upload the form's current rendering into the texture - const ok = updateTextureFromElement(gl, canvas, texture, form); - if (!ok) return; // same behaviour as before: stop if the update failed + // No snapshot exists until the first paint, and the element may not have + // a usable size yet, so skip drawing but keep the loop alive. + if (!updateElementTexture()) { + canvas.requestPaint(); + return; + } + + const paused = isPaused(); - // 2. Work out the time step + // `then` is updated every frame, even while paused, so the cube + // resumes smoothly instead of jumping ahead. const now = performance.now() * 0.001; // convert to seconds - const deltaTime = now - then; + if (then !== null && !paused) { + rotation += now - then; + } then = now; - // 3. Draw the scene and advance the animation - drawScene(gl, programInfo, buffers, texture, cubeRotation); - cubeRotation += deltaTime; - - // 4. Ask for the next paint event - canvas.requestPaint(); - }); -} + const model = multiply( + rotateZ(rotation), + multiply(rotateY(rotation * 0.7), rotateX(rotation * 0.3)), + ); + const mvp = multiply(projection, multiply(view, model)); + + // While paused, tell the browser where the form appears on the cube so + // that hit testing matches what is rendered. Release it when spinning + // resumes. + if (paused) { + canvas.updateElementGeometry(source, { + canvasTransform: elementToCanvasTransform( + mvp, + model, + view, + faces, + source.offsetWidth, + source.offsetHeight, + canvas.clientWidth, + canvas.clientHeight, + ), + }); + geometrySet = true; + } else if (geometrySet) { + canvas.clearElementGeometry(source); + geometrySet = false; + } -// -// Initialize a shader program, so WebGL knows how to draw our data -// -function initShaderProgram(gl, vsSource, fsSource) { - const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource); - const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource); + // Draw + gl.viewport(0, 0, canvas.width, canvas.height); + gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); - // Create the shader program + gl.useProgram(program); + gl.bindVertexArray(vao); + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, elementTexture); + gl.uniform1i(uTexture, 0); + gl.uniformMatrix4fv(uMVP, false, mvp); + gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT, 0); - const shaderProgram = gl.createProgram(); - gl.attachShader(shaderProgram, vertexShader); - gl.attachShader(shaderProgram, fragmentShader); - gl.linkProgram(shaderProgram); + canvas.requestPaint(); // request the next paint + }); +} - // If creating the shader program failed, alert +// --- Shader helpers ------------------------------------------------------ +function compileShader(gl, type, sourceText) { + const shader = gl.createShader(type); + gl.shaderSource(shader, sourceText); + gl.compileShader(shader); + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { + const log = gl.getShaderInfoLog(shader); + gl.deleteShader(shader); + throw new Error(`Shader compile error: ${log}`); + } + return shader; +} - if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) { - alert( - `Unable to initialize the shader program: ${gl.getProgramInfoLog( - shaderProgram, - )}`, - ); - return null; +function createProgram(gl, vertexSource, fragmentSource) { + const program = gl.createProgram(); + gl.attachShader(program, compileShader(gl, gl.VERTEX_SHADER, vertexSource)); + gl.attachShader( + program, + compileShader(gl, gl.FRAGMENT_SHADER, fragmentSource), + ); + gl.linkProgram(program); + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + throw new Error(`Program link error: ${gl.getProgramInfoLog(program)}`); } + return program; +} - return shaderProgram; +// --- Cube geometry ------------------------------------------------------- +// Each face is described by its outward normal `n`, and the `r` (right) and +// `u` (up) directions as seen from outside the cube. Corners are generated +// as n + s*r + t*u, with uv (0,0) at the top-left of the face, so that the +// top row of the element's texture lands at the top of every face. +function createCubeGeometry() { + const faces = [ + { n: [0, 0, 1], r: [1, 0, 0], u: [0, 1, 0] }, // front + { n: [0, 0, -1], r: [-1, 0, 0], u: [0, 1, 0] }, // back + { n: [0, 1, 0], r: [1, 0, 0], u: [0, 0, -1] }, // top + { n: [0, -1, 0], r: [1, 0, 0], u: [0, 0, 1] }, // bottom + { n: [1, 0, 0], r: [0, 0, -1], u: [0, 1, 0] }, // right + { n: [-1, 0, 0], r: [0, 0, 1], u: [0, 1, 0] }, // left + ]; + // [s, t, u, v] for top-left, top-right, bottom-right, bottom-left + const corners = [ + [-1, 1, 0, 0], + [1, 1, 1, 0], + [1, -1, 1, 1], + [-1, -1, 0, 1], + ]; + + const vertices = []; + const indices = []; + faces.forEach(({ n, r, u }, f) => { + for (const [s, t, uu, vv] of corners) { + vertices.push( + n[0] + s * r[0] + t * u[0], + n[1] + s * r[1] + t * u[1], + n[2] + s * r[2] + t * u[2], + uu, + vv, + ); + } + const b = f * 4; + // Counter-clockwise as seen from outside: TL, BL, BR / TL, BR, TR + indices.push(b, b + 3, b + 2, b, b + 2, b + 1); + }); + + return { + vertices: new Float32Array(vertices), + indices: new Uint16Array(indices), + faces, + }; } +// --- Hit-test geometry --------------------------------------------------- +// Builds the DOMMatrix that maps the element's CSS-pixel box onto the +// on-screen quad of the cube face that is most squarely facing the camera, +// for use with canvas.updateElementGeometry(). // -// creates a shader of the given type, uploads the source and -// compiles it. +// result = viewport * mvp * elementToFace // -function loadShader(gl, type, source) { - const shader = gl.createShader(type); - - // Send the source to the shader object - - gl.shaderSource(shader, source); - - // Compile the shader program - - gl.compileShader(shader); +// The viewport step sits before the perspective divide, so the browser +// performs the divide when it applies the matrix. +function elementToCanvasTransform( + mvp, + model, + view, + faces, + elW, + elH, + canvasW, + canvasH, +) { + // Pick the face whose normal points most directly at the camera + let best = faces[0]; + let bestScore = -Infinity; + for (const face of faces) { + const [nx, ny, nz] = face.n; + // Rotated normal (model is rotation-only, so this is also the face centre) + const cx = model[0] * nx + model[4] * ny + model[8] * nz; + const cy = model[1] * nx + model[5] * ny + model[9] * nz; + const cz = model[2] * nx + model[6] * ny + model[10] * nz; + // Face centre in view space (camera at origin) + const vx = cx + view[12]; + const vy = cy + view[13]; + const vz = cz + view[14]; + const score = -(cx * vx + cy * vy + cz * vz) / Math.hypot(vx, vy, vz); + if (score > bestScore) { + bestScore = score; + best = face; + } + } + const { n, r, u } = best; + + // Element pixels -> model space. (0,0) is the face's top-left corner, + // (elW,elH) the bottom-right; element z maps along the face normal so the + // matrix stays invertible. + const toFace = new Float32Array([ + (2 * r[0]) / elW, + (2 * r[1]) / elW, + (2 * r[2]) / elW, + 0, + (-2 * u[0]) / elH, + (-2 * u[1]) / elH, + (-2 * u[2]) / elH, + 0, + n[0], + n[1], + n[2], + 0, + n[0] - r[0] + u[0], + n[1] - r[1] + u[1], + n[2] - r[2] + u[2], + 1, + ]); + + // Clip space -> canvas CSS pixels (y flipped), applied before the w divide + const hw = canvasW / 2; + const hh = canvasH / 2; + const viewport = new Float32Array([ + hw, 0, 0, 0, + 0, -hh, 0, 0, + 0, 0, 1, 0, + hw, hh, 0, 1, + ]); + + const m = multiply(viewport, multiply(mvp, toFace)); + return new DOMMatrix(Array.from(m)); // 16 values, column-major +} - // See if it compiled successfully +// --- Minimal column-major 4x4 matrix helpers ----------------------------- +// WebGL clip space has z in [-1, 1] (WebGPU uses [0, 1]), so this is the +// standard OpenGL-style perspective matrix. +function perspective(fovy, aspect, near, far) { + const f = 1 / Math.tan(fovy / 2); + const nf = 1 / (near - far); + return new Float32Array([ + f / aspect, + 0, + 0, + 0, + 0, + f, + 0, + 0, + 0, + 0, + (far + near) * nf, + -1, + 0, + 0, + 2 * far * near * nf, + 0, + ]); +} - if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - alert( - `An error occurred compiling the shaders: ${gl.getShaderInfoLog(shader)}`, - ); - gl.deleteShader(shader); - return null; - } +function translation(x, y, z) { + return new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1]); +} - return shader; +function rotateX(a) { + const c = Math.cos(a), + s = Math.sin(a); + return new Float32Array([1, 0, 0, 0, 0, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1]); } -// Load texture +function rotateY(a) { + const c = Math.cos(a), + s = Math.sin(a); + return new Float32Array([c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1]); +} -function initTexture(gl) { - const texture = gl.createTexture(); - gl.bindTexture(gl.TEXTURE_2D, texture); - // No mipmaps, so MIN_FILTER must not be a mipmap mode or the texture is incomplete. - 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); - return texture; +function rotateZ(a) { + const c = Math.cos(a), + s = Math.sin(a); + return new Float32Array([c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); } -let allocated = false; -let texWidth = 0; -let texHeight = 0; - -function updateTextureFromElement(gl, canvas, texture, element) { - // Ratio between the canvas's drawing buffer and its CSS size - const scale = canvas.width / canvas.clientWidth; - const w = Math.ceil(element.offsetWidth * scale); - const h = Math.ceil(element.offsetHeight * scale); - - if (!(w > 0 && h > 0)) return false; - - gl.bindTexture(gl.TEXTURE_2D, texture); - if (!allocated || w !== texWidth || h !== texHeight) { - gl.texImage2D( - gl.TEXTURE_2D, - 0, - gl.RGBA, - w, - h, - 0, - gl.RGBA, - gl.UNSIGNED_BYTE, - null, - ); - allocated = true; - texWidth = w; - texHeight = h; +// Returns a * b (column-major). +function multiply(a, b) { + const out = new Float32Array(16); + for (let col = 0; col < 4; col++) { + for (let row = 0; row < 4; row++) { + let sum = 0; + for (let k = 0; k < 4; k++) sum += a[k * 4 + row] * b[col * 4 + k]; + out[col * 4 + row] = sum; + } } - gl.texElementSubImage2D(gl.TEXTURE_2D, 0, 0, 0, element); - return true; + return out; } diff --git a/html-in-canvas/webgpu-example/webgpu-demo.js b/html-in-canvas/webgpu-example/webgpu-demo.js index f481110c..07b49177 100644 --- a/html-in-canvas/webgpu-example/webgpu-demo.js +++ b/html-in-canvas/webgpu-example/webgpu-demo.js @@ -70,7 +70,7 @@ async function main() { // --------------------------------------------------------------------- // Geometry: interleaved position (vec3) + uv (vec2), plus an index buffer // --------------------------------------------------------------------- - const { vertices, indices } = createCubeGeometry(); + const { vertices, indices, faces } = createCubeGeometry(); const vertexBuffer = device.createBuffer({ size: vertices.byteLength, @@ -181,6 +181,18 @@ async function main() { return true; } + // --------------------------------------------------------------------- + // Pause the spin while the pointer is over the canvas or the form has focus + // --------------------------------------------------------------------- + let pointerOver = false; + canvas.addEventListener("pointerenter", () => { + pointerOver = true; + }); + canvas.addEventListener("pointerleave", () => { + pointerOver = false; + }); + const isPaused = () => pointerOver || source.matches(":focus-within"); + // --------------------------------------------------------------------- // Render loop, driven by the `paint` event // --------------------------------------------------------------------- @@ -193,6 +205,7 @@ async function main() { const view = translation(0, 0, -6); let rotation = 0; let then = null; + let geometrySet = false; canvas.addEventListener("paint", () => { // No snapshot exists until the first paint, and the element may not have @@ -202,8 +215,14 @@ async function main() { return; } + const paused = isPaused(); + + // `then` is updated every frame, even while paused, so the cube + // resumes smoothly instead of jumping ahead. const now = performance.now() * 0.001; // convert to seconds - rotation += then === null ? 0 : now - then; + if (then !== null && !paused) { + rotation += now - then; + } then = now; const model = multiply( @@ -213,6 +232,28 @@ async function main() { const mvp = multiply(projection, multiply(view, model)); device.queue.writeBuffer(uniformBuffer, 0, mvp); + // While paused, tell the browser where the form appears on the cube so + // that hit testing matches what is rendered. Release it when spinning + // resumes. + if (paused) { + canvas.updateElementGeometry(source, { + canvasTransform: elementToCanvasTransform( + mvp, + model, + view, + faces, + source.offsetWidth, + source.offsetHeight, + canvas.clientWidth, + canvas.clientHeight, + ), + }); + geometrySet = true; + } else if (geometrySet) { + canvas.clearElementGeometry(source); + geometrySet = false; + } + const encoder = device.createCommandEncoder(); const pass = encoder.beginRenderPass({ colorAttachments: [ @@ -285,9 +326,98 @@ function createCubeGeometry() { return { vertices: new Float32Array(vertices), indices: new Uint16Array(indices), + faces, }; } +// --- Hit-test geometry --------------------------------------------------- +// Builds the DOMMatrix that maps the element's CSS-pixel box onto the +// on-screen quad of the cube face that is most squarely facing the camera, +// for use with canvas.updateElementGeometry(). +// +// result = viewport * mvp * elementToFace +// +// The viewport step sits before the perspective divide, so the browser +// performs the divide when it applies the matrix. +function elementToCanvasTransform( + mvp, + model, + view, + faces, + elW, + elH, + canvasW, + canvasH, +) { + // Pick the face whose normal points most directly at the camera + let best = faces[0]; + let bestScore = -Infinity; + for (const face of faces) { + const [nx, ny, nz] = face.n; + // Rotated normal (model is rotation-only, so this is also the face centre) + const cx = model[0] * nx + model[4] * ny + model[8] * nz; + const cy = model[1] * nx + model[5] * ny + model[9] * nz; + const cz = model[2] * nx + model[6] * ny + model[10] * nz; + // Face centre in view space (camera at origin) + const vx = cx + view[12]; + const vy = cy + view[13]; + const vz = cz + view[14]; + const score = -(cx * vx + cy * vy + cz * vz) / Math.hypot(vx, vy, vz); + if (score > bestScore) { + bestScore = score; + best = face; + } + } + const { n, r, u } = best; + + // Element pixels -> model space. (0,0) is the face's top-left corner, + // (elW,elH) the bottom-right; element z maps along the face normal so the + // matrix stays invertible. + const toFace = new Float32Array([ + (2 * r[0]) / elW, + (2 * r[1]) / elW, + (2 * r[2]) / elW, + 0, + (-2 * u[0]) / elH, + (-2 * u[1]) / elH, + (-2 * u[2]) / elH, + 0, + n[0], + n[1], + n[2], + 0, + n[0] - r[0] + u[0], + n[1] - r[1] + u[1], + n[2] - r[2] + u[2], + 1, + ]); + + // Clip space -> canvas CSS pixels (y flipped), applied before the w divide + const hw = canvasW / 2; + const hh = canvasH / 2; + const viewport = new Float32Array([ + hw, + 0, + 0, + 0, + 0, + -hh, + 0, + 0, + 0, + 0, + 1, + 0, + hw, + hh, + 0, + 1, + ]); + + const m = multiply(viewport, multiply(mvp, toFace)); + return new DOMMatrix(Array.from(m)); // 16 values, column-major +} + // --- Minimal column-major 4x4 matrix helpers ----------------------------- // WebGPU clip space has z in [0, 1] (WebGL uses [-1, 1]), so the projection // matrix differs from the one gl-matrix's perspective() produces. From 1efda959e3064aed9ccb9d10b0a85937fe872325 Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Tue, 17 Nov 2026 15:26:21 +0000 Subject: [PATCH 06/12] Update html-in-canvas/2d-context-nested-canvases/index.html Co-authored-by: Vadim Makeev --- html-in-canvas/2d-context-nested-canvases/index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/html-in-canvas/2d-context-nested-canvases/index.html b/html-in-canvas/2d-context-nested-canvases/index.html index 5b002b13..d579abb8 100644 --- a/html-in-canvas/2d-context-nested-canvases/index.html +++ b/html-in-canvas/2d-context-nested-canvases/index.html @@ -2,7 +2,7 @@ - HTML-in-Canvas basic test + Nested canvases HTML-in-Canvas demo From 2ee7446295ae44eb967c2fc2426cf47fbae20c80 Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Tue, 17 Nov 2026 15:27:56 +0000 Subject: [PATCH 07/12] Update html-in-canvas/2d-context-example/index.html Co-authored-by: Vadim Makeev --- html-in-canvas/2d-context-example/index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/html-in-canvas/2d-context-example/index.html b/html-in-canvas/2d-context-example/index.html index 4955c3a5..cc697762 100644 --- a/html-in-canvas/2d-context-example/index.html +++ b/html-in-canvas/2d-context-example/index.html @@ -2,7 +2,7 @@ - HTML-in-Canvas basic test + Canvas 2D HTML-in-Canvas demo From a60cd26373cee61bd1b7de5c70cbc65e78e538e3 Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Tue, 17 Nov 2026 15:31:03 +0000 Subject: [PATCH 08/12] Update html-in-canvas/README.md Co-authored-by: Vadim Makeev --- html-in-canvas/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/html-in-canvas/README.md b/html-in-canvas/README.md index 76ea1a69..b6b125f4 100644 --- a/html-in-canvas/README.md +++ b/html-in-canvas/README.md @@ -2,7 +2,7 @@ This set of examples demonstrates usage of the [HTML-in-canvas API](https://github.com/WICG/html-in-canvas): -- [Canvas 2D context example](2d-context-example/): Demonstrates how an HTML form can be rendered on a 2D canvas, have a pixel distortion effect applied to it on mouseover, but still remain accessible, interactive, and submittable ([run example live](https://mdn.github.io/dom-examples/html-in-canvas/2d-context-example/)). -- [WebGL example](webgl-example/): This example shows how to render an HTML form as a texture onto all six sides of a rotating 3D cube. When the form is hovered or focused, the rotation pauses and you can interact with form on the front-most cube face as expected (clicking into it, etc.). Again, it still remains accessible, interactive, and submittable ([run example live](https://mdn.github.io/dom-examples/html-in-canvas/webgl-example/)). -- [WebGPU example](webgpu-example/): This example is the same as the WebGL example, only converted to use WebGPU instead ([run example live](https://mdn.github.io/dom-examples/html-in-canvas/webgpu-example/)). -- [Canvas 2D context nested canvases example](2d-context-nested-canvases/): Demonstrates how the paint events fire in nested canvases ([run example live](https://mdn.github.io/dom-examples/html-in-canvas/2d-context-nested-canvases/)). +- [Canvas 2D context example](2d-context-example/): Demonstrates how an HTML form can be rendered on a 2D canvas with a pixel distortion effect that follows the pointer, while the form remains accessible, interactive, and submittable ([run example live](https://mdn.github.io/dom-examples/html-in-canvas/2d-context-example/)). +- [WebGL example](webgl-example/): Demonstrates how to render an HTML form as a texture on all six faces of a rotating 3D cube. The rotation pauses when the form is hovered or focused, so you can interact with the form on the front-most face as expected (clicking into it, and so on). As in the 2D example, the form remains accessible, interactive, and submittable ([run example live](https://mdn.github.io/dom-examples/html-in-canvas/webgl-example/)). +- [WebGPU example](webgpu-example/): Demonstrates the same rotating cube as the WebGL example, only using WebGPU ([run example live](https://mdn.github.io/dom-examples/html-in-canvas/webgpu-example/)). +- [Canvas 2D context nested canvases example](2d-context-nested-canvases/): Demonstrates how `paint` events fire in nested canvases. Click the button to change the color of the inner element, and watch the console to see which canvases repaint ([run example live](https://mdn.github.io/dom-examples/html-in-canvas/2d-context-nested-canvases/)). From ba71d69a766e2e58d93b32b48c8f93a6147fda65 Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Tue, 17 Nov 2026 15:31:59 +0000 Subject: [PATCH 09/12] Update html-in-canvas/2d-context-example/pointer-distort.js Co-authored-by: Vadim Makeev --- html-in-canvas/2d-context-example/pointer-distort.js | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/html-in-canvas/2d-context-example/pointer-distort.js b/html-in-canvas/2d-context-example/pointer-distort.js index 1155fcff..74c227a1 100644 --- a/html-in-canvas/2d-context-example/pointer-distort.js +++ b/html-in-canvas/2d-context-example/pointer-distort.js @@ -3,9 +3,13 @@ * Call fx.apply() once per frame, AFTER your scene has been drawn. * Only pixels near the pointer are read and rewritten, so it stays cheap. * - * const ctx = canvas.getContext('2d', { willReadFrequently: true }); + * const ctx = canvas.getContext("2d", { willReadFrequently: true }); * const fx = createPointerDistort(canvas); - * function loop(t) { drawMyScene(ctx, t); fx.apply(t); requestAnimationFrame(loop); } + * canvas.addEventListener("paint", () => { + * drawMyScene(ctx); + * fx.apply(performance.now()); + * canvas.requestPaint(); + * }); */ export function createPointerDistort(canvas, options = {}) { const o = { From d26a737c8760c5e24d1b6b97b342abc3f0cddddb Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Tue, 17 Nov 2026 15:42:42 +0000 Subject: [PATCH 10/12] Fixes for pepelsbey review --- README.md | 2 ++ .../2d-context-example/pointer-distort.js | 4 +-- html-in-canvas/webgl-example/webgl-demo.js | 26 ++++++++++++------- html-in-canvas/webgpu-example/webgpu-demo.js | 6 +---- 4 files changed, 22 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 33ea9355..9c8fa6a0 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,8 @@ Do not specify supported browsers and their versions in code comments or prose, - The "history-api" directory contains an example that demonstrates the [History API](https://developer.mozilla.org/docs/Web/API/History_API). [View the demo live](https://mdn.github.io/dom-examples/history-api/). +- The "html-in-canvas" directory contains examples demonstrating the [HTML-in-canvas API](https://developer.mozilla.org/docs/Web/API/HTML-in-Canvas_API). See the [HTML-in-canvas README](html-in-canvas/README.md) for more information. + - The "indexeddb-api" directory contains a demo for the [IndexedDB API](https://mdn.github.io/dom-examples/indexeddb-api/index.html). - The "insert-adjacent" directory contains basic demos for [insertAdjacentElement](https://mdn.github.io/dom-examples/insert-adjacent/insertAdjacentElement.html) and [insertAdjacentText](https://mdn.github.io/dom-examples/insert-adjacent/insertAdjacentText.html). diff --git a/html-in-canvas/2d-context-example/pointer-distort.js b/html-in-canvas/2d-context-example/pointer-distort.js index 74c227a1..e185ebdb 100644 --- a/html-in-canvas/2d-context-example/pointer-distort.js +++ b/html-in-canvas/2d-context-example/pointer-distort.js @@ -3,7 +3,7 @@ * Call fx.apply() once per frame, AFTER your scene has been drawn. * Only pixels near the pointer are read and rewritten, so it stays cheap. * - * const ctx = canvas.getContext("2d", { willReadFrequently: true }); + * const ctx = canvas.getContext("2d"); * const fx = createPointerDistort(canvas); * canvas.addEventListener("paint", () => { * drawMyScene(ctx); @@ -64,7 +64,7 @@ export function createPointerDistort(canvas, options = {}) { bh = y1 - y0; if (bw <= 0 || bh <= 0) return; - const img = ctx.getImageData(x0, y0, bw, bh); // throws if the canvas is tainted (see note below) + const img = ctx.getImageData(x0, y0, bw, bh); // throws if the canvas is tainted const src = img.data; const dst = new Uint8ClampedArray(src); // copy; we read src, write dst const mx = m.x - x0, diff --git a/html-in-canvas/webgl-example/webgl-demo.js b/html-in-canvas/webgl-example/webgl-demo.js index 1e50bcf2..f284eb93 100644 --- a/html-in-canvas/webgl-example/webgl-demo.js +++ b/html-in-canvas/webgl-example/webgl-demo.js @@ -1,9 +1,5 @@ // A spinning cube with an HTML element as the texture on every face, -// using WebGL 2 and the HTML-in-Canvas proposal -// (https://github.com/WICG/html-in-canvas). -// -// Requires a Chromium build with HTML-in-Canvas enabled -// (chrome://flags/#canvas-draw-element, or the origin trial). +// using WebGL and HTML-in-Canvas main(); @@ -363,10 +359,22 @@ function elementToCanvasTransform( const hw = canvasW / 2; const hh = canvasH / 2; const viewport = new Float32Array([ - hw, 0, 0, 0, - 0, -hh, 0, 0, - 0, 0, 1, 0, - hw, hh, 0, 1, + hw, + 0, + 0, + 0, + 0, + -hh, + 0, + 0, + 0, + 0, + 1, + 0, + hw, + hh, + 0, + 1, ]); const m = multiply(viewport, multiply(mvp, toFace)); diff --git a/html-in-canvas/webgpu-example/webgpu-demo.js b/html-in-canvas/webgpu-example/webgpu-demo.js index 07b49177..11f37e38 100644 --- a/html-in-canvas/webgpu-example/webgpu-demo.js +++ b/html-in-canvas/webgpu-example/webgpu-demo.js @@ -1,9 +1,5 @@ // A spinning cube with an HTML element as the texture on every face, -// using WebGPU and the HTML-in-Canvas proposal -// (https://github.com/WICG/html-in-canvas). -// -// Requires a Chromium build with HTML-in-Canvas enabled -// (chrome://flags/#canvas-draw-element, or the origin trial). +// using WebGPU and HTML-in-Canvas main(); From 55bfe9d8549542e2d1cfa1bba4376d8a849fd7ef Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Wed, 18 Nov 2026 07:47:55 +0000 Subject: [PATCH 11/12] Update html-in-canvas/2d-context-example/index.html Co-authored-by: Vadim Makeev --- html-in-canvas/2d-context-example/index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/html-in-canvas/2d-context-example/index.html b/html-in-canvas/2d-context-example/index.html index cc697762..4102607c 100644 --- a/html-in-canvas/2d-context-example/index.html +++ b/html-in-canvas/2d-context-example/index.html @@ -3,7 +3,7 @@ Canvas 2D HTML-in-Canvas demo - + From dcdf1571c5c6828d7d0491b85e4a7d44c8afdab6 Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Wed, 18 Nov 2026 07:48:03 +0000 Subject: [PATCH 12/12] Update html-in-canvas/2d-context-nested-canvases/index.html Co-authored-by: Vadim Makeev --- html-in-canvas/2d-context-nested-canvases/index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/html-in-canvas/2d-context-nested-canvases/index.html b/html-in-canvas/2d-context-nested-canvases/index.html index d579abb8..e088f8c2 100644 --- a/html-in-canvas/2d-context-nested-canvases/index.html +++ b/html-in-canvas/2d-context-nested-canvases/index.html @@ -3,7 +3,7 @@ Nested canvases HTML-in-Canvas demo - +