Friday, November 26, 2010

Create a drawing application using AS3: Part 2

Today we're going to let our user draw rectangles.

Here's what we're making today:


And here is the code:

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

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

var mouseHolding:Boolean = false;
var clickedX:Number;
var clickedY:Number;

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

function mDown(MouseEvent):void
{
mouseHolding = true;
clickedX = mouseX;
clickedY = mouseY;
}

function mUp(MouseEvent):void
{
mouseHolding = false;
myDrawing.graphics.beginFill(0x222222, 0.5);
myDrawing.graphics.drawRect(clickedX, clickedY, mouseX-clickedX, mouseY-clickedY);
myDrawing.graphics.endFill();
clearTemp();
}

stage.addEventListener(MouseEvent.MOUSE_MOVE, mMove);

function mMove(MouseEvent):void
{
if (mouseHolding)
{
clearTemp();
temporaryDrawing.graphics.drawRect(clickedX, clickedY, mouseX-clickedX, mouseY-clickedY);
}
}

function clearTemp():void
{
temporaryDrawing.graphics.clear();
temporaryDrawing.graphics.lineStyle(2, 0x666666, 1);
}

Just like before, we have a variable that is true when user holds his mouse and 3 mouse listeners to operate around with. We will be using 2 Shape objects - one for temporary rectangle, second for drawing the final rectangles.

We add 2 variables - clickedX and clickedY. Those hold the coordinates we click on (the corner of our rectangle). So, in the MOUSE_DOWN function we set these variables to our mouseX and mouseY. When we hold and move our mouse, we draw temporary rectangle to show how it is going to look like when you release mouse.

We also need to add clearTemp() function, which clears all the previous temporaryDrawing.graphics data. Because clear(); resets all styles and fills, we set the lineStyle just after we clear the graphcis in our clearTemp() function.

When user releases mouse - temporary rectangle is cleared and a brand new rectangle (but on another shape) is being drawn. Done!

Thanks for reading!

Related:

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

No comments:

Post a Comment