2

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;
}
andr111
  • 2,982
  • 11
  • 35
  • 45

3 Answers3

7

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);
}
andrewmu
  • 14,276
  • 4
  • 39
  • 37
1

When it comes to pixels on a canvas, you have no choice but to grab them all with getImageData() - .data in your result is a byte array of the data in RGBA order. Don't expect great performance from this, but if that's what you have to do...

Chris Nash
  • 2,941
  • 19
  • 22
1

Count 'em up (pseudocode):

var alphaPixels, alpha, totalPixels

for each pixel (x, y)
    alpha = imageData.data[((y*(imageData.width*4)) + (x*4)) + 3] // <- real code
    //                                 offset to alpha channel ^
    if (alpha > 0)
        alphaPixels++

return alphaPixels / totalPixels

Reference

calebds
  • 25,670
  • 9
  • 46
  • 74