Mark Greenwood Team : Web Development Tags : Technology Web Design Web Development

Image animation performance HTML 5 canvas vs HTML 4

Mark Greenwood Team : Web Development Tags : Technology Web Design Web Development

In a recent project I had to animate a lot of images simultaneously (up to 700) and went looking for the best solution: HTML 5 + canvas or HTML 4 + css. It wasn't that easy to find anything on canvas and I soon found out why.

It turns out that canvas really is excellent for drawing vector graphics, however... there is no native animation in canvas! When animating, every frame must be redrawn, essentially from scratch using javascript. This works well enough on canvas when drawing vector graphics, but the frame rate can take a big hit depending on the javascript engine and the programmer's approach. If you are just importing and moving images, how hard could that be for canvas? It turns out that it's very taxing on the browser. When viewing on mobile devices, it is extremely taxing. Canvas is really designed for vector graphics.

HTML 4 suffers from similar problems when it comes to javascript engine and technique, however, it looks like css is far faster moving images around the screen. It may have to do with the fact that only the elements being moved need to be re-rendered for each frame, rather than the entire graphic area.

I found this excellent, simple frame rate comparison moving 1 image on canvas versus the DOM from Phrogz (can't tell you much more about him than that)

 Moving an Image via Canvas
• Moving an Image via CSS
 Moving 20 Sprites via Canvas over a 1024x768 background
• Moving 20 Sprites via CSS over a 1024x768 background

And here are the FPS results (see URL for test details):

                  Image  Image  Sprite  Sprite
        Browser  Canvas    CSS  Canvas     CSS
--------------------------------------------------------------
  Safari v5.0.3      59     95      59      89
Firefox v3.6.13      59     95      60      90
 Firefox v4.0b8      75     89      78      82
    Chrome v8.0     108    230     120     204
    iPad, Horiz      17     44       2      14
     iPad, Vert       4     75       2      15

As you can see, you're always going to get better results moving an image as a DOM element than redrawing the canvas.

The single most helpful information I could find on the internet is here at stackoverflow.com. You'll find links to the frame rate tests here too.