Canvas Pixel Manipulation

JavaScript performance comparison

Revision 90 of this test case created by mattdesl

Preparation code

<canvas id="canvas" height="256" width="256"></canvas>
      
<script>
Benchmark.prototype.setup = function() {
  var canvas = document.getElementById('canvas');
  var canvasWidth  = canvas.width;
  var canvasHeight = canvas.height;
  var ctx = canvas.getContext('2d');
  var imageData = ctx.getImageData(0, 0, canvasWidth, canvasHeight);
  
  var data = imageData.data;
  
  
  var buf = new ArrayBuffer(imageData.data.length);
  var buf8 = new Uint8ClampedArray(buf);
  var data32 = new Uint32Array(buf);
  
  
  
  function multiply1(pixels, rgba) {
          var r = ((rgba & 0xff000000) >>> 24),
              g = ((rgba & 0x00ff0000) >>> 16),
              b = ((rgba & 0x0000ff00) >>> 8),
              a = ((rgba & 0x000000ff)),
              len = pixels.length;
  
          for (var i=0; i<len; i+=4) {
              pixels[i] = pixels[i] * r / 255;
              pixels[i+1] = pixels[i+1] * g / 255;
              pixels[i+2] = pixels[i+2] * b / 255;
              pixels[i+3] = pixels[i+3] * a / 255;
          }
  }
  
  function multiply2(pixels, rgba) {
          var len = pixels.length,
              a1, a2, b1, b2, g1, g2, r1, r2,
              r, g, b, a,
              val;
  
          for (var i=0; i<len; i++) {
              val = pixels[i];
  
              a1 = ((val & 0xff000000) >>> 24);
              a2 = ((rgba & 0xff000000) >>> 24);
              b1 = ((val & 0x00ff0000) >>> 16);
              b2 = ((rgba & 0x00ff0000) >>> 16);
              g1 = ((val & 0x0000ff00) >>> 8);
              g2 = ((rgba & 0x0000ff00) >>> 8);
              r1 = ((val & 0x000000ff));
              r2 = ((rgba & 0x000000ff));
              r  = r1 * r2 / 255;
              g  = g1 * g2 / 255;
              b  = b1 * b2 / 255;
              a  = a1 * a2 / 255;
                  
              pixels[i] = (a << 24) | (b << 16) | (g << 8) | r;
          }
  }

};

Benchmark.prototype.teardown = function() {
  ctx.putImageData(imageData, 0, 0);

};
</script>

Preparation code output

<canvas id="canvas" height="256" width="256"></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
32-bit Pixel Manipulation
multiply2(data32, 0xFF00FFFF);
imageData.data.set(buf8);
pending…
8-bit Pixel Manipulation
multiply1(data, 0xFF00FFFF);
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.

0 Comments