Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using multiple canvases slower than using one?

If I'm going for fps, is it faster to use one larger canvas and redraw constantly or have a bunch of small canvases and redraw less often but use css3 for animation like this?

<canvas id="1" width="60px" height="60px"></canvas>
<canvas id="2" width="60px" height="60px"></canvas>
<canvas id="3" width="60px" height="60px"></canvas>
<canvas id="4" width="60px" height="60px"></canvas>
like image 791
nuway Avatar asked Aug 11 '12 05:08

nuway


1 Answers

In theory, one canvas would actually be faster, assuming you were to program an algorithm that only redrew what needed to be redrawn, and the redraw method happened all at once*. A redraw method can be one of the most demanding actions a browser can accomplish; the less the better.

However, the amount of code necessary to accomplish such a system probably wouldn't be worth the effort in the end. I would just stick with having multiple canvases for maintainability and extendability purposes.

Here's some other optimization tricks I've learned:

  • Clearing an entire canvas does not appear to take any more time than clearing a specific area, and can actually be faster than looping through all the objects and clearing them individually.

  • setTimeout works best for animations where seeing every frame is important. requestAnimationFrame can skip frames on less capable machines.

  • Checking to see if an element is in range before attempting to draw it can save CPU cycles, even though the canvas API does this anyway.

*To invoke a single redraw, you can set a canvas display to none, and then back to block after the context has been changed.

like image 120
Jeffrey Sweeney Avatar answered Oct 19 '22 19:10

Jeffrey Sweeney