HTML5 Canvas: better to re-draw objects or use bitmaps?
My project has an HTML5 Canv开发者_StackOverflowas 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)
- What would be the best way to do this with HTML5 Canvas?
- Is it a good idea at all or is the overhead of working with bitmaps greater than re-drawing the objects every time?
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
Depending on how many objects could change in a second, and consequentially how many objects you have to redraw and how - within the same second, redrawing more than caching could be quite an option.
On a general basis I would suggest to consider the following decisional path.
You mentioned that there can be 100 different ways for one of your objects to appear.
This could be considered similar to a minimum of 99^2 theoretically possible status transitions for each of your objects.
Are these status transitions dramatic in shape / size / color, but they're still well-identified, marked and manageable? If so, caching just once 100 different appearances to be used by all of your objects could be a significant performance improvement.
Conversely, if - just for example - the background hardly changes and the drawn part occupies a less relevant part of the object area you could seriously consider redrawing it every time.
In fact, a pre-rendered image could not fit your needs for performance if your drawn object changes dynamically and especially on a continuous basis, as a pre-rendered image needs to be drawn completely at every state transition while redrawing the object could mean less computational load.
精彩评论