Search code examples
htmlcanvasalphaalpha-transparency

HTML5 get number of alpha-pixels in canvas


I need to get the ratio of transparent/opaque pixels in my canvas. What is the best way to do this?

UPDATE: Based on the below posts I ended up writing this code:

function getNumberOfAlphaPixels(can) {
    var step = 200; //We skip 200 pixels to make it work faster
    var ctx = can.getContext('2d');
    var imgd = ctx.getImageData(0, 0, can.width, can.height);
    var pix = imgd.data;
    var alphaPixelsNum = 0;

    for (var i = 0; i < pix.length; i += 4*step) {
        if (pix[i+3] == 0) {
            alphaPixelsNum += step;
        }
    }

    return alphaPixelsNum;
}

Solution

  • As mentioned, counting the individual opaque pixels is the only way to do it.

    The following is probably faster than the pseudo-code shown in the other answer. Despite JIT tracing/code analysis, it does help for speed to spell out basic low level operations.

    function alphaRatio(ctx) {
      var alphaPixels = 0;
    
      var data = ctx.getImageData(0,0, ctx.canvas.width,ctx.canvas.height).data;
      for(var i=3; i<data.length; i+=4) {
        if(data[i] > 0) alphaPixels++;
      }
    
      return alphaPixels / (ctx.canvas.width * ctx.canvas.height);
    }