Thursday, November 25, 2010

Create a mouse eraser using AS3

Today we'll create an eraser effect using AS3.

Try erasing the white space to see an image:


Here's the code.

var myDrawing:Shape = new Shape();
addChild(myDrawing);
myPicture.mask = myDrawing;

var mouseHolding:Boolean = false;

stage.addEventListener(MouseEvent.MOUSE_DOWN, mDown);
stage.addEventListener(MouseEvent.MOUSE_UP, mUp);

function mDown(MouseEvent):void
{
mouseHolding = true;

}

function mUp(MouseEvent):void
{
mouseHolding = false;
}

stage.addEventListener(MouseEvent.MOUSE_MOVE, mMove);

function mMove(MouseEvent):void
{
if (mouseHolding)
{
myDrawing.graphics.beginFill(0x000000);
myDrawing.graphics.drawRect(mouseX-20, mouseY-20, 40, 40);
myDrawing.graphics.endFill();
}
}

Just like in the previous tutorial, we have a variable called mouseHolding, which is true when the user holds his mouse, as well as 3 mouse event listeners.

What we need to do, is to set myPicture's (instance name of my picture container on stage) mask to myDrawing and draw rectangle at the current mouse position when mouse is held. Simple, but effective!

Thanks for reading!

1 comment:

dontworryaboutitmate said...

Haha, there I was expecting a natural landscape to be underneath..

Nice!

Post a Comment