First time here? First time here? Newsletter Signup Newsletter
651326 Members and growing! | Flash Jobs
Search tutorials
Author: Josh Buhler | Website: http://www.joshbuhler.com

Dynamic Drawing Using ActionScript

When Flash MX was introduced, several new features were added to both the authoring enviroment and to ActionScript. My favorite group of new methods added were the drawing methods added to the MovieClip class, also referred to as the Drawing API. This tutorial will try to help you in understanding and using these methods.

When Flash MX was introduced, several new features were added to both the authoring enviroment and to ActionScript. My favorite group of new methods added were the drawing methods added to the MovieClip class, also referred to as the Drawing API. These methods allow you to dynamically draw shapes on the stage of the Flash Player at runtime. Now, you may be thinking one of a few things now: "Neat. I can draw a square with ActionScript. Wow." or, "when would I ever use this?", or if you're like me, "SWEET! Now what can I do with this?" If you were thinking one of the first two things I just mentioned, keep reading, and I'll show you what you can do with this, and why you would want to use it. If you're excited about this and what to see just what you can do, I'll show you what I've already done with it. There are some pretty basic concepts here, but you'll be able to do some amazing things once you get them down.

First, some basics - The Drawing API consists of eight methods:
  • lineStyle()
  • moveTo()
  • lineTo()
  • curveTo()
  • beginFill()
  • beginGradientFill()
  • endFill()
  • clear()

Each of these methods allows you to dynamically draw a shape on the stage using a MovieClip. The easiest way to visualize how this thing works is to imagine yourself at a desk with a pen and a piece of paper. The first thing you'll do is pick what pen you want to use. You'll then decide where you want to start drawing at, and move your pen to that spot. You then decide where you want your lines to end, and draw them to that point. If you want to start a new line, you'll move your pen to that spot, and start again.

The Drawing API works in a similar method. First, you already have your paper, the stage. To draw, you'll also need a "pen". This is a MovieClip. You can use a MovieClip already placed on the stage, or, you can create one dynamically using createEmptyMovieClip. You then need to decide what type of "pen" you want. This is done by using the lineStyle() method. lineStyle() allows you to specify the line thickness, color, and alpha value of the line. You then move the "pen" to the position you'd like to start drawing from using moveTo(), and then draw your line using either lineTo() or curveTo(). If you would like to fill this shape, you would use either beginFill() or beginGradientFill(), combined with endFill(). To wipe the slate clean and erase your drawings, the clear() method is called.

But enough talk, on to the coding -
First, a quick example of this thing in action. The code below draws a simple black box on the stage, with no fill, followed by a solid black box, with a red border. To view this in action, open a new .FLA, and paste the code below into the first frame.

Download the source files for this tutorial - drawingAPI.zip

example1.fla

// first create a 'pen' to draw with
  createEmptyMovieClip("pen_mc",5);
  //
  // set the line style - 0 pixels thick, black, 100% alpha
  pen_mc.lineStyle(0,0x000000,100);
  //
  // move the pen to 100 x,100 y on the stage
  pen_mc.moveTo(100,100);
  //
  // draw the next lines, each starting from the last point the pen was at
  pen_mc.lineTo(200,100);
  pen_mc.lineTo(200,200);
  pen_mc.lineTo(100,200);
  pen_mc.lineTo(100,100);
  //
  // start the next box
  // set the new line style - 5 pixels thick, red, 100% alpha
  pen_mc.lineStyle(5,0xff0000,100);
  //
  // move the pen to 400 x,100 y on the stage
  pen_mc.moveTo(300,100);
  //
  // start the fill
  pen_mc.beginFill(0x000000,100);
  // draw the next lines, each starting from the last point the pen was at
  pen_mc.lineTo(400,100);
  pen_mc.lineTo(400,200);
  pen_mc.lineTo(300,200);
  pen_mc.lineTo(300,100);
  //
  // end the fill
pen_mc.endFill();

The code above produces the following:




The comments explain most of what's going on here, but here is some extra notes. First, a MovieClip is created to use as a 'pen'. The line style is then set using lineStyle(). Three parameters are passed to this - the line thickness, which can be from 0-255, the color, and the alpha value of the line.

// lineStyle() syntax
movieClip_mc.lineStyle(thickness,color,alpha);

While you can set the line thickness to a value between 1-10, in the Flash IDE using the properties panel, you can set the line thickness to be any thickness between 0 and 255, using ActionScript. Setting the thickness to zero is the same as using a hairline in the IDE. You must first set the lineStyle() before you begin drawing, otherwise, how can you draw without first choosing what type of pen you're going to use?

The 'pen' is then moved to the point 100,100. Using moveTo() moves the drawing point, without drawing anything. Then, a set of lines are drawn to various points using lineTo(). The important thing to remember about lineTo() is that it will draw a line from the last position of the pen to the new position specified. If no starting point is specified using moveTo(), then the point 0,0 on the timeline in which the MovieClip lives will be used as a starting point. Since we moved the pen to 100,100 using moveTo(), the first line will be drawn from 100,100 to 200,100. The next line will then be drawn from 200,100 to 200,200, and so on and so on...

// moveTo() syntax
movieClip_mc.moveTo(x,y);
//
// lineTo() syntax
movieClip_mc.lineTo(x,y);

After the first box is done, we start a new one in the same manner that we did the first one. However, we can skip creating a new MovieClip because the same MovieClip can draw more than one shape, but only in the same timeline. One small difference here is that we changed the line style the shape is drawn with. But the main difference between these shapes is the fill.

To draw a solid shape, you need to use beginFill() before you begin drawing your shape. You then draw the shape, and when the shape is complete, use endFill(). The important thing to remember when using fills it to make sure that your shape ends at the same point that it begins at. If you do not end the shape at the same point it began at, unpredictable things can happen, and the shape most likely will not fill correctly. You can also fill a shape using a gradient fill, but that is almost a topic for another tutorial. I'll cover that a little bit later on.

// beginFill() syntax
movieClip_mc.beginFill(fillColor,alpha);
//
// endFill syntax
movieClip_mc.endFill();

In the source files you downloaded, open the file basicShapes.fla.
basicShapes.fla - (opens in a new window)

The example above, basicShapes.fla, is a quick example of how you could use the drawingAPI to create some basic shapes such as a square, triangle, and circle.

Using curveTo()

To draw a curve, curveTo() is used. This draws a curve using three points. The last point drawn to or set using moveTo(), a control point which is used to specify the amount of curve, and the end point of the curve. An example of a curve and the points used is below. Just drag the handles around to see the points used in drawing the curve below.

// curveTo() syntax
movieClip_mc.curveTo(controlX, controlY, endX, endY);

curveTo.fla





Now, going back to the basicShapes.fla example, you can see how these curves and their control points can affect a curve. If you compare the circle and the oval, you'll notice that the oval actually has four points on it's sides. This is because of the quadratic bezier curves that Flash uses to draw curves. In order to draw something close to drawing a true circle using the drawing API, you'll need to use at least 8 line segments. However, this involves doing some somewhat tricky geometry to determine the control points. You can see the code involved in drawing a circle in the basicShapes.fla in the drawCircle() function.

Gradient Fills

After covering everything else, beginGradientFill() needs a mention. This is the most complicated of the drawing commands, but I'll try to keep it simple. You can find a more in-depth explaination in ActionScript for Flash MX: The Definitive Guide, Second Edition - Colin Moock. (You'll need to look in the second edition, as the first edition doesn't cover the drawing methods.)

// beginGradientFill() syntax
movieClip_mc.beginGradientFill(fillType, colors, alphas, ratios, matrix);
The parameters are:
  • fillType - A string value of either "linear" or "radial", depending on the type of gradient you would like to use.
  • colors - An array of the colors used in the gradient
  • alphas - An array of the alpha values for each color used, 0-100
  • ratios - A value 0-255 for each color that determines the distribution of the colors in the gradient
  • matrix - An object that contains information about the placement of the gradient
If you would like to use a gradient that has three colors in it, you'll use three colors in your colors array:
var colors:Array = [0xff0000, 0x00ff00, 0x0000ff];

Now that you are using three colors, the alphas and ratios arrays both must have three elements in them. One for each color. Whenever you use beginGradientFill(), these arrays must always have the same number of elements in them to work properly.

var alphas:Array = [100, 50, 92];
var ratios:Array = [0, 125, 255];

