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/index.html b/html-in-canvas/2d-context-example/index.html new file mode 100644 index 00000000..4102607c --- /dev/null +++ b/html-in-canvas/2d-context-example/index.html @@ -0,0 +1,24 @@ + + + + + Canvas 2D HTML-in-Canvas demo + + + + + +
+
+ + +
+
+ + +
+ +
+
+ + 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..214ee4c5 --- /dev/null +++ b/html-in-canvas/2d-context-example/index.js @@ -0,0 +1,26 @@ +import { createPointerDistort } from "./pointer-distort.js"; + +function main() { + const canvas = document.querySelector("canvas"); + const form = document.querySelector("canvas form"); + const ctx = canvas.getContext("2d"); + + if (!ctx.drawElementImage) { + alert( + "CanvasRenderingContext2D.drawElementImage() is not available. HTML-in-Canvas is not supported.", + ); + return; + } + + const fx = createPointerDistort(canvas, { radius: 120 }); + + canvas.addEventListener("paint", () => { + ctx.fillStyle = "#7D82B8"; + ctx.fillRect(0, 0, canvas.width, canvas.height); + ctx.drawElementImage(form, 100, 100); + fx.apply(performance.now()); + canvas.requestPaint(); + }); +} + +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..e185ebdb --- /dev/null +++ b/html-in-canvas/2d-context-example/pointer-distort.js @@ -0,0 +1,126 @@ +/** + * 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"); + * const fx = createPointerDistort(canvas); + * canvas.addEventListener("paint", () => { + * drawMyScene(ctx); + * fx.apply(performance.now()); + * canvas.requestPaint(); + * }); + */ +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 + 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/2d-context-nested-canvases/index.html b/html-in-canvas/2d-context-nested-canvases/index.html new file mode 100644 index 00000000..e088f8c2 --- /dev/null +++ b/html-in-canvas/2d-context-nested-canvases/index.html @@ -0,0 +1,20 @@ + + + + + Nested canvases HTML-in-Canvas demo + + + + +

+ +
+ 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 new file mode 100644 index 00000000..b6b125f4 --- /dev/null +++ b/html-in-canvas/README.md @@ -0,0 +1,8 @@ +# 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 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/)). diff --git a/html-in-canvas/webgl-example/index.html b/html-in-canvas/webgl-example/index.html new file mode 100644 index 00000000..57ab8a43 --- /dev/null +++ b/html-in-canvas/webgl-example/index.html @@ -0,0 +1,25 @@ + + + + + WebGL HTML-in-Canvas demo + + + + + + +
+
+ + +
+
+ + +
+ +
+
+ + 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..f284eb93 --- /dev/null +++ b/html-in-canvas/webgl-example/webgl-demo.js @@ -0,0 +1,443 @@ +// A spinning cube with an HTML element as the texture on every face, +// using WebGL and HTML-in-Canvas + +main(); + +function main() { + const canvas = document.querySelector("#gl-canvas"); + const source = document.querySelector("form"); + + const gl = canvas.getContext("webgl2", { alpha: false }); + if (!gl) { + alert("WebGL 2 is not supported by your browser."); + return; + } + if (typeof gl.texElementSubImage2D !== "function") { + alert( + "texElementSubImage2D() is not available. HTML-in-Canvas is not supported.", + ); + return; + } + + // --------------------------------------------------------------------- + // 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); + } + `; + + const fragmentShaderSource = `#version 300 es + precision mediump float; + in vec2 vUV; + uniform sampler2D uTexture; + out vec4 outColor; + + void main() { + outColor = texture(uTexture, vUV); + } + `; + + 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); + + 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; + } + + // --------------------------------------------------------------------- + // 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", () => { + // 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(); + + // `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 + if (then !== null && !paused) { + rotation += 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)); + + // 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; + } + + // Draw + gl.viewport(0, 0, canvas.width, canvas.height); + gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); + + 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); + + canvas.requestPaint(); // request the next paint + }); +} + +// --- 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; +} + +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; +} + +// --- 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(). +// +// 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 ----------------------------- +// 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, + ]); +} + +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; +} diff --git a/html-in-canvas/webgpu-example/index.html b/html-in-canvas/webgpu-example/index.html new file mode 100644 index 00000000..02d2e0c4 --- /dev/null +++ b/html-in-canvas/webgpu-example/index.html @@ -0,0 +1,25 @@ + + + + + WebGPU HTML-in-Canvas demo + + + + + + +
+
+ + +
+
+ + +
+ +
+
+ + diff --git a/html-in-canvas/webgpu-example/style.css b/html-in-canvas/webgpu-example/style.css new file mode 100644 index 00000000..a55b954d --- /dev/null +++ b/html-in-canvas/webgpu-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/webgpu-example/webgpu-demo.js b/html-in-canvas/webgpu-example/webgpu-demo.js new file mode 100644 index 00000000..11f37e38 --- /dev/null +++ b/html-in-canvas/webgpu-example/webgpu-demo.js @@ -0,0 +1,476 @@ +// A spinning cube with an HTML element as the texture on every face, +// using WebGPU and HTML-in-Canvas + +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, faces } = 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; + } + + // --------------------------------------------------------------------- + // 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", () => { + // 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(); + + // `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 + if (then !== null && !paused) { + rotation += 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); + + // 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: [ + { + 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()]); + + canvas.requestPaint(); // request the next paint + }); +} + +// --- 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), + 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. +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; +}