Building a black hole in the browser
2 min read
The M87 black hole image was fixed angle. I wanted to orbit the disk, flip relativistic beaming on and off, and compare edge-on vs polar views without opening a paper. The result is a client-side sim on my research page.
Goal
- Interactive camera (drag + a few presets)
- Lensing, shadow, and optional hot disk in one pass
- Runs on a laptop GPU, no backend
Stack
Next.js serves the page. A React client component owns the <canvas>, pointer input, and uniforms. WebGL draws one fullscreen triangle; a GLSL fragment shader does the physics per pixel. TypeScript is just glue. No Three.js, no video, no server-side simulation.
Approach
Each pixel fires a null geodesic through Schwarzschild spacetime (). About 140 leapfrog steps per ray. Captured rays paint the shadow. Escaping rays sample procedural stars and can cross the equatorial disk when the ray hits .
Integration loop (simplified):
for (int step = 0; step < 140; step++) {
float r = sqrt(dot(pos, pos));
if (r <= 1.01) { captured = true; break; }
float h = clamp(0.068 * (r - 0.84), 0.014, 0.42);
vec3 acc = -1.5 * L2 * pos / (r2 * r2 * r);
vec3 nextPos = pos + vel * h + 0.5 * acc * h * h;
// ... leapfrog velocity update ...
}
Disk hits are plane tests, not mesh intersections:
if (uDiskMix > 0.002 && pos.y * nextPos.y <= 0.0) {
float tCross = abs(pos.y) / (abs(pos.y) + abs(nextPos.y) + 1e-6);
vec3 hit = mix(pos, nextPos, tCross);
vec4 diskSample = evaluateDisk(hit, photonTravelDir);
accumColor += transmittance * diskSample.rgb * diskSample.a;
}
Doppler mixes gravitational redshift with orbital beaming before brightness:
float gFactor = mix(gravRedshift, dopplerShift, uDoppler);
float beaming = pow(clamp(gFactor, 0.25, 2.2), 3.2);
Disk structure is procedural FBM, not MHD. Presets only move the camera and disk vs background mix; Edge-on and Polar share the same physics.
Split of work
| Layer | Job |
|---|---|
| React | yaw/pitch, presets, Doppler, requestAnimationFrame |
| WebGL | compile shader once, set uniforms, draw quad |
| Fragment shader | integrate ray, horizon test, disk hit, sky, tone map |
Each frame, React only pushes camera and toggles into uniforms, then draws:
gl.uniform3f(uniforms.camPos, camX, camY, camZ);
gl.uniform1f(uniforms.diskMix, state.diskMix);
gl.uniform1f(uniforms.doppler, state.doppler);
gl.drawArrays(gl.TRIANGLES, 0, 6);
If shader compile fails, the effect bails early. I learned that after a typo left a silent black canvas.
Trade-offs
Schwarzschild only (no spin). Fixed step size near the photon sphere instead of adaptive integration. Disk is a shading hack that looks right, not a fluid sim.
Try it
/research/black-hole. Toggle Doppler on Edge-on or Polar.