Flash Explained

Learn Flash easily.

Creating a colored gradient background for your SWF movie via ActionScript

October 14th, 2008 | Author: Luka | Category: ActionScript

In this lesson, I will show you how to create a background for your Flash document using no design tools at all! Besides being far more easy to change then a drawn graphic, this background created with ActionScript will adapt itself automatically to any size your movie may have. But more on that later.

The examples below show what you’re going to achieve at the end of this tutorial.

Setting up your Flash document

1 Open a new Flash document. Select File > Publish Settings. Click the Flash tab on top of the window that appears.

In the Version menu, choose Flash Player 6 (see 1 in the image below). In the ActionScript version menu, select ActionScript 1.0 (2). Click OK.

Setting the Publish settings for your Flash movie.

You have just set up your Flash document so that it is backwards compatible. This means that if a user has Flash Player 6 installed on his system, he will still be able to see your movie with no problems. You cannot go on assuming that everyone has the latest version of Flash Player installed on their system. This is especially true if you are making a site for large audiences.

Now, you only needed to do this if you are working in Flash MX 2004 or Flash 8. If you are working in Flash MX, you don't need to make these kinds of adjustements.

2 Call the first layer in your movie actions. Click on its first (and only) keyframe to select it.

Selecting the first keyframe.

You can even lock this layer if you want. Just click on the small dot below the little padlock icon. This is done in order to ensure that you don't accidentaly draw something in this layer. That wouldn't do your movie any harm, but it is better to have a layer reserved just for ActionScript. And you can enter the ActionScript in this layer even if it is locked.

Top of page

Entering the ActionScript that creates the gradient movie background

3 Select Window > Actions or press F9 to open up the Actions panel. You will see a title on top of the Actions window saying "Actions - Frame".

That means the ActionScript code that you're going to type in will be assigned to the keyframe you just selected in the previous step, and not a movie clip or a button (if you had one in your movie). This is just a small check that assures you that you are putting your ActionScript where it's supposed to be placed.

ActionScript code that is situated on the first keyframe of a movie, regardless of the layer it is in, gets executed immediately. It is the first thing Flash reads and runs. Of course, if your timeline contains an animation that loops infinitely (unless you told it to stop at the end), the ActionScript in the first keyframe will get executed again when the playhead returns to the beginning after reaching the end of the animation.

4 Enter the following ActionScript code in the Actions window:

wSize = Stage.width;
hSize = Stage.height;
fillType = "linear";
colors = [0xFF0000, 0xFFFF00];
alphas = [100, 100];
ratios = [0, 255];
matrix = {matrixType:"box", x:0, y:0, w:wSize, h:hSize, r:90/180*Math.PI};
_root.lineStyle(1, 0xFFFFFF, 0);
_root.beginGradientFill(fillType, colors, alphas, ratios, matrix);
_root.lineTo(wSize, 0);
_root.lineTo(wSize, hSize);
_root.lineTo(0, hSize);
_root.lineTo(0, 0);

You will see a small letter "a" appear in the first keyframe. This shows you that there is some ActionScript situated on that keyframe.

A lowercase letter a indicating ActionScript placed on a keyframe.

5 Select Control > Test Movie to preview your Flash movie. You shoud see a red-yellow gradient appear, spanning the whole stage, from top to bottom.

The image below is a reduced screenshot of what your result should look like.

A gradient color background made with ActionScript.

6 Now go back to your movie and change its size. Select Modify > Document (or press Ctrl+J). In the window that appears, change the movie's width and height by entering some other numbers in the Dimensions fields (see 1 in the image below).

Modifying the document dimensions.

Click OK. Test your movie again (Ctrl+Enter) and you'll see that the gradient fills the whole movie area again. You can try this as many times as you want, the gradient background will always cover the whole area of the SWF.

Now that you've seen how nice this is 🙂 let me explain you what makes it happen.

Top of page

The ActionScript that creates the gradient background explained

The first two lines of your ActionScript code,

wSize = Stage.width;
hSize = Stage.height;

define two variables, wSize and hSize. The value of the first variable, wSize, is the width of the stage of your flash movie in pixels. So, by writing Stage.width you tell Flash to look up the width of the stage. Once read, this value is stored in the wSize variable for later use.

The variable hSize stores the height of your flash movie's stage, again, in pixels.

It is precisely these two variables that make possible the filling of the entire flash movie area with the gradient. No matter what dimensions of your document you chose (in the Document Properties window), once the movie is being run, Flash instantly reads those two values and stores them in variables.

