Setting one HTML5 Canvas Pixel (v25)

Revision 25 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="160" height="144"></canvas>
<style type="text/css">
  canvas {
    image-rendering: optimizeSpeed;
    image-rendering: -moz-crisp-edges;
    image-rendering: -webkit-optimize-contrast;
    image-rendering: optimize-contrast;
    -ms-interpolation-mode: nearest-neighbor;
    border: 5px solid #ddd;
    width: 640px;
    height: 574px;
  }
</style>
<script>
  $c = document.getElementById('c');
  $ctx = $c.getContext('2d');
  $ctx.imageSmoothingEnabled = false;
  $ctx.webkitImageSmoothingEnabled = false;
  $ctx.mozImageSmoothingEnabled = false;
  $ctx.clearRect(0, 0, $c.width, $c.height);
  $buf = $ctx.getImageData(0, 0, $c.width, $c.height);
  $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+=4) {
  var c = random() * 4 | 0;
  var col = 64 * c + 63;
  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.