outwest.dev

ExperimentCanvasPerformanceVue

Stable fluids in 150 lines

· 13 min read

A while back I wrote about building a random walk on canvas. It was a fun couple of nights, but the whole time I kept thinking the little walker would look a lot better if it were dragging something behind it. Something that swirled. So for the 2027 refresh of this site I went back to it, and the walker now drives an ink simulation in the hero on the home page.

The goals were pretty simple:

  • It should feel physical. Ink should curl and push back, not just smear.
  • It should run on about a laptop fan's worth of CPU.
  • No dependencies. No WebGL, no libraries, just a 2D canvas.

The approach is Jos Stam's Stable Fluids from SIGGRAPH 1999. Not counting comments and blank lines, the solver is 115 lines, and the per-frame update() and render() functions add 37 more. That's where the 150 comes from.


Grid
stable fluids · 128×40 grid · ink seeded by a random walkmove through it →

The Grid

Everything lives on a grid of cells, 128 wide by 40 tall by default. Each cell has a horizontal and vertical velocity, plus a value for each dye: walker for the green ink the random walker leaves and pointer for the orange ink you stir in with your mouse. The grid also gets a one-cell border on every side, which we use to handle the walls.

Rather than nested arrays, every field is a flat Float32Array:

const rowSize = width + 2               // one border cell on each side
const cellCount = rowSize * (height + 2)
const createField = () => new Float32Array(cellCount)

const velocityX = createField(), velocityY = createField()
const prevVelocityX = createField(), prevVelocityY = createField()
const pressure = createField(), divergence = createField()

const index = (x, y) => x + rowSize * y

If this index helper looks familiar, it's the same trick from the random walk post where we turned 2D coordinates into an index in a 1D array. Multiply y by the row size to get to the start of the row, then add x. No * 4 this time since each field holds a single number per cell.

There are a couple of nice wins with flat typed arrays. The memory is contiguous, so walking the grid row by row is about as cache friendly as JavaScript gets. And copying a whole field is one call: prevVelocityX.set(velocityX) copies all ~5,000 cells without allocating anything. We do that every frame, so it adds up.

The dyes are created from whatever you pass in, along with how fast each one fades:

dyes: dyeDecay = { walker: 0.994, pointer: 0.988 }, // dye name -> fade per step

So if you wanted a third color, you'd add a name here and a color in the renderer. The solver doesn't care.

The walls

The border cells get filled in after every pass by setBoundaries(). For dye and pressure it just copies the neighbor, so nothing leaks out. For velocity it mirrors the value at the wall it's moving into, so the fluid bounces back instead of flowing off the edge:

const SCALAR = 0      // copy the neighbour (dye, pressure)
const VELOCITY_X = 1  // mirror at the left and right walls
const VELOCITY_Y = 2  // mirror at the top and bottom walls

Stam's original code passes a bare 0, 1 or 2 here. Naming them made the rest of the solver a lot easier to read.

Three Steps Per Frame

The whole simulation boils down to three steps that run every frame.

1. Add forces

splat() drops a soft blob of velocity and dye into the grid at a point. The blob is a small Gaussian, so it's strongest in the middle and fades out toward the edges:

function splat(x, y, forceX, forceY, dyeName, amount = 0.5, radius = 3) {
  const dye = dyes[dyeName]
  const spread = (radius * radius) / 2.25
  for (let offsetY = -radius; offsetY <= radius; offsetY++) {
    for (let offsetX = -radius; offsetX <= radius; offsetX++) {
      const cellX = Math.round(x) + offsetX, cellY = Math.round(y) + offsetY
      if (cellX < 1 || cellY < 1 || cellX > width || cellY > height) continue
      const weight = Math.exp(-(offsetX * offsetX + offsetY * offsetY) / spread)
      const cell = index(cellX, cellY)
      velocityX[cell] += forceX * weight
      velocityY[cell] += forceY * weight
      dye[cell] = Math.min(1.4, dye[cell] + amount * weight)
    }
  }
}

Dye is capped at 1.4 rather than 1 so the center of a fresh splat stays fully saturated for a few frames before it starts fading. It gets clamped back to 0..1 when we read it for drawing.

2. Advect

Advection is how the fluid carries stuff around, including its own velocity. The naive approach is to take each cell and push its contents forward along the velocity. The problem is that forward pushing blows up with big time steps, and things land between cells.

Stam's trick is to go backwards. For every cell, ask "where did the stuff that's here now come from?" Trace back along the velocity, land somewhere between four cells, and blend them with bilinear interpolation:

