In this tutorial, I will assume a basic level of Flash Actionscript knowledge and will be using the basic drawing API methods available since Flash MX. We will also use functions to create streamlined, reusable code.
Sections:

1. A brief look at the Flash Drawing API.
2. Organising our Movie.
3. Creating the graphics with Actionscript.
4. Creating the percentage textfield with Actionscript.
5. Centering the preloader on the stage.
6. Writing the functions to collect data.
7. Putting it all together.

Grab all the tutorial files here


What is the point?

The idea behind preloading is that to ensure that everything we need to run our movie correctly; graphics, sounds, animations, etc have all completely loaded. We do this by stopping the movie from playing at a very early point – frame 1 being the most logical place – whilst we find out two things:

1) how much of the movie there is in total to load.
2) how much we have already loaded.

Once we have these two numbers, we can create a percentage and then effectively give a waiting user a good idea of how long they will have to wait before the show will begin!

Since Flash MX, it has been possible to create graphics through Actionscript code whilst the movie is running and we will use this to create a simple bar graphic to display how much of our movie is loaded.


Step 1: A brief look at the Flash Drawing API.

The Flash Drawing API gives us the power to create graphics in our movie without ever having to touch the Flash authoring environment. It provides extremely simple methods (functions), with which we can draw lines, shapes and fills whilst the movie is running. The methods we will be using in our preloader will be:

moveTo – Move to a new position to begin drawing.
lineTo – Draw a straight line from the current drawing position to the x,y coordinates specified.
beginFill – Specify the fill details of the shape we are about to draw.
endFill – Close current shape and fill it.

NOTE: Method names above are linked to Macromedia’s LiveDocs for full explanation.


Step 2: Organising our Movie.

As the code we’re going to be writing here will be dedicated to our preloader we don’t want to get it confused with other pieces of code that may exist in our movie. To prevent this and make it easy for us to find our code within our movie, create a new layer on the main timeline and call it ‘PRELOADER’. We will use the first frame of this layer for all our code.

NOTE: It is a good option to create an external actionscript file (.as) and use the ‘#include‘ compiler directive to add your code to the movie.


Step 3: Creating the Graphics with Actionscript.

Right. Let’s get started.
The first thing we will need if we are going to be able to draw is a MovieClip. As moveTo, lineTo, etc are all methods of the MovieClip Class (object), we will need an instance of a MovieClip in our movie in order to use them. This doesn’t mean that we have to go placing a clip on the stage like usual – all we need to do is to use the createEmptyMovieClip method.
When using createEmptyMovieClip we can capture a reference (a virtual link to the actual MovieClip) to the newly created MovieClip and store it in a variable for ease of use.

NOTE: For more information on MovieClips and references, check out Colin Moock’s Actionscript: The Definitive Guide.

Lets’s start by creating a container MovieClip, which will hold all of our graphics. We do this so that when it’s time to remove our preloader, we can do so by just removing the container. Select the 1st frame on our PRELOADER layer and add the following:

// Create our container and store reference in a variable:
var preloader_mc = createEmptyMovieClip( “preloader”, 10 );

Our preloader’s graphics will be two basic rectangles: one filled and one hollow. First, let’s make our filled rectangle – 150 pixels wide and 15 pixels high. This will be the main bar of our preloader.

//Create our drawing MovieClip inside our container:
var filledBar_mc = preloader_mc.createEmptyMovieClip( “filledBar”, 20 );

// Set the Style for the outline of our rectangle:
// ( thickness, rgb color, alpha )
filledBar_mc.lineStyle( 1,0×999999,100 );

// Move our drawing clip into position:
filledBar_mc.moveTo( 0,0 );

// Set our shape’s fill properties:
filledBar_mc.beginFill( 0xCCCCCC );

// Draw our rectangle ( 150px / 15px ):
filledBar_mc.lineTo( 150,0 );
filledBar_mc.lineTo( 150,15 );
filledBar_mc.lineTo( 0,15 );
filledBar_mc.lineTo( 0,0 );

// Close shape and fill:
filledBar_mc.endFill();

Now for our hollow one.
We want this clip to appear on top of our filled bar, so our depth will be 30.

// Create our drawing MovieClip inside our container:
var hollowBar_mc = preloader_mc.createEmptyMovieClip( “hollowBar”, 30 );

// Set the Style for the outline of our rectangle:
hollowBar_mc.lineStyle( 1,0×666666,100 );

// Move our drawing clip into position:
hollowBar_mc.moveTo( 0,0 );

// Draw our rectangle ( 150px / 15px ):
hollowBar_mc.lineTo( 150,0 );
hollowBar_mc.lineTo( 150,15 );
hollowBar_mc.lineTo( 0,15 );
hollowBar_mc.lineTo( 0,0 );

We have now created our graphics. They’re not going to win any prizes for design, but they’re clear, functional and they took us seconds to make. I’ll leave the award-winning to you.

Next comes the percentage display. If you don’t want to show the user this information, you can skip this next part and go straight to centering the preloader, but it is always a good idea to keep the user as informed as possible as to what exactly is happening and not providing enough feedback could mean the difference between a user staying or leaving your site!


Step 4: Creating the percentage textfield with Actionscript.

