9 min read

Clickable DOM on a 3D plane: HTML-in-Canvas hit testing is a projective map

Chrome's HTML-in-Canvas API can texture live DOM onto WebGL geometry, but input only lands if you hand the browser the full 4×4 projective matrix. An affine fit misses 5 of 9 buttons at 65°. Plus three Chrome 158 behaviours the docs don't spell out: paint records, stacking and corners behind the camera.


I built a walkable 3D trading floor whose screens are live data grids and charts: real DOM, ticking at market-data rates, textured onto planes in a WebGL scene with Chrome's new HTML-in-Canvas API (stable since Chrome 157). Getting the pixels onto the planes took an afternoon. Getting clicks to land on the right row took the rest of the week, and the failure was silent: the picture is always right, because WebGL draws it; only the input is wrong.

The symptom is easy to reproduce. Take a 400×300 element laid out as a 3×3 grid of buttons, put it on a plane rotated 50° away from the camera, and tell the browser where it is with a 2D matrix fitted to three of its projected corners. Click the centre of each button as it appears on screen. Six of the nine clicks land on the right button. At 65°, four do. With the full 4×4 projective matrix, all nine land at every angle.

This note explains why, what exactly to hand the browser, and three behaviours of Chrome 158's implementation that you will hit as soon as the camera moves: when an element's image becomes available, how overlapping elements stack, and what happens when a corner goes behind the camera.

The API in one paragraph

A canvas declared with content="drawable" lays out its drawable children like normal DOM but never displays them. Each time one of them repaints, the canvas fires a paint event whose changedElements lists what changed, and you can draw an element into a 2D context with drawElementImage or upload it into a WebGL texture with texElementSubImage2D. Drawing is only half of the contract: for hit testing and accessibility, you also tell the canvas where the element ended up, with canvas.updateElementGeometry(element, { canvasTransform }). In the 2D context drawElementImage sets that geometry for you. In WebGL nothing can, because only your shader knows where the texel ends up, so the transform is yours to compute.

What the transform has to be

canvasTransform is a DOMMatrix that maps the element's CSS pixel coordinates into the canvas's CSS pixel box, with the origin at the canvas's top-left corner. I checked the origin explicitly: an identity transform on an element that is laid out 200 px down inside the canvas reports a bounding rect at the canvas's corner, not 200 px lower. The element's own layout position plays no part.