One thing to remember about the ratios values is this: if you want to actually see a gradient from one color to another, make sure that left-to-right the values always increase. Otherwise, you'll end up with with a solid line from one color to another, with no gradient transition between them. Open the gradientFill.fla example to see how this works. You can adjust the sliders and see in the textBox near the bottom how the code to generate the fill is created. Adjust the "Ratios" sliders so that the red slider is higher than the green one, and you'll see how you can create the solid line instead of a nice transition.

gradientFill.fla - (opens in a new window)

The matrix object is created as follows:

var matrix:Object = {matrixType:"box", x:xPos, y:yPos, w:width, h:height, r:rotationAmountInRadians};

The matrixType is set to "box". Then, you set the x and y positions of where your gradient starts. Basically, you'll be creating the gradient on a "layer" underneath the shape you draw. The shape then acts as a mask over your gradient. The gradient will actually extend far beyond your shape, but only the area underneath your shape will be seen. You can adjust the position of your gradient under the shape using the x and y values of the matrix. The height and width values are the height and width of your gradient. Finally, set the rotation value of your gradient. However, this needs to be the amount of rotation in radians, not degrees. To convert degrees to radians, use the following function in your code:

function toRadians(degrees:Number):Number {
 return degrees*Math.PI/180;
}

You can then set your rotation value using this:

r:toRadians(degrees)

By playing around with the sliders in the gradientFill.fla example, you can see how these values all work together in creating your gradient fill. Take a look at the code inside to get a better look at how everything works.

Ending your gradient fill is the same as a regular one: movieClip_mc.endFill(); once you've completed your shape.

Examples of the Drawing API at work

I've included some more examples of some things I've done with the drawing API. Some real-world examples, and some just for fun ones. Not all of these will be found with the source files you've downloaded.

Dodge Viper - I wouldn't recommend drawing a car using the drawing API, as it could easily be done much faster using the standard drawing tools. However, this was for a class project a long time ago, and I had the time to type out the over 900 lines needed to do this. You can compare the differences between standard and gradient fills with this one.

RideHarder.com's Build-A-Board - At MediaRain we used the drawing API in this application which allows users to design and order their own one-of-a-kind custom snowboard. I've got one, and I love it.

Slurs and Ties in music - In creating the slurs and ties over the notes, (the arches over the notes for non-music folk), we used the drawing API in order to draw them however we needed to.

The Spinner is a quick little example of something I just though of one morning while taking a shower. Just click and hold somewhere in the gray circle. Included with the source files.

Line Design is another example of designs that can be done with this. However, it may run slowly on older machines. Included with the source files.

Redrawing Images - This example uses a php script that reads through a jpg image and extracts the color information, then passes it back to Flash to redraw the image using the drawing API. The image comes from Penny Arcade

Other things I have done include a drawing tool similar to MS Paint, (about the same quality too!), a Flash version of the Etch-A-Sketch toy, and marquee selection tools for other projects.

» Level Intermediate

Added: 2005-01-09
Rating: 9 Votes: 10
(10 being the highest)
» Author
Josh Buhler is a Macromedia Certifed Flash developer in Salt Lake City, UT
» Download
Download the files used in this tutorial.
» Forums
More help? Search our boards for quick answers!

Comments

  • There are no comments yet. Be the first to comment!

  • You must have javascript enabled in order to post comments.

Leave a Comment
  • Your email address will not be published. All fields are required.
Featured Flash FLA
» Author: work2survive
» Title: Girl Walking 1kb
» Description: Walking girl, animation just takes 1kb, using high heels shoes, and fashion model attitude.
Featured Sound Loops
Image for equalize

Audio Player

» Author: BoxCat
» Title: CPU Talk
» Description: From the cyberpunk RPG, "Nameless: the Hackers" Completely Free to use! Keywords: edm hip hop rap electronic mysterious mission hacking chase exciting spy ios ambient chilling love happy sad angry suspense
Latest Font
» Author: Fábio FAFERS
» Description: I created this font for free use. Everyone can apply it in personal or business texts. Its free, but I want to be communicated in case of business use. Donations are accepted to keep the project of free fonts alive! Thank you all
Featured Sound Fx
Image for equalize

Audio Player

» Author: nathan
» Description:

A recorded sound of the Dimensional Fork Gate.