andr111
andr111

Reputation: 3052

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;
}

Upvotes: 2

Views: 2368

Answers (3)

andrewmu
andrewmu

Reputation: 14534

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);
}

Upvotes: 7

calebds
calebds

Reputation: 26228

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

Upvotes: 1

Chris Nash
Chris Nash

Reputation: 3051

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...

Upvotes: 1

Related Questions