W.William
Weeks-Balconi

Working examples

๐Ÿ”ฎ Raytracer โ€” Rust + WASM

Reference guide1 min readOpen working example โ†—

A real-time ray tracer rendering a 640ร—480 scene with 5 spheres, reflections, shadows, and an orbiting camera โ€” all computed per-pixel in Rust, compiled to WASM.

How Ray Tracing Works

For each pixel, a ray is cast from the camera through the image plane into the scene. The ray tests intersection against every sphere. At the hit point, we compute lighting (diffuse + specular) from two point lights, check shadows, and recursively trace reflected rays up to 3 bounces deep.

Scene

ObjectColorSpecularReflective
Ground planeGray1015%
Azure sphereBlue8040%
Green sphereGreen20060%
Red sphereRed5020%
Gold sphereYellow12050%

Performance

At 640ร—480 = 307,200 pixels per frame, each requiring sphere intersections, shadow rays, and reflection bounces, this is a lot of math. Rust compiles to tight WASM that typically achieves 3-8 fps depending on device โ€” impressive for a brute-force per-pixel raytracer running in a browser tab.

Implementation Details

  • Vec3 โ€” minimal vector math (dot, normalize, reflect, scale)

  • ImageData โ€” pixel buffer written directly to canvas via put_image_data

  • Clamped<&[u8]> โ€” zero-copy buffer transfer from Rust to Canvas API

  • Camera orbits the scene using sin/cos of elapsed time

Build

wasm-pack build rust/raytracer --target web --out-dir ../../resources/public/wasm/raytracer