Tutorial: How to Draw Simple Shapes in AS3


Written By Mr Sun at 8:00 am - Saturday, September 13th, 2008
Categories: AS3, All Tutorials, Beginner Tutorials, Flash

Hey guys, today we’re going to learn something fun and exciting! That is, drawing shapes in ActionScript 3.0. I’ve actually covered a little bit of this in my platform tutorial, but I want to make it the focus of this tutorial. So, let’s get started shall we?

First of all, we’re going to create a new flash file. Then, we’ll name “Layer 1″ to “actions” because that will be the only layer that we’ll need to use today.

Drawing Circles

In order to draw a circle, we have to place the following code into the first frame:

//defining a new variable that will be the circle
var newCircle:Shape = new Shape();
//now we begin adding a fill to the variable
//this will make the circle red
newCircle.graphics.beginFill(0xFF0000);
//now we call a function that will draw the circle
//the first value (100) is the x value
//the second value (100) is the y value
//and the third value(50), is the radius
//the x and y values count for the center of the circle,
//now the left corner like you'd usually see
newCircle.graphics.drawCircle(100,100,50);
//this function just tells actionscript that we're done
//using this red fill
newCircle.graphics.endFill();
//adding the circle to the stage
addChild(newCircle);

I really commented out this one so hopefully you can understand what this code does. This will just draw a red circle that is 50 pixels in radius, 50 pixels from left and top of the stage. Without the comments, it only takes 5 lines, so it isn’t too complicated.

End Product

(I made the stage a bit smaller)

Drawing Rectangles/Squares

Drawing a rectangle or square is very similar to the circle, except with a different function called. Here’s the commented code for doing so:

var newRect:Shape = new Shape();
newRect.graphics.beginFill(0xFF0000);
//now we call a function that will draw the square
//the first value (50) is the x value
//the second value (50) is the y value
//the third value (100), is the width
//and the final value (100), is the height
newRect.graphics.drawRect(50,50,100,100);
newRect.graphics.endFill();
addChild(newRect);

I just commented the new stuff that was added in.

The End Product

One Comment

Martin:

ive entered the code correctly, ive double checked and triple checked, but the shape doesnt show on the screen is there some kind o promt to make it appear that you havent mentioned?


Leave a Comment

«
»