Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A hundred contexts vs one context in HTML5 Canvas?

I'm creating a simple physics engine working with the Canvas API. What is the best practice in terms of performance? Is it to create a separate context for ever object in the canvas (ex. for every ball, box etc..), or to use just one context? The latter involves defining the path on the context for every object to be redrawn, plus setting the color etc..

Is it a bad idea to use multiple contexts when the number of objects get near a hundred?

The reason why I ask, is because I don't want to get a surprise a hundred working hours later because I went with the wrong way of doing this.

like image 207
Friend of Kim Avatar asked Sep 08 '13 09:09

Friend of Kim


Video Answer


1 Answers

Performance gains with multiple canvas’s comes from knowing why you use multiple canvases.

Don’t use multiple canvases unless they serve a useful purpose:

  • Canvases are modestly expensive elements.
  • On mobile, canvases are still quite slow—-multiple canvases are slower.

Here are some reasons to use more than 1 canvas:

You have drawings that animate at different times.

For example, a background might animate every 5 frames while your more active objects might animate every frame. Having the background on a second canvas means you don’t have to draw the background every animation frame.

You want to “double buffer” to increase display speed.

For example, while the current frame is being displayed, you might use a second canvas to assemble a complex element and then use displayContext.drawImage(bufferCanvas,0,0) to draw the buffer canvas on the display canvas. This lets you use the “downtime” between animation frames to ready your next frame.

You use canvas to make variations on a single image/drawnElement (templating).

For example, if you need a physical barrier (say an image of a gray building). You might desire red, blue and green buildings for variety. You could have the gray building image on an offscreen canvas and use context’s globalCompositeOperation to recolor that one building into red,blue and green variations. This lets you reuse 1 image resource in multiple ways.

There are other reasons for multiple canvases, but the point is to use multiple canvases to fill a need.

like image 93
markE Avatar answered Oct 05 '22 23:10

markE