I used wSize and hSize as variable names - you can make up any other names, as long as they aren't ActionScript keywords reserved for a particular purpose. Don't use the words "width" or "height" because they are ActionScript keywords.

The variable fillType stores the information which tells what kind of fill will be used - it can be linear or radial gradient. So, you can choose to write either "linear" or "radial". This value must be written between quotation marks, because it is a string type of variable. If you'd omit the quotation marks, Flash would think that this some kind of variable, would look for it, woudln't find it and an error would occur. This variable will be used later, with the beginGradientFill method.

fillType = "linear";

The colors variable is an array type of variable. An array variable can contain multiple values, unlike the wSize or fillType variables, which were simple variables containing a numerical and a string (text) value, respectively. Think of an array variable as of a filing cabinet. There are many drawers in this cabinet, and inside each drawer there is a value.

You will store the codes for colors used in your gradient inside this variable. Each value has to be separated by a comma and they are all placed inside square brackets: [ and ].

colors = [0xFF0000, 0xFFFF00];

The code for a particular color is preceded by a zero and a lowercase letter x (0x). What follows is the hexademical code for a color you chose to put inside your gradient. How to find the code for a particular color? Easy (of course it is :). In Flash, just click on any case for picking a color (the one in the Tools panel for example) and read its code (see 1 in the image below).

Reading the code of a color in Flash.

If you want to look up the code for a color that isn't displayed within the web-safe palette, click on the small colored circle (see 2 in the image above) and you'll have all the thousands of color available on your machine at your disposal.

