Skip to content
Advertisement

Increase performance for 10,000 particles in HTML5 Canvas

I have two JS Fiddles, both with 10,000 snow flakes moving around but with two different approaches.

The first fiddle: http://jsfiddle.net/6eypdhjp/

Uses fillRect with a 4 by 4 white square, providing roughly 60 frames per second @ 10,000 snow flakes.

So I wondered if I could improve this and found a bit of information on HTML5Rocks’ website regarding canvas performance. One such suggestion was to pre-render the snow flakes to canvases and then draw the canvases using drawImage.

The suggestion is here http://www.html5rocks.com/en/tutorials/canvas/performance/, namely under the title Pre-render to an off-screen canvas. Use Ctrl + f to find that section.

So I tried their suggestion with this fiddle: http://jsfiddle.net/r973sr7c/

How ever, I get about 3 frames per second @ 10,000 snow flakes. Which is very odd given jsPerf even shows a performance boost here using the same method http://jsperf.com/render-vs-prerender

The code I used for pre-rendering is here:

JavaScript

So I wondered why am I getting such horrendous frame rate? And is there any better way to get higher particle counts moving on screen whilst maintaining 60 frames per second?

Advertisement

Answer

Best frame rates are achieved by drawing pre-rendered images (or pre-rendered canvases).

You could refactor your code to:

  • Create about 2-3 offscreen (in-memory) canvases each with 1/3 of your particles drawn on them
  • Assign each canvas a fallrate and a driftrate.
  • In each animation frame, draw each offscreen canvas (with an offset according to its own fallrate & driftrate) onto the on-screen canvas.

The result should be about 60 frames-per-second.

This technique trades increased memory usage to achieve maximum frame rates.

Here’s example code and a Demo:

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement