An Example and the Code

In this simple example, we show how to programmatically create a mask in ActionScript 3 and Flash. For animating and manipulating masks dynamically, visit our tutorial: See Masking in Flash CS3 and ActionScript 3. For gradient masks, 'soft' masks with feathered edges, see another of our How-Tos: How to Create a Gradient Mask in ActionScript 3.


The Code

We keep comments as comments within the code for greater clarity.

We imported a jpeg image to the Stage and converted it to a MovieClip called PrepPic. Then we linked the MovieClip to AS3 via Linkage item in the Library menu (Flash CS3), or Properties - Linkage (Flash CS4). A Library object that is linked to AS3, can be instantiated at runtime and this is what we are doing below. Instead, of linking to AS3, you could have placed and positioned the MovieClip on the Stage and give it an instance name 'maskedClip'. In that case, you would skip the first four lines. The rest would remain the same.

var maskedClip:MovieClip=new PrepPic();





var clipWidth:Number=maskedClip.width;

var clipHeight:Number=maskedClip.height;


var maskingShape:Shape=new Shape();


//Even though the mask itself will not be visible, it MUST be

//added to the Display List.






//We call a function, defined later in the script, that draws an ellipse

//in 'maskingClip'.



The next line assigns 'maskingShape' as a mask of 'maskedClip'. Comment out this line and test the movie. You see the filled ellipse drawn in 'maskingShape'. When you uncomment the line, the only portion of 'maskedClip' visible is the area of the ellipse. The filled portion of a masking object acts like a 'window' through which we see a masked object.



function drawInMask():void {;,1);,0,clipWidth,clipHeight);;


The masked object can be any Display Object, not necessarily a MovieClip. The masking object can also be any Display Object, not necessarily a Shape. The only visible portion of the masked object will be the portion behind the filled part of the masking object.

If you wish to remove a mask set the 'mask' property of the masked object to null and remove the masking object:


Back to AS3 How To and Tips              Back to Flash and Math Home

We welcome your comments, suggestions, and contributions. Click the Contact Us link below and email one of us.

Adobe®, Flash®, ActionScript®, Flex® are registered trademarks of Adobe Systems Incorporated.