HTML5 Canvas Pixel (v27)

Revision 27 of this benchmark created on


Description

Testing 'reasonable' methods to set one pixel on an HTML5 Canvas; used to support this Stack Overflow question.

Preparation HTML

<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 = [];
// test
var canvasWidth  = c.width;
var canvasHeight = c.height;
var imageData = $ctx.getImageData(0, 0, canvasWidth, canvasHeight);
var data = imageData.data;
  // 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>

Test runner

Ready to run.

Testing in
TestOps/sec
fillRect
var px = $pxls[$i++ % 10000];
for (var h = 0; h < 1000; ++h) {
  $ctx.fillStyle = 'rgba(' + px.r + ',' + px.g + ',' + px.b + ',' + (px.a / 255) + ')';
  $ctx.fillRect(px.x, px.y, 1, 1);
}
ready
1x1 ImageData
var px = $pxls[$i++ % 10000];
var d = $px.data;
for (var h = 0; h < 1000; ++h) {
  d[h] = px.r;
  d[h] = px.g;
  d[h] = px.b;
  d[h] = px.a;
  $ctx.putImageData($px, px.x, px.y);
}
ready
test
var px = $pxls[$i++ % 10000];
var d = $px.data;
for (var h = 0; h < 1000; ++h) {
  d[h] = px.r;
  d[h] = px.g;
  d[h] = px.b;
  d[h] = px.a;
 
} 
$ctx.putImageData($px, px.x, px.y);
ready
test2
var px = $pxls[$i++ % 10000];
for (var h = 0; h < 1000; ++h) {
  data[h] = px.r;
  data[h] = px.g;
  data[h] = px.b;
  data[h] = px.a;
}
$ctx.putImageData(imageData, 0, 0);
ready

Revisions

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