Interactive HTML5 Canvas Fluid & Smoke Simulation: Navier-Stokes Physics & WebGL Velocity Grids

The Quick Answer

Real-time 2D fluid simulation on HTML5 Canvas relies on a discretized Eulerian grid approximating the incompressible Navier-Stokes equations: advection, diffusion, and pressure Poisson projection. By coupling mouse or touch velocity vectors into a low-resolution velocity grid (e.g. 64x64 or 128x128) and upsampling with bilinear interpolation, you achieve silky 60fps fluid swirl dynamics with minimal CPU overhead.

Interactive Demo Live Preview
👆 Drag or move cursor to swirl multi-color fluid

Step 1: Discretizing the Fluid Velocity Grid

Simulating full 3D fluid dynamics in JavaScript is computationally prohibitive. Instead, we use an Eulerian grid where the screen is divided into a low-resolution grid of velocity vectors (u for horizontal, v for vertical) and density scalar values. The Navier-Stokes equation governing this is ∂u/∂t = -(u·∇)u - (1/ρ)∇p + ν∇²u + f.

fluid-grid.js
class FluidGrid {
  constructor(size, diffusion, viscosity, dt) {
    this.size = size;
    this.dt = dt;
    this.diff = diffusion;
    this.visc = viscosity;
    const numCells = (size + 2) * (size + 2);
    this.u = new Float32Array(numCells); // horizontal velocity
    this.v = new Float32Array(numCells); // vertical velocity
    this.u_prev = new Float32Array(numCells);
    this.v_prev = new Float32Array(numCells);
    this.density = new Float32Array(numCells);
    this.density_prev = new Float32Array(numCells);
  }

  addDensity(x, y, amount) {
    const idx = x + (this.size + 2) * y;
    this.density[idx] += amount;
  }

  addVelocity(x, y, amountX, amountY) {
    const idx = x + (this.size + 2) * y;
    this.u[idx] += amountX;
    this.v[idx] += amountY;
  }
}

Step 2: Advection and Gauss-Seidel Relaxation

Fluid velocity must be advected forward in time while enforcing incompressibility (divergence = 0). We solve the Poisson pressure equation using an iterative Gauss-Seidel relaxation loop (typically 12–20 iterations) to subtract velocity divergence at boundaries.

fluid-solver.js
function project(size, u, v, p, div) {
  const n = size;
  for (let j = 1; j <= n; j++) {
    for (let i = 1; i <= n; i++) {
      div[i + (n + 2) * j] = -0.5 * (
        u[(i + 1) + (n + 2) * j] - u[(i - 1) + (n + 2) * j] +
        v[i + (n + 2) * (j + 1)] - v[i + (n + 2) * (j - 1)]
      ) / n;
      p[i + (n + 2) * j] = 0;
    }
  }
  setBnd(n, 0, div); setBnd(n, 0, p);

  // 16 Gauss-Seidel iterations for pressure relaxation
  for (let k = 0; k < 16; k++) {
    for (let j = 1; j <= n; j++) {
      for (let i = 1; i <= n; i++) {
        p[i + (n + 2) * j] = (div[i + (n + 2) * j] +
          p[(i - 1) + (n + 2) * j] + p[(i + 1) + (n + 2) * j] +
          p[i + (n + 2) * (j - 1)] + p[i + (n + 2) * (j + 1)]) / 4;
      }
    }
    setBnd(n, 0, p);
  }
}

Step 3: Coupling Cursor Motion & Multi-Color Splats

When the visitor drags their cursor or swipes across mobile screens, calculate velocity deltas (dx = clientX - prevX, dy = clientY - prevY). Inject density and velocity into the fluid grid at the normalized coordinates, applying high-chroma OKLCH color cycling.

mouse-interaction.js
window.addEventListener('pointermove', (e) => {
  const rect = canvas.getBoundingClientRect();
  const x = Math.floor(((e.clientX - rect.left) / rect.width) * GRID_SIZE);
  const y = Math.floor(((e.clientY - rect.top) / rect.height) * GRID_SIZE);
  const dx = e.movementX * 3.5;
  const dy = e.movementY * 3.5;

  if (x >= 1 && x <= GRID_SIZE && y >= 1 && y <= GRID_SIZE) {
    fluid.addVelocity(x, y, dx, dy);
    fluid.addDensity(x, y, 220); // inject ink pigment
  }
});

Next-Level Addons: Elevating Your Implementation

Take this technique further by combining it with complementary design token studios and animation tools:

NAVIER-STOKES INK DYNAMICS

1. Viscous Neon Swirls with OKLCH Gamut

Explore in Mesh Gradient Studio →

Simulate high-viscosity fluid ribbons by tuning diffusion decay constants and mapping velocity magnitude to vibrant P3 and Rec.2020 color palettes.

Cooling Factor: 0.985 · 60 FPS

2. Thermal Dissipation & Smoke Fade Out

Explore in Noise & Grain Studio →

Add natural atmospheric dissipation by decaying density arrays by a cooling factor (e.g. 0.985 per frame) and blending soft procedural film noise.

FBO Ping-Pong 0ms Main Thread

3. Mobile Performance & WebGL Shaders

Explore in Particle Background Studio →

For low-power mobile devices, offload the Jacobi pressure solver directly into fragment shaders via double-buffered WebGL framebuffers (FBOs).

Chaam
Chaam's Pro Tip

Whenever I design responsive widgets or fluid typography, I rely heavily on clamp() and container queries (@container). Testing down to 320px viewport widths in Chrome DevTools will instantly reveal edge cases before your users see them.

Why I Built the Particle Background Studio

I got tired of guessing values and testing browser quirks in DevTools, so I built this tool to tweak and preview values in real time with 1-click code export.

Open in Particle Background Studio ↗

Frequently Asked Questions

Practical answers to common implementation questions, browser quirks, and performance tips.

How computationally expensive is fluid simulation on mobile browsers?

A 2D Eulerian CPU grid at 64x64 resolution consumes less than 3ms per frame on modern smartphones. On mobile, decrease the grid resolution to 48x48 and reduce Gauss-Seidel iterations from 20 to 10 for buttery 60fps performance without thermal throttling.

Can Navier-Stokes fluid simulations run in pure CSS without JavaScript?

No. While CSS gradients and SVG filters can simulate liquid morphing (such as metaball gooey effects with feColorMatrix), real fluid equations require numerical matrix calculations (advection, pressure projection) that require JavaScript Canvas or WebGL shaders.

How do you prevent fluid animations from draining battery on idle tabs?

Use the Page Visibility API (document.visibilityState). Pause the requestAnimationFrame loop when the browser tab is hidden and suspend pointer listeners when idle for more than 10 seconds.

How do you make fluid backgrounds responsive on high-DPI retina screens?

Decouple simulation grid resolution from canvas render resolution. Run the Navier-Stokes physics on a fixed 128x128 grid, then upscale to the canvas with context.imageSmoothingEnabled = true.

What is the best way to handle touch events on mobile devices for fluid inputs?

Use standard Pointer Events (pointerdown, pointermove, pointerup) with touch-action: none set on the canvas container. This prevents default mobile scrolling gestures while tracking touch coordinates accurately.

← Back to all blog guides Launch Generator Studio →