← Back

Physics on a web page without rebuilding the page

29 November 2026 · 2 min read

The toolbox on the home page and the big 404 on the error page share one idea: keep the elements as ordinary HTML, and let a physics engine decide where they are. No canvas redraw of text, so the words stay selectable, crisp and accessible.

The pattern

For each element I create an invisible body in matter-js with the same width and height. On every physics step I read the body’s position and angle and write them back as a CSS transform on the element. The engine is the source of truth for movement and the DOM is just the paint. Pills get a rounded rectangle, the zero in 404 gets a circle, and a few walls keep everything inside the stage.

Dragging

Matter ships with a mouse constraint, but it also attaches touch listeners that block scrolling, which is a bad trade on a phone where the stage is in the middle of a page. The 404 page skips it and uses pointer events instead: on pointer down a spring constraint is attached from the pointer to the body, on move the anchor follows the pointer, and on release the constraint is removed. Only the digits set touch-action: none, so you can still scroll past the rest of the page with your thumb.

Traps I hit

  • Resizing. Rotate a phone and the walls move. Bodies that were resting near the old edge end up outside the new stage. After rebuilding the walls, clamp every body back inside and zero its velocity.
  • Only simulate what’s visible. An IntersectionObserver starts and stops the runner, so a page scrolled out of view costs nothing.
  • Reduced motion. With prefers-reduced-motion on, the digits and chips stay where the layout put them and the shake button is hidden.
  • Scoped CSS. Astro scopes component styles to elements it rendered. Elements you create from JavaScript don’t carry that scope, so styling them needs :global(). I lost a while to unstyled grey chips before remembering this.

None of it is clever, but it’s a small amount of code for a lot of play, and it degrades to a normal page when JavaScript is off.

More posts Work with me