Tutorial: Applying and Manipulating a Mask in ActionScript 3

Flash has become the de-facto standard for all kinds of web animations. One of the main reasons, is that it offers an impressive array of bitmap manipulation functions. Out of the box it probably has one of the richest API’s to manipulate bitmaps, vectors and even animation. One of those possibilities is masking, which I will explain in this post.

downloaddownload the full source and FlashDevelop project right here

As you will learn in this small tutorial, applying a mask to any Flash object is incredibly easy. However, if you search for more information on Google, you’ll only find ActionScript 2 tutorials. This one is specific for ActionScript 3 and furthermore it is a pure ActionScript solution, so you don’t need to buy anything. FlashDevelop will do just fine. They have just released a new version.

Applying a mask is just as easy as it used to be in AS2:

background.mask = myMask;

The mask itself is a Sprite on which I drew a rectangle. You could make it pretty much any shape. I put the rectangle in the top left corner and moved the sprite. This will make it a lot easier to move and rescale the sprite later on.

myMask = new Sprite();
myMask.graphics.beginFill(0x00FF00);
myMask.graphics.drawRect(0, 0, myMaskSize, myMaskSize);
myMask.x = 350;
myMask.y = 250;
addChild(myMask);

This is all pretty straightforward, however I was a bit stumped when I wanted to let the user move the mask with his mouse. Apparently it’s not possible to attach an event listener to a Sprite once it is a mask. According to all the AS2 demos I found, this used to be possible. But no problem, I attached them to the stage. If you only want to register clicks on the displayed area, you might want to do a little processing of the mouse coordinates in the mouseDown method, but I didn’t bother.

Just for kicks I also added a mouse wheel listener, so that you can change the size of the masked area. This is the result:

You might notice that Flash still forwards the scroll event to the browser, so the browser window also scrolls. Apparently there isn’t a good solution for this problem. So beware if you want to use the scroll event in a real application.

downloaddownload the full source and FlashDevelop project right here

Image credit