The element is drawn on a flat rectangle in 3D, so the map from its pixels to the screen is a chain of four matrices: element pixels to plane-local units, plane to world (the mesh's model matrix), world to clip space (view and projection), and clip space to canvas pixels. All four are 4×4 and the last division by w is what makes the result a perspective projection. Fold them into one matrix and give the browser that, in column-major order, which is what both DOMMatrix.fromFloat64Array and WebGL libraries use:

// Column-major 4×4 helpers: fromRows takes a matrix written row by row.
const fromRows = (r) => [0, 1, 2, 3].flatMap((c) => [r[c], r[c + 4], r[c + 8], r[c + 12]]);
const mul = (a, b) => Array.from({ length: 16 }, (_, i) =>
  [0, 1, 2, 3].reduce((s, k) => s + a[k * 4 + (i % 4)] * b[(i >> 2) * 4 + k], 0));

// W, H: element size in CSS px. pw, ph: plane size in world units.
// cw, ch: canvas size in CSS px. model, view, proj: 4×4, column-major.
const elementToPlane = fromRows([
  pw / W, 0,       0, -pw / 2,
  0,      -ph / H, 0,  ph / 2,   // CSS y grows down, plane y grows up
  0,      0,       1,  0,
  0,      0,       0,  1,
]);
const clipToCanvas = fromRows([
  cw / 2, 0,       0, cw / 2,
  0,      -ch / 2, 0, ch / 2,
  0,      0,       1, 0,
  0,      0,       0, 1,
]);
const m = mul(clipToCanvas, mul(proj, mul(view, mul(model, elementToPlane))));
canvas.updateElementGeometry(el, {
  canvasTransform: DOMMatrix.fromFloat64Array(new Float64Array(m)),
});

Chrome accepts the non-affine matrix and applies the perspective divide itself: elementFromPoint, getBoundingClientRect, hover, focus and real pointer events all follow the projected quadrilateral.

Why an affine fit can't work

A plane seen through a pinhole camera is a homography: a 3×3 projective map with eight degrees of freedom. An affine 2D matrix has six. It can match any three corners of the projected quadrilateral, but the fourth corner and everything in between drift, and the drift grows with obliqueness because perspective foreshortening is not linear across the plane. The only angle where affine is exact is the one you are most likely to test with: facing the plane head-on.

Here is the measurement. The setup is the one above: a 400×300 element of nine buttons on a 4×3 plane, a 60° vertical field of view, the camera 5 units away, an 800×600 canvas. For each angle I compute the true screen position of each button's centre, call elementFromPoint there, and count correct hits under the exact matrix and under an affine matrix fitted to the top-left, top-right and bottom-left corners. The last column is the distance between the true and the affine position of the bottom-right corner. Chrome 158.0.8127.88, headless:

rotation  projective hits  affine hits  far-corner error
   0°          9 / 9          9 / 9          0.0 px
  30°          9 / 9          8 / 9        129.9 px
  50°          9 / 9          6 / 9        210.9 px
  65°          9 / 9          4 / 9        260.2 px

At 30° a 130 px error already crosses a button boundary. On a dense grid with 27 px rows, the click lands several rows away from where the user aimed.

Three behaviours to design around

1. An element has no image until the canvas has painted it

getElementImageDefaultSize(), which you need to allocate the texture, throws for an element that has not been through a paint yet. Appending an element and querying it in the same task fails, and so does querying in the next requestAnimationFrame; it works once the canvas's paint event has fired:

same task      throws  "…: No cached paint record for element."
next rAF       throws  "…: No cached paint record for element."
after 'paint'  { width: 120, height: 80 }

Once a paint record exists, texElementSubImage2D also works outside the paint handler and uploads the latest record. That matters more than it looks. It means uploads can live in the render loop, where you know which planes are visible and how far away they are, instead of in an event handler that fires whenever any grid cell ticks. The returned size is the CSS size multiplied by the canvas's pixel ratio (a 1280×720 element is 2560×1440 on a canvas sized for DPR 2), and UNPACK_FLIP_Y_WEBGL is honoured, so the texture can follow whatever UV convention the rest of the scene uses.

For a trading screen this turns into a staleness budget you choose explicitly. A 1440×810 panel on a DPR 2 canvas is 2880×1620×4 bytes, about 18.7 MB per upload; at 12 uploads per second that is 224 MB/s for one grid. In the demo, uploads are capped by distance (12 Hz near, 6 Hz mid-room, 3 Hz far) and skipped for planes outside the frustum, which stay dirty and upload the moment they come back into view. A panel you are not looking at is allowed to be stale; the one you are using is uploaded every frame.

2. Overlapping elements stack in the order they first got geometry

When two transformed elements overlap on screen, one of them wins elementFromPoint. The documentation describes the updated element moving to the top of the hit-test stack on each update unless preserveHitTestOrder is set. That is not what I measured. Two 200×200 elements, a and b, overlapping; a frame between each step; hit test at a point inside both:

first geometry: a, then b         → b
clear a, set a again              → b
clear b, set b again              → b
clear both, set b then a          → b
update a (new matrix)             → b
update b (new matrix)             → b
update a, preserveHitTestOrder    → b
update b, then a                  → b

In a fresh document where b received geometry first and a second, a won, and kept winning. In Chrome 158 the stacking order is fixed by the order in which elements first receive geometry; neither later updates nor clearing and re-setting the geometry reorder them.

So "update the planes back to front every frame and let the nearest win" does nothing. What works is deciding the order once, before the first real frame: assign a throwaway transform to every element in the order you want them stacked, bottom first, and clear it again. In the trading floor that means wall screens first and desk monitors last, because the monitors are what stand in front of the walls. A scene whose occlusion order genuinely changes as you move cannot be expressed this way; occlusion by non-DOM geometry (a desk in front of a screen) cannot be expressed at all, since the browser knows nothing about your depth buffer.

3. A corner behind the camera makes the whole element unclickable

Walk close to a screen at a grazing angle and part of the plane goes behind the camera. Those corners get a negative w, and the projective map folds: points behind the eye are flipped through it. I put a 200×200 element on a 2×2 plane rotated 80°, with the camera 0.8 units from its centre:

corner w:            -0.185   1.785   -0.185   1.785
bounding rect:       x 362, y -2063, 365 × 4686 px
elementFromPoint:    0 hits on a 10 px grid over the whole 600×500 canvas

Chrome doesn't clip the quadrilateral at the near plane; it reports a bounding box more than four thousand pixels tall and stops hit testing the element altogether, including the half that is plainly visible. Before sending a matrix, transform the four corners and check w. If any is below the near plane, call clearElementGeometry() instead, which also marks the element as off screen for assistive technology, rather than leaving a nonsensical rectangle in the accessibility tree.

Why the usual safeguards miss this

The types are no help: canvasTransform is a DOMMatrix, and an affine one is a perfectly valid DOMMatrix. Screenshot tests pass, because the browser never draws the element; your shader does, and the shader is right. Interaction tests that click a known button tend to do so with the camera square to the plane, the one configuration where an affine fit is exact. And stacking only matters where two planes overlap on screen, which a test scene with one plane never produces.

The cheapest detector is the measurement above, run as an assertion: for a few camera poses, including an oblique one and one with a corner behind the camera, project the centre of each known child element through the same matrices the renderer uses and check that elementFromPoint returns that child. It needs no screenshots and no image comparison. One caution if you drive it with real input: headless Chrome on a software GPU renders at a few frames per second, so wait for camera animations to finish instead of sleeping for a fixed time. Otherwise the test clicks where the plane was rather than where it is.

Using a plane, not just pointing at it

Hit testing being exact at any angle does not make an oblique grid comfortable to use. Column resizing, scrollbars and range inputs are driven by pointer movement, and at an angle one screen pixel no longer corresponds to one element pixel, nor even to a constant number of them across the plane. I did not try to measure how each widget copes with that; I sidestepped it. When the user chooses a screen, I fly the camera onto the plane's normal at the distance where one CSS pixel of the element covers one device-independent screen pixel:

distance = planeHeight × viewportHeight / (2 × tan(fov / 2) × targetHeightPx)

with targetHeightPx equal to the element's CSS height, capped so the whole plane still fits the viewport. At that distance the projective matrix reduces to a scale of 1 and a translation, text is as sharp as on a flat page, and every drag gesture behaves as it would outside the canvas.

The general rule

When you render through a camera and want input to come back through it, the inverse has to be the same projection, not an approximation that agrees with it at the pose you tested. HTML-in-Canvas makes that unusually concrete: the forward path is your shader, the inverse is a matrix you hand to the browser, and nothing checks that the two agree. Compose the same four matrices the renderer uses, clear the geometry when the projection folds, and decide stacking once, because the browser will not revisit it.

The trading floor is live at trading-floor-3d.vercel.app and needs Chrome 157 or later. Walk with WASD, click a screen to use it, and try the order ticket or the kill switch; the how it was built page covers the upload pipeline and lighting that this note leaves out. The source is on GitHub.