Search code examples
htmlcreatejseaseljs

How to detect that the AlphaMaskFilter is completely gone in easeljs/createjs


I am doing a little scratch/reveal game based on the AlphaMaskFilter example: http://createjs.com/demos/easeljs/AlphaMaskReveal.html

I want to detect that the the mask is completely gone, or use a threshold (90% scratched for example).

I read the doc on AlphaMaskFilter, shape and graphics objects and im not really sure how to achieve this.

Im not even sure i Have acess to the pixel information and check the alpha channel to detect it, but even so, I wonder if I will performance issue.

any help is welcome, thanks.

**** EDIT **** ADD TO THE ACCEPTED ANSWER ****

So, I was able to have the pct of transparency using the AlphaMapFilter (thanks Lanny). The AlphaMapFilter offer you a mapping to the alpha channel of all the pixels. Here is a little sample code that worked for me:

        // mShapeToScratch is a createjs Shape. like in the http://createjs.com/demos/easeljs/AlphaMaskReveal.html example
        var alphaMaskFilter = new createjs.AlphaMapFilter(mShapeToScratch.cacheCanvas);
        var canvas = alphaMaskFilter.alphaMap;
        var ctx = canvas.getContext("2d");
        var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
        var alphaData = imgData.data;
        var pixelTotal = rect.h*rect.w;
        var transparentPixel = 0;

        // rect.h is the height of the image and rect.w is the width not shown in the example
        for (var y = 0; y < rect.h; ++y)
        {
          for (var x=0; x < rect.w; ++x)
          {
            var pixelIdx = (y*rect.w + x);

            if(alphaData[pixelIdx] > 128) // transparent will be 255.
            {
                transparentPixel++;
            }
        }

        console.log("transparent % = " + transparentPixel/pixelTotal);

This example checks all the pixels, but it's pretty easy to check one every X pixels to speeds up checks as Lanny suggested.


Solution

  • The alpha mask uses canvas composite operation, and not pixel access, so without some completely custom approach, there isn't a great way to do this.

    Iterating pixels (check out AlphaMapFilter as an example) would work - but could be fairly slow. Maybe checking every 4th, 10th, or 25th pixel would speed it up.

    Cheers.