David Harper

N-Body Demo

The Web is very powerful but too often underappreciated. What you see below is a live simulation running in JavaScript. I rely on Open Web standards throughout. ESM modules via import maps (no bundling!) and the Canvas graphical API. We stand on the shoulders of giants who have built the Web software platform we all enjoy.

To explain what's going on in more detail: There are 3,000 particles in a 2D universe. They're attracted to each other, sorta like gravity. I used my experience with numerical integration to write a modest engine that simulates their dynamics. I draw results from that engine to an HTML <canvas> element, one frame at a time. I use the requestAnimationFrame API to trigger the next step, so I don't have to think about timing or when to pause.

I calibrated this engine to be entertaining, not precise. You can have accuracy or speed with numerical integration, but rarely both. You'll notice that collisions with the walls slow down the particles. Errors can build up over time to produce "numerical heating." I added this "cooling" effect to keep the simulation stable.

I also added some interaction. If you're viewing this on a device with a cursor, you can hover over the simulation below, and you'll attract the dots.