Particle simulation in JavaScript

The goal of this project is to squeeze every last drop of performance to run particle simulation at 60 fps without using WebGL. Simulation Source code

Disclaimer: I’m not a javascript expert, some things might be wrong.

Basic particle information

Storing particles

To store particle information I used one dimensional array. (JSPerf)For every particle we need to store: Position, Velocity, ‘Home’ position and damping ratio. In one dimensional array it will look like this:

[ x, y, velX, velY, homeX, homeY, daming, x, y, velX, velY ... ]

So every particle needs seven numbers.

Updating position

It’s pretty straightforward. Every frame it updates particle position using simple math and vectors.

Drawing

To draw particles we have two ways: using fillRect function or directly writing image data pixel by pixel. Last one is much better if we have a lot of objects to draw. There is a nice article on MDN: Pixel manipulation.

Performance tips and tricks

Detaching data array from imageData increases performance.

If you have big loops use var or declare i out of the loop. JSPerf

I used ~~ instead of Math.floor for rounding down. JSPerf

Checking if number is in range using binary operations instead of two comparisons if slightly faster and more compact (but looks confusing). JSPerf

Minimise calculations inside the loop

Use profiler in DevTools to see what steals your precious milliseconds.

Thanks for reading.

Show your support

Clapping shows how much you appreciated Alex’s story.