Canvas tile drawing

JavaScript performance comparison

Test case created by Oneway

Info

Rendering tests for clipping tiles from a tileset image to a screen in order to create a performant level editor for a 2d tile based platformer.

Preparation code

<canvas id="cv">
</canvas>
<img src="http://www.steven-attevelt.nl/base.png">
<script>
  // Prep tiles and canvas vars
  var imgObj = new Image();
  imgObj.src = 'http://www.steven-attevelt.nl/base.png';
  var tiles = [{
    s: 0,
    lx: 1,
    ly: 1,
    tx: 2,
    ty: 13
  }, {
    s: 0,
    lx: 1,
    ly: 2,
    tx: 1,
    ty: 14
  }, {
    s: 0,
    lx: 1,
    ly: 3,
    tx: 1,
    ty: 0
  }, {
    s: 0,
    lx: 2,
    ly: 2,
    tx: 7,
    ty: 0
  }];
  var tilesize = 32;
  var c = document.getElementById('cv');
  c.width = 512;
  c.height = 512;
  var cc = c.getContext('2d');


  // Prep for test 3
  var tileCanvases = [];
  for (var i = 0; i < tiles.length; i++) {
    var tc = document.createElement('canvas');
    tc.width = tilesize;
    tc.height = tilesize;
    var tcc = tc.getContext('2d');
    var tile = tiles[i];
    tcc.drawImage(
    imgObj, tile.tx * tilesize, tile.ty * tilesize, tilesize, tilesize, 0, 0, tilesize, tilesize);
    tileCanvases[i] = tc;
  }
</script>

Preparation code output

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
clip from image to screen canvas
cc.clearRect(0, 0, 512, 512);
for (var i = 0; i < tiles.length; i++) {
  var tile = tiles[i];
  cc.drawImage(
  imgObj, tile.tx * tilesize, tile.ty * tilesize, tilesize, tilesize, tile.lx * tilesize, tile.ly * tilesize, tilesize, tilesize);
};
pending…
clip from image to intermediate canvas
var c2 = document.createElement('canvas');
c2.width = 32;
c2.height = 32;
var cc2 = c2.getContext('2d');
for (var i = 0; i < tiles.length; i++) {
  var tile = tiles[i];
  cc2.clearRect(0, 0, tilesize, tilesize);
  cc2.drawImage(
  imgObj, tile.tx * tilesize, tile.ty * tilesize, tilesize, tilesize, 0, 0, tilesize, tilesize);
  cc.clearRect(tile.lx * tilesize, tile.ly * tilesize, tilesize, tilesize);
  cc.drawImage(c2, tile.lx * tilesize, tile.ly * tilesize);
}
pending…
tiles prerendered in seperate canvases
for (var i = 0; i < tiles.length; i++) {
  var tile = tiles[i];
  cc.clearRect(tile.lx, tile.ly, tilesize, tilesize);
  cc.drawImage(
  tileCanvases[i], tile.lx * tilesize, tile.ly * tilesize, tilesize, tilesize);
};
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment