HTML5 Canvas: better to re-draw objects or use bitmaps?

travelboy picture travelboy · Oct 6, 2011 · Viewed 12.3k times · Source

My project has an HTML5 Canvas on which graphical objects are drawn repeatedly. These objects change rapidly. Drawing them takes time. How can I make it faster?

The objects are not overly complex but contain things like arcs, gradients, polygons.

The look of an object depends on about 10 properties which each have one of about 10 values. That means that there are only about 100 different appearances than an object can have. That's why I'm thinking about only drawing each appearance once and then caching a bitmap for re-use.

Everything must work on the client (i.e. I cannot use ready-made images)

  1. What would be the best way to do this with HTML5 Canvas?
  2. Is it a good idea at all or is the overhead of working with bitmaps greater than re-drawing the objects every time?

Answer

Loktar picture Loktar · Oct 6, 2011

Cache cache cache! Check out this article by Simon Sarris, and my own findings. Basically you make a canvas in memory copy the contents there and you can reuse them. You will see huge performance increases doing this.

Rotating sprites without caching

Rotating sprites WITH caching (walk upwards to find the zombies)

You should see a pretty big improvement in the 2nd example.

EDIT

jsfiddle example cached

jsfiddle example not cached

Simon posted this in the comments, which should really clear things up if you can't see the performance gains by just looking at the demos.

JSperf findings by Simon Sarris