const fromX = Math.max(0.5, Math.min(width + 0.5, x - dt * prevVelocityX[cell]))
const fromY = Math.max(0.5, Math.min(height + 0.5, y - dt * prevVelocityY[cell]))
const left = Math.floor(fromX), top = Math.floor(fromY)
const right = fromX - left, bottom = fromY - top
target[cell] =
  (1 - right) * ((1 - bottom) * source[index(left, top)] + bottom * source[index(left, top + 1)]) +
  right * ((1 - bottom) * source[index(left + 1, top)] + bottom * source[index(left + 1, top + 1)])

left and top are the cell we landed in, and right and bottom are how far we are toward the next cell over and the next cell down. So (1 - right) is how much the left column counts, right is how much the right column counts, and the same goes for top and bottom.

Because we only ever blend values that already exist, the result can never grow beyond what was there. That's what makes it unconditionally stable, which is the whole point of the paper. You can crank the velocity way up and it'll look chaotic, but it won't explode into NaN.

3. Project

This is the step that took me a minute to wrap my head around, and it's also the one that makes the whole thing look like fluid.

After adding forces and advecting, the velocity field is a mess. Some cells have more flowing in than out, which isn't how water works. Real fluid is incompressible. Push on it in one spot and it has to go somewhere, which is exactly where the swirls come from.

project() fixes this in three passes:

  1. Measure the divergence of every cell, meaning how much more is flowing out than in.
  2. Solve for a pressure field that would cancel that out. This is a Poisson equation, and we solve it with 16 iterations of Gauss-Seidel, where each cell repeatedly becomes the average of its neighbors plus its divergence.
  3. Subtract the pressure gradient from the velocity.
for (let n = 0; n < iterations; n++) {
  for (let y = 1; y <= height; y++) {
    for (let x = 1; x <= width; x++) {
      const cell = index(x, y)
      const neighbours = pressure[cell - 1] + pressure[cell + 1] + pressure[cell - rowSize] + pressure[cell + rowSize]
      pressure[cell] = (divergence[cell] + neighbours) / 4
    }
  }
  setBoundaries(SCALAR, pressure)
}

A nice side effect of the flat arrays: cell - 1 and cell + 1 are the cells to the left and right, and cell - rowSize and cell + rowSize are the cells above and below. No need to call index() four times.

Notice that pressure is updated in place. Each cell reads neighbors that were already updated earlier in the same pass, and that's what makes it Gauss-Seidel instead of the slower Jacobi method. Sixteen iterations isn't enough to fully converge, but it's plenty for something that only has to look right.

Without this step you get ink that drifts and smears. With it you get curls. If you want to see the difference, comment out both project() calls in step() and watch the ink lose all of its curls.

Putting it together

Here's the full step:

function step(dt = 1 / 60) {
  project()
  prevVelocityX.set(velocityX); prevVelocityY.set(velocityY)
  advect(VELOCITY_X, velocityX, prevVelocityX, dt)
  advect(VELOCITY_Y, velocityY, prevVelocityY, dt)
  project()
  prevVelocityX.set(velocityX); prevVelocityY.set(velocityY)
  for (const name of dyeNames) {
    prevDye.set(dyes[name])
    advect(SCALAR, dyes[name], prevDye, dt)
    for (let cell = 0; cell < cellCount; cell++) dyes[name][cell] *= dyeDecay[name]
  }
  for (let cell = 0; cell < cellCount; cell++) {
    velocityX[cell] *= velocityDecay
    velocityY[cell] *= velocityDecay
  }
}

We project once before advecting the velocity and once after, so the field that moves the dye is always divergence free. Then each dye rides along on it and fades a little.

If you've read Stam's paper you'll notice I skipped the diffusion step entirely. That's on purpose. Bilinear sampling already blurs things a little every frame, and the decay multipliers slowly fade everything out. Together they get close enough to viscosity that a separate diffusion solve wasn't worth the extra CPU. The orange decays a bit faster than the green (0.988 vs 0.994) so your trail fades before the walker's does.

Rendering Cheaply

The grid is only 128×40, but the canvas is a lot bigger than that. Instead of drawing big rectangles per cell, we write the dye straight into an ImageData the same size as the grid, put it on a small offscreen canvas, and then let the browser scale it up:

