←Blog

Real-Time Dithering with Rust and WebAssembly (and When You Don't Need It)

Real-Time Dithering with Rust and WebAssembly (and When You Don't Need It)

The figure on my home page is a 3D model of a head, rendered with three.js and turned into a two-colour, 1-bit image on every frame by a small Rust library compiled to WebAssembly. Move the cursor over it and a lens switches the algorithm underneath: Floyd–Steinberg error diffusion outside, ordered Bayer dithering inside.

This post covers how the pipeline works, the one-line mistake that briefly made the WebAssembly version slower than plain JavaScript, and what the benchmarks say about when WebAssembly is actually worth it.

The pipeline

Every animation frame does four things:

  1. three.js renders the head into a small WebGL canvas that isn't attached to the page, at one pixel per CSS pixel of the figure (about 340×255).
  2. gl.readPixels copies the frame directly into the WebAssembly module's memory. There's no intermediate JavaScript array: the destination is a Uint8Array view over the module's memory.
  3. Rust converts each pixel to a tone, then dithers the whole frame, writing an RGBA image back into its memory: the ink colour where it's dark, fully transparent where it's light.
  4. putImageData draws that buffer onto the visible canvas, which is scaled with image-rendering: pixelated so the dots stay crisp.
const mem = wasm.memory.buffer;
gl.readPixels(0, 0, W, H, gl.RGBA, gl.UNSIGNED_BYTE,
    new Uint8Array(mem, bufs.src, W * H * 4));

wasm.render_frame(bufs.src, W, H, bufs.scratch, bufs.out, bufs.params);

ctx.putImageData(
    new ImageData(new Uint8ClampedArray(mem, bufs.out, W * H * 4), W, H), 0, 0);

There's no wasm-bindgen. The module exports alloc, dealloc and one render_frame function that takes raw pointers, the same approach I've used for other in-browser image tools. The logic underneath works on plain Rust slices, so cargo test runs it natively. The compiled module is 23 KB.

Why error diffusion is sequential

Dithering fakes shades of grey with only black and white. The simplest version is a threshold: anything darker than 50% becomes ink. That throws away every mid-tone.

Error diffusion keeps them. When a pixel that's 30% grey is rounded to white, the 30% it lost is pushed onto neighbours it hasn't visited yet, so they're more likely to become ink. Floyd–Steinberg splits that error four ways:

// Floyd–Steinberg weights, mirrored on right-to-left rows.
let dir: isize = if ltr { 1 } else { -1 };
for (dx, dy, wgt) in [(dir, 0usize, 7.0), (-dir, 1, 3.0), (0, 1, 5.0), (dir, 1, 1.0)] {
    // ...bounds checks...
    scratch[ny * w + nx as usize] += err * wgt / 16.0;
}

Because each pixel depends on the error from the ones before it, you can't hand the pixels to a GPU to process in parallel the way a shader would. It's a tight sequential loop over every pixel, which is the kind of code WebAssembly is supposed to be good at.

Two details make it look better. Serpentine scanning alternates left-to-right and right-to-left on each row, which breaks up the diagonal "worm" patterns a one-way scan leaves. And inside the cursor lens, pixels use an 8×8 Bayer matrix instead: each pixel is compared against a fixed, tiled threshold. That gives the regular cross-hatched texture, and it's why no error is diffused into the lens, so the pattern stays clean.

The mistake: WebAssembly was slower than JavaScript

The first version took about 3.1 ms per frame. A straight JavaScript port of the same code took 1.6 ms. The Rust was twice as slow.

The culprit was one call per pixel: powf, used for the gamma curve. WebAssembly has instructions for square roots but not for powers, so Rust compiles powf to a software routine. JavaScript's ** runs on the browser's native math library.

The fix was to stop calling it per pixel. The input is 8-bit, so there are only 256 possible tones. The curve is now built once per frame as a 256-entry lookup table, and the luminance math uses integers:

let mut curve = [0f32; 256];
for (i, c) in curve.iter_mut().enumerate() {
    *c = (i as f32 / 255.0 * p.exposure).clamp(0.0, 1.0).powf(p.gamma);
}
// per pixel:
let lum = (54 * r + 183 * g + 19 * b + 128) >> 8;   // Rec. 709, weights sum to 256
*v = curve[lum as usize];

That brought the Rust version down to 0.65 ms.

Honest benchmarks

The fair comparison gives the JavaScript version the same lookup-table trick. These are averages over 200 frames, measured in Chromium on an Apple Silicon Mac:

Frame sizeRust → WASMJavaScript, same algorithm
338 × 254 (the figure)0.65 ms0.70 ms
1280 × 9608.9 ms12.6 ms

At the size the figure actually uses, they're effectively tied. WebAssembly only pulls ahead, by about 1.4×, on a frame with about fourteen times as many pixels. Modern JavaScript engines compile a tight loop over typed arrays into very good machine code.

So why use WebAssembly here?

Not because JavaScript couldn't do it. The honest reasons are:

  • Predictability. The Rust code allocates nothing per frame and has no garbage collector, and its types are fixed at compile time, so there's no risk of the engine throwing away an optimized function because a value changed type. Frame times stay steadier.
  • Headroom. At larger frames it's measurably faster, and it's the version to extend with heavier algorithms, such as the 12-tap Jarvis–Judice–Ninke kernel, colour palettes, or SIMD.
  • Testing. The dithering logic is unit tested natively with cargo test, with no browser involved.

The broader lesson is to measure before reaching for WebAssembly. It isn't automatically faster, a single missing instruction can make it slower, and for small, simple loops JavaScript is often close enough. It's worth it for large inputs, for code you already have in Rust or C++, or when you need consistent timing.

If WebAssembly isn't available, the figure falls back to the plain three.js render. The Rust source is about 360 lines, tests included.

#Discussion · 0 comments

Leave a comment

By submitting a comment, you verify that you agree to our Privacy Policy and Terms of Service.