Setting one HTML5 Canvas Pixel (v24)

Revision 24 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="480" height="480"></canvas>
<script>
  $c = document.getElementById('c');
  $ctx = $c.getContext('2d');
  $ctx.clearRect(0, 0, 480, 480);
  $buf = $ctx.getImageData(0, 0, 480, 480);
  $scale = 4;
  $px = [
    $ctx.createImageData($scale, $scale),
    $ctx.createImageData($scale, $scale),
    $ctx.createImageData($scale, $scale),
    $ctx.createImageData($scale, $scale)
  ];
  for (var i = 0, ilen = $px.length; i < ilen; i++) {
    var d = $px[i].data;
    for (var j = 0, jlen = d.length; j < jlen; j+=4) {
      d[j+0] = 64 * i + 63;
      d[j+1] = 64 * i + 63;
      d[j+2] = 64 * i + 63;
      d[j+3] = 255;
    }
  }

  $fs = [
    'rgba('+(64*0+63)+','+(64*0+63)+','+(64*0+63)+',255)',
    'rgba('+(64*1+63)+','+(64*1+63)+','+(64*1+63)+',255)',
    'rgba('+(64*2+63)+','+(64*2+63)+','+(64*2+63)+',255)',
    'rgba('+(64*3+63)+','+(64*3+63)+','+(64*3+63)+',255)'
  ];
    

</script>

Test runner

Ready to run.

Testing in
TestOps/sec
blit image data
var random = Math.random;
var d = $buf.data;
for (var i = 0, ilen = d.length; i < ilen; i+=64) {
  var c = random() * 4 | 0;
  var col = 64 * c + 63;
  for ( var j = 0; j < 64; j+=4) {
    d[i+j] = col;
    d[i+j+1] = col;
    d[i+j+2] = col;
    d[i+j+3] = 255;
  }
}
$ctx.putImageData($buf, 0, 0);
ready
fillRect
var random = Math.random;
for (var y = 0; y < 120; y++) {
for (var x = 0; x < 120; x++) {
  var i = random() * 4 | 0;
  $ctx.fillStyle = $fs[i];
  $ctx.fillRect(x*$scale, y*$scale, 4, 4);
}}
ready
put image data
var random = Math.random;
for (var y = 0; y < 120; y++) {
for (var x = 0; x < 120; x++) {
  var i = random() * 4 | 0;
  $ctx.putImageData($px[i], x*$scale, y*$scale);
}}
ready

Revisions

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