Save Expand icon

Ron Valstar
front-end developer

Interactive fluid dynamics in JavaScript

Don’t know why, but after seeing Oliver Hunt’s fluid solver I wanted to use fluid dynamics on my site as an interactive particle flowfield.

As you might suspect fluid dynamics is really complex stuff. In computational programming it is mimicked by using Navier-Stokes equations. Olivers fluid solver is based on a 2003 paper by Jos Stam describing a fast implementation for realtime use.

The first thing I did is grab his script and implement it roughly. Only it worked wrongly for non square images. So I looked around some more for other implementations of fluid dynamics and found one in ActionScript by Eugene Zatepyakin. Since ActionScript is my second language and Eugene is an excellent programmer I decided I’d port his code to JavaScript (+Eugenes version had viscosity implemented).

When I got the port up and running it ran faster than Olivers script but it had the same vertical vs horizontal discrepancy. Luckily, while optimizing, I found out why and fixed it.

Porting stuff from C++ to Java to ActionScript to JavaScript does not go by unpunished. The Webkit browers will run it quite nicely but Firefox really sucks at it (even moreso than IE).

Here it is:

In the above implementation I’ve used the raw fluid in a canvas, and the red dots are tiny 1px divs above it. You can also watch it fullscreen from https://test.ronvalstar.nl/fluidSolver or download the source.

With it I’ve made a minimal dusty look on ronvalstar.nl (only Webkit since Firefox and IE aren’t fast enough). It uses only the velocity field for the dust particles. It starts with a low number of particles that is in- or decremented depending on the framerate. The dust particles are influenced by mouse movement, but also by interacting with the menu and/or projects.