Wednesday, November 24, 2010

Create a drawing application using AS3: Part 1

Today we will create a simple drawing application.

Try it out:


Here is the code.

var myDrawing:Shape = new Shape();
addChild(myDrawing);
myDrawing.graphics.lineStyle(2, 0x000000, 1);

var mouseHolding:Boolean = false;

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

function mDown(MouseEvent):void
{
mouseHolding = true;
myDrawing.graphics.moveTo(mouseX, mouseY);
}

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

stage.addEventListener(MouseEvent.MOUSE_MOVE, mMove);

function mMove(MouseEvent):void
{
if (mouseHolding)
{
myDrawing.graphics.lineTo(mouseX, mouseY);
}
}

Now I'll explain.

Firstly, we create a graphics container (a Shape object). We need to create a boolean variable that will hold information on whether the user is holding his mouse or not.

Add 2 mouse listeners to manage this variable, as well as add a moveTo(); to the MOUSE_DOWN function. This is needed, because this will be the starting point of our line we will draw.

Now we add a listener for MOUSE_MOVE and check, whether the user is holding his mouse. If he is, we use the lineTo(); method to draw a line to the current mouse position.

Thanks for reading!

Related:

Create a drawing application using AS3: Part 2
Create a drawing application using AS3: Part 3
Create a drawing application using AS3: Part 4
Create a drawing application using AS3: Part 5

1 comment:

Anonymous said...

nice...for a beginner

Post a Comment