Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiency of <canvas> and <div>s

I want to ask if someone can give me some hints with a design decision I want to make.

My project will feature some sprites (expecting 10 to 30 on the screen at once), and there are several ways to implement them. One way would be CSS-Sprites, another is drawing them on a canvas. Both are not difficult. The background will be a tile-map drawn by another <canvas>, in the background.

I've seen that Crafty attaches Sprites as <div> that is in the HTML within the <canvas>, as a CSS-Sprite. I am not sure if there's a speed difference if the <div> is in the canvas or not. Is there a difference?

I expect the user to interact with the sprites, by mouse clicks, left, right, etc. And the sprites are of course standing or walking on elements of the tile map. So is it more efficient to write a handler for the <canvas> and find the sprite, or rather using the <div> and let the browser handle the finding?

I hope I could communicate my problem.

like image 861
Lanbo Avatar asked Nov 04 '11 12:11

Lanbo


1 Answers

My tests show that pure HTML + CSS is generally faster for sprites than Canvas:
Performance of moving image on web page via CSS vs HTML5 Canvas

See the tests and results (from browsers 10 months ago) here:
http://phrogz.net/tmp/image_move_speed.html

Specifically, I have two tests almost exactly the same as your question:

  • 20 animated sprites using CSS
  • 20 animated sprites using Canvas

Summarized FPS:

                  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

More recent browsers are generally much faster (Chrome almost always hits a 250fps internal cap on the same machine) and close the gap more, but using Canvas is still slower and far more work.

like image 79
Phrogz Avatar answered Nov 15 '22 21:11

Phrogz