Setting one HTML5 Canvas Pixel

JavaScript performance comparison

Test case created by Phrogz

Preparation code

<p>(Scroll down to see the 'Run Tests' button.)</p>
<canvas id="c" width="800" height="300"></canvas>
<script>
  $c = document.getElementById('c');
  $ctx = $c.getContext('2d');
  $ctx.clearRect(0, 0, 800, 300);
  $px = $ctx.createImageData(1, 1);
  $pxls = [];
  // Precompute random pixels so this time isn't included in the tests
  for (var i = 0; i < 10000; ++i) $pxls.push({
   x: Math.random() * 800 << 0,
   y: Math.random() * 300 << 0,
   r: Math.random() * 255 << 0,
   g: Math.random() * 255 << 0,
   b: Math.random() * 255 << 0,
   a: Math.random() * 128 << 0 + 128
  });
  $i = 0;
</script>
    

Preparation code output

<p>(Scroll down to see the 'Run Tests' button.)</p> <canvas id="c" width="800" height="300"></canvas>

Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
get/putImageData
var px = $pxls[$i++ % 10000];
var idata = $ctx.getImageData(0, 0, 800, 300);
var d = idata.data;
var o = (px.y * 800 + px.x) * 4;
d[o] = px.r;
d[o + 1] = px.g;
d[o + 2] = px.b;
d[o + 3] = px.a;
$ctx.putImageData(idata, 0, 0);
pending…
fillRect
var px = $pxls[$i++ % 10000];
$ctx.fillStyle = 'rgba(' + px.r + ',' + px.g + ',' + px.b + ',' + (px.a / 255) + ')';
$ctx.fillRect(px.x, px.y, 1, 1);
pending…
1x1 image data
var px = $pxls[$i++ % 10000];
var d = $px.data;
d[0] = px.r;
d[1] = px.g;
d[2] = px.b;
d[3] = px.a;
$ctx.putImageData($px, px.x, px.y);
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.

4 Comments

Phrogz (revision owner) commented :

I have filed a bug on the performance of the 1x1 putImageData() in FF 4.0b relative to 3.6 and relative to fillRect.

dira commented :

Thanks for this great investigation! It helped us optimize canvas rendering for http://tzigla.com

We noticed that in FF 4.0b11 setting the pixels directly through the getImageData().data array is way faster than all the alternative methods above.

dira commented :

Thanks for this great investigation! It helped us optimize canvas rendering for http://tzigla.com

We noticed that in FF 4.0b11 setting the pixels directly through the getImageData().data array is way faster than all the alternative methods above.

Rikard commented :

Thank you for this, very helpful.

(Scroll down to see the 'Run Tests' button.)