gridContext.putImageData(image, 0, 0)
context.imageSmoothingEnabled = true
context.imageSmoothingQuality = 'high'
context.drawImage(gridCanvas, 0, 0, canvas.value.width, canvas.value.height)

The browser's smoothing when it upscales is what gives the ink that soft look. We're getting the nice part for free, which is my favorite kind of free.

Each pixel is a blend of three colors. Wherever neither dye is covering the cell, the ground color shows through:

const walkerInk = fluid.sample('walker', x, y)
const pointerInk = fluid.sample('pointer', x, y)
const bare = Math.max(0, 1 - walkerInk - pointerInk)
const offset = (x + width * y) * 4
for (let channel = 0; channel < 3; channel++) {
  pixels[offset + channel] =
    groundRgb[channel] * bare + walkerRgb[channel] * walkerInk + pointerRgb[channel] * pointerInk
}
pixels[offset + 3] = 255

Same RGBA rules as last time: the data is a Uint8ClampedArray, so offset jumps four values per pixel, and anything over 255 just gets clamped so we don't have to worry about it.

Making It Polite

A hero animation that pins a CPU core while you're reading a post three screens down is not polite. So the component does a few things to stay out of the way:

  • Pause when nobody is looking. An IntersectionObserver tracks whether the canvas is on screen, and document.hidden covers background tabs. When either is false the loop keeps scheduling frames but skips the work.
  • Respect reduced motion. If prefers-reduced-motion is set, we run SETTLE_STEPS (300) updates up front, draw one still frame, and never start the loop. You still get the picture, it just doesn't move.
  • Don't break scrolling on phones. touch-action: pan-y lets vertical swipes scroll the page instead of getting swallowed by the canvas.
  • Stay SSR safe. All the canvas work happens in onMounted, so Nuxt can render the page on the server without needing <ClientOnly>.

I also kept the solver completely free of Vue and the DOM. lib/stableFluids.js just takes numbers in and gives numbers back. The FluidCanvas component owns the canvas, the input and the lifecycle, and that's it. It's the same humble component idea I keep coming back to: the logic can be tested and reused on its own, and the component stays small and boring.

Interaction

There are two sources of ink.

The random walker from the old post is still in there. Every frame it nudges its heading a little, steps forward, and splats green ink in the direction it's facing:

const drift = (Math.random() - 0.5) * 0.5
const pullToCenter = (walker.y - height / 2) * 0.004
walker.heading += drift - pullToCenter
walker.x += Math.cos(walker.heading) * WALKER_SPEED
walker.y += Math.sin(walker.heading) * WALKER_SPEED

drift is the random part, and pullToCenter gets stronger the further the walker strays from the middle so it doesn't hug the edges. Once it walks off the right side it respawns on the left. It keeps the whole thing alive when nobody is touching it.

The pointer is the second source. On pointermove we convert the position into grid coordinates and remember how far it moved since the last event:

pointer = {
  x, y,
  deltaX: pointer ? x - pointer.x : 0,
  deltaY: pointer ? y - pointer.y : 0,
  isFresh: true,
}

On the next update that delta gets multiplied by POINTER_FORCE and becomes velocity, so a fast flick throws the ink harder than a slow drag. The isFresh flag makes sure we only splat once per move event, otherwise holding the mouse still would keep pumping ink into the same spot.

Numbers

I benchmarked step() on its own in Node 20 on an Apple M1, averaged over 2,000 steps:

GridCellsTime per step
64×201,280~0.5ms
128×405,120~2.1ms
192×6011,520~4.8ms
256×8020,480~8.4ms

The cost scales pretty much linearly with the cell count, which makes sense since every step is a handful of passes over the grid. At the default 128×40 the solver uses roughly 2ms of a 16.7ms frame, which leaves plenty of room for the render and everything else on the page. Somewhere past 256×80 you start eating into the frame budget on a fast machine, and a lot sooner on a slow phone. Try the grid sizes in the demo above and you can feel it.

Where To Go Next

The obvious next step is WebGL. The same three steps map really nicely onto fragment shaders, one pass each, and you can run them at full screen resolution instead of a tiny grid. That's also where you'd add vorticity confinement, which puts back some of the small swirls that the semi-Lagrangian advection smooths away.

But for a hero on a personal blog, a 2D canvas and 150 lines turned out to be plenty.

Conclusion

This was one of those projects where the math looked scarier than it was. Once I understood that every frame is just add forces, advect and project, the whole thing clicked. And the "go backwards" trick in advection is one of those ideas that's so simple you wonder why nobody thought of it sooner.