Recipe 7.15.
Scripting Masks
Problem
You want
to create a mask at runtime.
Solution
Use DisplayObject.mask.
Discussion
Masks can be used to create unique shapes or
visual effects. For example, you can use masks to create wipes and
transitions. You can use masks to create interesting animations in
which only the masked portion of the artwork is visible at a given
time. You can even create masks that shape tween and use them to
mask bitmapped graphics (in movie clips).
Any display object can be used as a mask of
another display object by using the mask property. The
following sets maskSprite as the mask for
sampleSprite:
sampleSprite.mask = maskSprite;
The following example draws two shapes and uses
one as a mask. Note that both display objects are added to the
display list via addChild( ). Although masks will work in
most cases, even when the mask object isn't added to the display
list, it's recommended that you add the mask object to the display
list:
var maskSprite:Sprite = new Sprite( );
var pen:Pen = new Pen(maskSprite.graphics);
pen.beginFill(0xFFFFFF);
pen.drawArc(100, 100, 50, 80, 20, true);
pen.endFill( );
var maskedSprite:Sprite = new Sprite( );
maskedSprite.graphics.lineStyle( );
maskedSprite.graphics.beginFill(0xFF0000);
maskedSprite.graphics.drawRect(0, 0, 200, 200);
maskedSprite.graphics.endFill( );
maskedSprite.mask = maskSprite;
addChild(maskedSprite);
addChild(maskSprite);
This next example shows a mask being used to
follow the mouse. The mask is assigned to a loader containing a
loaded image, which makes it so only the users can see the portion
of the image over which they have placed the mouse:
var loader:Loader = new Loader( );
loader.load(new URLRequest("http://www.rightactionscript.com/samplefiles/image2.jpg"));
addChild(loader);
var maskSprite:Sprite = new Sprite( );
maskSprite.graphics.lineStyle( );
maskSprite.graphics.beginFill(0xFFFFFF);
maskSprite.graphics.drawCircle(0, 0, 50);
maskSprite.graphics.endFill( );
loader.mask = maskSprite;
addChild(maskSprite);
maskSprite.startDrag(true);
|