The important thing is that you must omit the hash sign (#) in front of the color code, and put the appropriate ActionScript sign (0x). So, the color #00CC66 displayed in the above image would become 0x00CC66.

Also, remember that you can have a maximum of 15 colors in your colors variable. These colors will be used later too, just like the fillType variable.

The piece of ActionScript that follows,

alphas = [100, 100];

defines the transparency of the colors you have just written in the previous line. The alpha property of a color can go between 0 and 100. If you want a color to be completely transparent (i.e. invisible), put this value to zero. 100 means the color will be completely opaque.

Important: the number of values in the alphas array must match the number of colors used in the colors array.

The same is true for the next array variable: ratios. The number of values inside this array must match those of colors and alphas.

ratios = [0, 255];

The ratio value for a color defines the place inside the gradient, for that color, where it has its purest value, before or after it has begun merging with an adjacent color. This value can go from 0 to 255. The following pictures will help you better understand the role of this parameter.

Pure red (FF0000) is positioned at the beginning of the gradient, therefore, its ratio value equals 0. Pure yellow (FFFF00) is situated at the end of the gradient, so its ratio value is 255.

The arrows indicate the positions of the pure colors with their corresponding ratio values.

By making the following change to the ratio for red (marked in bold):

ratios = [127, 255];

You will have the following result:

The gradient with the ratio value for red increased to 127.

So, once the ratio value for red has been increased to 127, the pure red hue (FF0000) goes from the beginning (ratio 0) up to ratio value 127, which is in the middle of the gradient. Well, the exact middle would be 127.5 (255 divided by 2), but I put 127. Now you see how the ratio value can be used to influence the distribution of colors in the gradient.

The ratio values in the ratios array must be written in increasing order. In other words, they must be written as they grow. For example: [20, 100, 255] is ok. You cannot write [255, 100, 20] - your gradient would show just one color.

The matrix variable defines the shape, placement, size and rotation of the gradient.

matrix = {matrixType:"box", x:0, y:0, w:wSize, h:hSize, r:90/180*Math.PI};

The shape of the gradient is rectangular ("box", it can also be more complicated, like a 3x3 matrix, but I'll leave that for some other lesson). Its position is defined by the position of its top left corner (x:0, y:0), its dimensions by the w and h parameters (you wrote them at the beginning, stored inside the wSize and hSize variables).

The last parameter is r, which stands for rotation of the gradient. Its value is expressed in radians, rather than degress. So I put inside a mathematical formula for converting degrees into radians:


Translated into english, the formula says this:

rotation in radians = rotation in degrees / 180 * ?

In this lesson, you have 90 degrees so that the gradient goes from top to the bottom of your movie's scene. Try putting 45 instead of 90 and see how the gradient will get rotated diagonally, by 45 degrees.

The next line is an obligatory one if you want to start drawing with ActionScript:

_root.lineStyle(1, 0xFFFFFF, 0);

You can also put an Instance name of a movie clip, if you have one on your stage, instead of _root, which designates the main timeline (the flash movie itself):

myMovieClip.lineStyle(1, 0xFFFFFF,0);

So, the lineStyle method (a method is a command in programmers' jargon) tells Flash that drawing via ActionScript is about to begin. The first parameter between the parentheses defines the thickness of the line. The second one the color used, and the last one the color's alpha property (transparency). I have set it to zero because I don't want it to be seen - I want only the gradient to appear, with no frame around it.

Now, you also tell Flash that you will fill that drawing, with a gradient fill, by using the beginGradientFill method. This method has many parameters between its parentheses, which define the appearance of the gradient. All these values have been just explained previously.

_root.beginGradientFill(fillType, colors, alphas, ratios, matrix);

Drawing with ActionScript is done via the ActionScript lineTo method. If you don't tell Flash to move the starting point for drawing with the moveTo command (see the tutorial on basic drawing with ActionScript for an in-depth explanation of this command), it will begin drawing from the default starting point: x:0, y:0.

So, here, the drawing starts at the default point (0,0), which is the top left point of the stage. The next line is drawn from this point to the top right corner of the stage:

_root.lineTo(wSize, 0);

Remember, the wSize variable holds the width of the stage in pixels which you defined at the beginning of your code. The next portion of ActionScript code draws three lines which close the rectangle.

_root.lineTo(wSize, hSize);
_root.lineTo(0, hSize);
_root.lineTo(0, 0);

Here's the image explaining the drawing:

Diagram explaining how the lineTo method works.

The last piece of ActionScript closes the fill.


Cool! You just learned how the ActionScript movie background actually functions.

Top of page

Some points to keep in mind

The advantages of a gradient-filled movie background created with ActionScript over one made with design tools (rectangle, paint bucket, etc) are many:

  • This background is easy to apply to any movie. You just have to copy the code you learned in this tutorial and paste it into another movie.
  • Changing the colors of the gradient is really easy: all you have to do is change their codes, and that's it.
  • If you were to create a gradient background with the rectangle tool, you would have to change the rectangle in accordance with the movie's dimensions. The gradient made with ActionScript is self-adjusting. It adapts itself to any movie size.
  • It is easy to add more colors to the gradient by just adding them inside the appropriate variable. Again, this is far more practical then making another fill in the Colors panel. It saves you time, too.
  • You learned some very simple ActionScript code that produces a great effect, which is, of course, cool. 🙂

Download the zipped source FLA file for this lesson.

Download the source for the example with multiple colors.

Be Sociable, Share!


Submit a comment

  • Tony Akers Oct 26, 2008 at 1:00 pm

    I am trying to learn web design and this is very easy and helpful, thank you. It would be helpful to the beginners (me) if you could go into a little deeper explanation how to apply a movie to it. And as I said, thank you it is a good start.

  • Vitaliy Nov 1, 2008 at 8:41 am


  • Mexico’s gal Jan 8, 2009 at 6:20 am

    I like your explanation and the example helped me to do one of the exercises with my class. I have given all the students your website and name as reference for future projects.
    I wish you the best on this 2009.

    Mexico’s gal.

  • Anya Natane Feb 11, 2009 at 4:30 pm

    This was extremely helpful! I do have one question. I am drawing gradients behind dynamically created text boxes. There are three text boxes on the stage at a time. The first gradient corresponds to the first text box location and dimensions and so on. However, for some reason, even when I change the variable names of the gradient part it still draws the gradient in the same place as the first one. Can I have multiple gradients drawn at the same time?

  • Dawy Jul 14, 2009 at 4:02 pm

    very very useful

  • admec multimedia Dec 2, 2010 at 10:50 am

    Really, it was very helpfull for me, i am a senior actionscript programmer in admec multimedia institute teaching actionscript2.0 and 3.0 with flex frameworks. i developed many concepts for stage color changing but it is very easy to use.

    post some more nice tuts.

    admec multimedia staff

  • Gecko Multimedia Feb 10, 2011 at 7:36 am

    wow ! it was really very helpful for me thanks for sharing with us………

  • vinay May 3, 2012 at 7:53 am

    its too much helpfull to the learners

  • eashan Sep 13, 2012 at 5:26 am

    Excellent detailed tutorial! Thanks a lot for sharing this! It’s ideal for beginners

You must log in to post a comment.