CSS Sprites vs. HTML5 Canvas (v4)

Revision 4 of this benchmark created on


Description

Compare which is the better alternative, use a div element with a shifting background, or an Image object drawed upon a canvas element.

Preparation HTML

<div id="d1" style="width: 130px; height: 130px;">
</div>
<canvas id="c1" width="130" height="130">
</canvas>
<script>
  var width = 130;
  var height = 130;
  var spriteStartWidth = 130 * 9;
  var offset = 0;
  var imgUrl = "http://dl.dropbox.com/u/6948808/test.jpg";
  
  //var d = document.createElement("div");
  var d = document.getElementById("d1");
  //d.style.cssText = "width:" + width + "px; height:" + height + "px";
  d.style.backgroundImage = "url(" + imgUrl + ")";
  
  
  
  
  //var c = document.createElement("canvas");
  var c = document.getElementById("c1");
  c.width = width;
  c.height = height;
  
  
  var imgSprite = new Image(width, height);
  imgSprite.src = imgUrl;
  
  var ctx = c.getContext('2d');
  // when image has loaded, draw on canvas elements
  imgSprite.onload = function() {
    ctx.drawImage(imgSprite, offset, 0, width, height, 0, 0, width, height);
  };
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
CSS Sprite offset
d.style.backgroundPosition = "-" + offset + "px";
d.style.top= "-" + offset + "px";
d.style.left= "-" + offset + "px";

offset += width;
if (offset > spriteStartWidth) {
  offset = 0;
}
ready
Canvas offset
offset += width;
if (offset > spriteStartWidth) {
  offset = 0;
}

ctx.drawImage(imgSprite, offset, 0, width, height, 0, 0, width, height);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.