Sunday, 28 June 2009

Dynamic masks using sprites in Actionscript 3.0

In this Flash tutorial you will learn how to create dynamic masks using sprites in Actionscript 3.0. This means you will use code to create the masks, instead of creating the masks using the shapes tools. This tutorial uses Sprite objects which are similar to move clips, but do not require a timeline.

For more information on the Sprite class checkout the ActionScript 3.0 Sprite components reference.

Dynamic masks using sprites in Actionscript 3.0

Step 1

Open a new Flash Actionscript 3.0 file.
Import an image you wish to use as your masked background by selecting File > Import > Import to Stage. Adjust the size of your image to the same as your stage.




Step 2

Select your image and convert into a symbol by selecting F8. Give your image an appropriate name, check movie clip and click ok. Then select your movie clip and give it the instance name: maskedbg_mc.




Step 3

On the timeline insert a new layer called “Actions” then right click and select Actions and add the following code. Most of the code below should look familiar from the Dynamic masks in AS3 tutorial, but the first section is different.

//1.
var mask_mc:Sprite = new Sprite();
mask_mc.graphics.beginFill(0x000000);
mask_mc.graphics.drawEllipse(0, 0, 70, 60);
mask_mc.graphics.endFill();
addChild(mask_mc);

//2.
maskbg_mc.mask=mask_mc;
maskbg_mc.addEventListener(MouseEvent.MOUSE_DOWN, dragMask);
maskbg_mc.addEventListener(MouseEvent.MOUSE_UP, noMask);

//3.
function dragMask(event:MouseEvent):void {
mask_mc.startDrag();
}

function noMask(event:MouseEvent):void {
mask_mc.stopDrag();
}

Code:
1. This creates a new sprite called “mask_mc” and draws an ellipse with the position at (0, 0), the width = 70, height = 60 and adds the shape onto the stage. You can change these values accordingly if you wish. The other shapes you can use as mask are:

* drawCircle(x:Number, y:Number, radius:Number)
* drawRect(x:Number, y:Number, width:Number, height:Number)
* drawRoundRect(x:Number, y:Number, width:Number, height:Number, ellipseWidth:Number, ellipseHeight:Number = NaN)
* drawTriangles(vertices:Vector, indices:Vector = null, uvtData:Vector = null, culling:String = "none")

(Checkout the Actionscript 3.0 graphics component reference for more details)

2. This sets the masked objects to the background image. And also contains two event listener with mouse up and down events with the dragMask and noMask parameters.

3. This is two functions which drags and drops the mask_mc sprite using the stopDrag() and startDrag() methods.


Step 4

Test your dynamic mask Ctrl + Enter. Now use your mouse to click and drag and mask.



You should now have a dynamic mask using sprites in Actionscript 3.0.

0 comments:

  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP