Using the AlphaMaskFilter class

This filter is similar in usage to the AlphaMapFilter class, but we will briefly talk about this filter as well. As per the CreateJS documentation, it's recommended that you use this filter instead of AlphaMapFilter because it has much better performance.

AlphaMaskFilter applies the alpha mask from the mask image (or canvas) to the target. The alpha channel of the result will be derived from the mask, and the RGB channels will be copied from the target object.

Here is how we define the AlphaMaskFilter class:

AlphaMaskFilter (mask)

The parameters in this code snippet are as follows:

mask | Image

This class is an instance of the Image class.

Here is an example of using this filter:

/* Declare variables */
var canvas, stage, img;

function init() {
  /* Add canvas and stage */
  canvas = document.getElementById("canvas");
  stage = new createjs.Stage(canvas);

  /* Load image */
  img = new Image();
  img.onload = handleimg;   //function that's called once image has loaded
  img.src = "targetImg.png";  //image url
}

function handleimg() {
  /* Create mask layer */
  var box = new createjs.Shape();
  box.graphics.beginLinearGradientFill(["#000000", "rgba(0, 0, 0, 0)"], [0, 1], 0, 0, 0, 200)
  box.graphics.drawRect(0, 0, 200, 200);
  box.cache(0, 0, 200, 200);

  /* Create bitmap */
  var bmp = new createjs.Bitmap(img); 

  /* Add filter to bitmap */
  bmp.filters = [
     new createjs.AlphaMaskFilter(box.cacheCanvas)
  ];
    bmp.cache(0, 0, 200, 200);

  /* Add bitmap to stage and update stage */ 
  stage.addChild(bmp);
  stage.update();
}

As you can see, the usage of this filter is almost the same as AlphaMapFilter.

The example source code is divided into two functions, init and handleimg. In order to load the image properly, we used the Image class and the onload event. We then used the handleimg function for the onload event callback function.

Inside init function, stage class is created. We also configured the Image class and assigned the handleimg function to the onload event. A major part of the example's source code is inside the handleimg function. In the first few lines, we created a rectangle with a linear gradient background. The reason for using the rgba function to define color is to change the alpha channel of the gradient so that the filter will derive this alpha channel for the final result. Finally, we cached the shape using the cache method.

Then, we loaded an image using the Bitmap function and also applied it to the bmp variable with the filters property. We also cached this image in order to apply the filter changes.

The following screenshot illustrates the result of our example:

Using the AlphaMaskFilter class
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.187.233