Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
24 changes: 24 additions & 0 deletions html-in-canvas/2d-context-example/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Canvas 2D HTML-in-Canvas demo</title>
<script type="module" src="index.js"></script>
<link href="style.css" rel="stylesheet" />
</head>
<body>
<canvas width="640" height="480" content="drawable">
<form drawable>
<div>
<label for="name">Name:</label>
<input type="text" id="name" name="name" />
</div>
<div>
<label for="email">Email:</label>
<input type="email" id="email" name="email" />
</div>
<button>Submit</button>
</form>
</canvas>
</body>
</html>
26 changes: 26 additions & 0 deletions html-in-canvas/2d-context-example/index.js
Original file line number Diff line number Diff line change
@@ -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();
126 changes: 126 additions & 0 deletions html-in-canvas/2d-context-example/pointer-distort.js
Original file line number Diff line number Diff line change
@@ -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 };
}
34 changes: 34 additions & 0 deletions html-in-canvas/2d-context-example/style.css
Original file line number Diff line number Diff line change
@@ -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;
}
20 changes: 20 additions & 0 deletions html-in-canvas/2d-context-nested-canvases/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Nested canvases HTML-in-Canvas demo</title>
<script type="module" src="index.js"></script>
<link href="style.css" rel="stylesheet" />
</head>
<body>
<p><button>Change inner color</button></p>
<canvas id="parent-canvas" width="640" height="480" content="drawable">
<div id="parent-element" drawable>
Parent element content
<canvas id="child-canvas" width="300" height="200" content="drawable">
<div id="child-element" drawable>Child element content</div>
</canvas>
</div>
</canvas>
</body>
</html>
39 changes: 39 additions & 0 deletions html-in-canvas/2d-context-nested-canvases/index.js
Original file line number Diff line number Diff line change
@@ -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();
21 changes: 21 additions & 0 deletions html-in-canvas/2d-context-nested-canvases/style.css
Original file line number Diff line number Diff line change
@@ -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;
}
8 changes: 8 additions & 0 deletions html-in-canvas/README.md
Original file line number Diff line number Diff line change
@@ -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/)).
25 changes: 25 additions & 0 deletions html-in-canvas/webgl-example/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>WebGL HTML-in-Canvas demo</title>
<link href="style.css" rel="stylesheet" />
<script src="webgl-demo.js" type="module"></script>
</head>

<body>
<canvas id="gl-canvas" width="640" height="480" content="drawable">
<form drawable>
<div>
<label for="name">Name:</label>
<input type="text" id="name" name="name" />
</div>
<div>
<label for="email">Email:</label>
<input type="email" id="email" name="email" />
</div>
<button>Submit</button>
</form>
</canvas>
</body>
</html>
41 changes: 41 additions & 0 deletions html-in-canvas/webgl-example/style.css
Original file line number Diff line number Diff line change
@@ -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;
}
Loading
Loading