Alongside dynamically creating MovieClips, we also have the ability in Actionscript to create textfields. In our preloader, we now need to display a percentage that shows the user how much of the movie has loaded and to do this we must create a textfield using the createTextField method.
When creating our textfield we need to specify a name, depth, position (x and y) and dimensions (width and height) and to do this we need to work out a few things beforehand.

  • Name. This is up to you – in this case, I’ll just call it ‘percentDisplay’, but the more obvious your naming of objects and variables in your code, the better.
  • Depth. We need the percentage to appear above the rest of the graphics, so it’ll be 40.
  • Position. The percentage will be centered on the hollowBar graphic, so we will use its position and dimensions to center the textfield.
  • Dimensions. We only need a small area to display the percentage, so think about the largest possible string that we will have to display. In this case it will be “100%”,
    so as long as this fits, we will be fine.

NOTE: With naming conventions, you won’t readily notice the difference on smaller projects, but in larger, more complex applications, keeping names self-explanatory and easy to understand will help you immensely when it comes to working on sections of code that you may not be familiar with or simply haven’t touched for a while.

// Find our X position from hollowBar’s _x position and _width:
var textFieldX = filledBar_mc._x + ( filledBar_mc._width/2 ) – 26;

// Find our Y position from hollowBar’s _y position and _height:
var textFieldY = filledBar_mc._y + ( filledBar_mc._height/2 ) – 8.5;

// Create our textfield:
preloader_mc.createTextField( “percentDisplay”,31,textFieldX,textFieldY,50,15 );

// Take a reference to our new textfield for easy reference:
var percentDisplay_txt = preloader_mc.percentDisplay;

// Set Text to be unselectable:
percentDisplay_txt.selectable = false;

Now we have a textfield, we can apply style to the text (font,size,colour,etc) by using a TextFormat object. The TextFormat object gives us the ability to apply a style to a textfield or portion of text.

// Create a new TextFormat Object:
var myTextFormat = new TextFormat();

// Set the Text alignment:
myTextFormat.align = “center”;

// Set the Text font:
myTextFormat.font = “Verdana”;

// Set Text size:
myTextFormat.size = 10;

// Set Text colour:
myTextFormat.color = 0x003300;

// Apply the TextFormat to our textfield:
percentDisplay_txt.setTextFormat( myTextFormat );


Step 5: Centering the Preloader on the stage.

Having graphics on the stage is fine, but let’s make it look a little cleaner and align our preloader to the center of our movie.
We can do this by taking our movie’s current width and height, finding the center point, finding the center point of our preloader and matching the two together.

// Store our Movie’s width and height in two variables:
// Replace with your movie’s dimensions:
var movieWidth = 400;
var movieHeight = 300;

// Find the preloader’s new X position using the Stage width:
preloader_mc._x = Math.round( movieWidth/2 – preloader_mc._width/2 );

// Find the preloader’s new Y position using the Stage height:
preloader_mc._y = Math.round( movieHeight/2 – preloader_mc._height/2 );


Step 6: Writing the function to collect data.

OK. Now we have taken care of the graphical elements of our preloader, we need to start thinking about how it’s all going to work. We will need to montior the amount of data we’ve already loaded and update our graphics accordingly. As the code that will do this will have to execute over and over again, we can simplify our code by encapsulating the commands into a function. Using functions has the effect of cleaning up code considerable and, with proper naming conventions again, can make code a lot more readable to other users.

In this case we are going to take several lines of code that gather information and perform a calculation with that data and stick them all into a function called ‘getPercentageLoaded’. Not only are we cleaning up the code, but we are also letting others know exactly what our code does simply by encapsulating it in a well-named function.

The information we’re after here are will be provided by the methods: getBytesTotal and getBytesLoaded. They are simple to use and return the relevant amounts of data in bytes.

NOTE: Remember that if you ever want to obtain an accurate number of kilobytes from a bytes value, you must divide by 1024
i.e. var kilobytes = bytes/1024;

// Create our function:
function getPercentageLoaded(){

  // Get total bytes and loaded bytes of our movie:
  var total = this.getBytesTotal();
  var loaded = this.getBytesLoaded();

   // Create percentage and return result:
  var percentage = Math.ceil( loaded / total * 100 );
  return percentage;
}

You will notice above that the last statement in the function is ‘return percentage’. If you’re not familiar with functions, what this does is to pass the variable we have just created inside the function (percentage) back out to the code where the function was called. This will become clearer in the next section, where we put everything together, call the function and use it’s output.


Step 7: Putting it all together.

All that’s left to do now is to write the actual logic of our process. We have our data gathering function and our graphics that are ready and waiting to be manipulated to give our user some valuable feedback and now we need to look at how our movie is actually going to play.

The first thing we want to do is to stop the movie, then we will use the onEnterFrame event handler to control our preloader. The onEnterFrame event is fired each time the movie enters a new frame and by attaching an onEnterFrame function to any movieclip (including the main timeline), we know that the code inside our function will be executed once every frame. Here we will attach the function to our ‘preloader_mc’ movieClip that we created earlier.

// Stop playback:
stop();

// Create our event handler:
preloader_mc.onEnterFrame = function(){

  // Call our function and store result:
  var percent = _root.getPercentageLoaded();

  // Set filledBar size as per our percentage:
  this.filledBar._xscale = percent;

  // Display percentage text in our textfield:
  this.percentDisplay.text = percent + “%”;

  // Check to see if our movie’s loaded or not:
  if( percent > 99 ){

    // Hide preloader graphics:
    this._visible = false;

    // Stop this onEnterFrame loop:
    delete this.onEnterFrame;

    // Play the main timeline:
    _root.play();
    }
}

…and there you have it. This is a movie preloader that you can use again and again. To add this to a movie, just paste it into the first frame of your movie.