In this detailed tutorial made for Flash 8, you will see how easy it is to create a preloading system that is gradually displaying an image as your site loads. I will show you the following:
- How to import an image into Flash,
- How to create a rectangular movie clip and turn it into a mask,
- How to write ActionScript that will power the preloader and more.
You can see the example of what you will learn with this lesson below. This is only an animation showing what the preloader will look like at the end, it is not the actual preloader that you will be building in this tutorial.
Importing the image and centering it on the stage
1 Open a new Flash document.
2 Select Modify > Document. In the window that opens, find the Frame rate field and enter 30 inside it. This means that your SWF movie will have a speed of 30 fps, or frames per second. This is a good frame rate for any self-respecting Flash movie :). Actually, I will explain you later why this had to be done.
3 Download the image I made for this tutorial. Right-click on the image below, select "Save picture as..." and save it somewhere on your hard disk where you'll quickly find it.
4 Select File > Import > Import to Stage. In the Import dialog that appears, find the image you just saved a moment ago, select it and click Open. The image will appear on your document's stage.
5 Using the Selection tool (V), click on the image to select it.
6 Open the Align panel by selecting Window > Align. To nicely center the image on the stage, click the button for aligning objects in relation to the stage (see 1 below). Now click the button for horizontal centering (2) and after that the one for vertical centering (3).
7 Call the current layer bottle and lock it.
8 Create a new layer and call it rectangle mask.
In the section that follows, you will proceed to make a rectangle, convert it into a movie clip symbol and make a mask out of it. Onwards!
Making the rectangle movie clip that will mask the image
9 Select the Rectangle tool (R). You will draw a rectangle without the outline colors. To do this, go to the Colors area of the Tool panel. Click on the small pencil icon to select the Stroke color (see 1 in the image below). Next, click on the middle icon in the last row (2) to block the selected color. There. It is now possible to draw a rectangle without its surrounding frame.
10 Click somewhere above and to the left or right of the bottle image and start dragging your mouse. Make a small rectangle, regardless of the proportions. You will fix that soon.
11 Unlock the bottle layer.
12 With the Selection tool (V), click on the rectangle to select it. Now hold Shift and click on the bottle to select it too. As you can see, selecting multiple objects on different layers is perfectly possible.
13 You will need the Align panel again (shortcut key: Ctrl+K). Now, turn off the Align/Distribute to stage button. It is shown turned off in the image below (1).
Next, click the Match width and height button (2). This will instantly make the rectangle's dimensions the same as those of the image.
14 Lock the bottle layer again, because you won't be needing it anymore.
15 With the rectangle still selected, use the Align panel once more. You need to center the rectangle on the stage - do this like you did it with the image in step 6:
- Turn on the button for Aligning objects to stage,
- Center the rectangle horizontally,
- and then vertically.
There! Everything is in its proper place now.
16 Your rectangle should still be selected. Select Modify > Convert to Symbol (shortcut key: F8). You will make a movie clip out of this shape, so be sure to select the right option (1).
Now, this is important for good functioning of your preloader: Make sure to select the middle rectangle in the bottom row of the Registration point schema (see 2 above). This is necessary in order to be able to stretch the rectangle movie clip from the bottom up, so that the image of the bottle "fills" properly.
Every visual transformation made to a movie clip via ActionScript is done in relation to its registration point. Don't get confused with the presence of the other point of rotation and transformation, which is used by the Free Transform Tool (Q), when you are rotating and transforming your symbols manually with it. The image below (with black background to see more clearly the difference between the two) shows both points: the point marked with number 1 is used by ActionScript - this is the registration point. The other one, marked with number 2, is the center of all rotations and transformations made with design tools. It is easy to see the difference: the first one has the shape of a small cross, while the second one is a hollow circle.
Lastly, name your new symbol: call it rectangle and click OK.
17 Now that you have created the movie clip that will act as a mask for the image below it, keep it selected and go to the Properties inspector below the stage. On its left side, you will find the Instance name field. Enter the name for your movie clip here: rectMask_mc.
Without the Instance name, you wouldn't be able to control this movie clip via ActionScript. The movie clip's Library name, rectangle, isn't important at all when programming with ActionScript. It exists to differentiate between the symbols in the Library.
18 Lock the rectangle mask layer. Right-click on it and select Mask from the menu that shows up. You should see the icons of the layers change: the rectangle mask layer has become the masking one, and the bottle layer beneath it the masked one.
Also, you should see the image of the bottle appear, meaning that the masking was done successfully.
You will now see how to create the outline for the bottle and add some dummy content to your preloader, just to be able to see if it works correctly.
Drawing the outline for the bottle
19 Make a new layer and call it outline.
20 Select the Line tool (N). Go to the Properties inspector and select hairline as line type (1).
Next, click on the small colored square (2). In the color palette window that will show up, choose black as color - its hex code is #000000 (3). Lower its alpha to 60% (4).
Pure opaque black would be too much of a contrast here. By lowering its alpha (transparency), you make it blend in much better with the overall look of the preloader.
21 Click somewhere near the left bottom part of the bottle - close to it but not inside it, and start dragging upwards. Zoom in if necessary to work more easily and to be more precise.
In case that your line is snapping to some nearby point, just turn off the Snap to objects option. It is the little magnet icon found at the bottom end of the Tools panel . You will be able to draw freely once you have turned it off.
Once you have reached the upper curve of the bottle, release your mouse button. You should have a nice line following the left side of the bottle drawn.
22 Turn on snapping to objects again (remember the little magnet icon), so that you can continue drawing from the last point. Zoom in again. Do the following (the sequence is clearly shown in the image below):
- Using the Line tool (N), bring your mouse near the end of the line that you have drawn previously.
- Click and start dragging - the new line will automatically begin at the end of the previous one.
- Draw a line that goes to the point where the curve of the bottle ends.
- Choose the Selection tool (V) and bring the cursor somewhere near the middle of the new line. A small curve will appear near the arrow, indicating that this line can be turned into a curve now (see the middle image below).
- Click and start dragging up and to the left - once you have obtained a good, smooth curve that follows the outline of the bottle, release the mouse button.
You can continue drawing the outline by using the Line and Selection tools, or you can do it with the Pen tool (P). To see a good explanation on the use of the Pen tool, check out the first page of my tutorial on making a camera focus change effect in Flash, steps 11 through 20.
You can stop once that you have drawn half of the outline. Since the bottle in the image is almost symmetrical on its vertical axis, this is sufficient. Just add the curve at the bottom, and you should have a result similar to the onw shown below:
23 Flash offers you numerous ways of doing the same thing in a different manner. So, instead of drawing the complete outline, do the following (the numbers in the list are the same ones on the image below):
- Select the half of the outline you have drawn so far, using the Selection tool (V).
- Press Ctrl+C to copy it, then press Ctrl+Shift+V to paste it in place. The new copy of the vector outline will be placed exactly on top of the original. Don't click anywhere, otherwise this new copy will merge with the original. Instead, just hold Shift and press the right arrow key to move the outline to the right.
- While the outline copy is still selected, select Modify > Transform > Flip Horizontal to make a mirror image of it.
- Select the Selection tool (V), bring your mouse close to the right outline's top point, click and start moving it until you reach the left half. A small circle will appear, indicating that the two halves are ready to snap into place, becoming one. To do this, you must have the Snap to objects option turned on, of course.
If you are not completely satisified with the merging of the two outlines, use the Selection tool to tweak them where necessary, until it looks good. Also, move the right part of the outline (while it is selected) with the left and right arrow keys until it fits nicely.
Adding content to the Flash document to test the preloader
24 Lock the outline layer. Create a new layer and call it site content.
25 Right-click on frame 10 of this new layer and select Insert Keyframe from the contextual menu that will appear.
The content of the site has to come after the first frame in your movie. Why, you may ask? Well, if you place it in the first frame, your web site visitors will see a blank screen instead of the preloader which will indicate that your Flash movie is loading. You will stop your movie from playing via ActionScript later, and thus the preloader will load instantly or in a few seconds (depending on the speed of your visitors' Internet connection). After all, this is the only purpose of the preloader: to show your users that your site isn't dead or malfunctioning, but that they just have to wait a little bit.
26 Select File > Import > Import to Stage (shortcut key: Ctrl+R). Browse your computer and find an image (JPG, GIF or PNG) that has about 100 KB. Select it and click Open. The little circle in the second keyframe you just inserted a few moments before has become black, meaning that some content is present here.
This image that you have inserted inside your Flash document serves for testing purposes only - to see if the preloader works as it should. If you have real content ready you can put it inside, but I recommend that you test your preloader first, and if everything works out fine, replace the dummy content with real one.
Adding the ActionScript code that powers the preloader
27 Lock the site content layer. Make a new layer above it and call it actions. Click on its first keyframe to select it for ActionScript input. Actually, this is the layer's only keyframe, all the other ones are simple frames.
You may have noticed that the duration of the actions layer is the same as the one of the site content layer. This is perfectly normal - when you add a new layer in Flash, it has as many frames as the "longest" layer created before it.
28 Select Window > Actions (shortcut key: F9). The Actions panel will show up. Enter the following ActionScript code inside it:
stop();
rectMask_mc._height = 1;
this.onEnterFrame = function():Void {
var loadedData:Number = this.getBytesLoaded();
var allData:Number = this.getBytesTotal();
var percent:Number = Math.round(loadedData/allData*100);
rectMask_mc._yscale = percent;
if (loadedData >= allData) {
gotoAndStop(10);
delete this.onEnterFrame;
}
};
29 Test your movie. You should see the image appear instantly. This is because you are testing your movie locally, meaning on your computer and not on the Web. To see how it would load over the Web, still in the test movie window, select View > Simulate Download. You should now see the movie loading progressively, as it will on the Web.
If you want to select a certain download simulation speed, go to View > Download Settings. You have various options there, ranging from a stone-age 14.4 K modem speed, up to fast broadband connections. Select the standard 56K modem speed to see how a user having that kind of connection would experience your site loading.
During the first two seconds probably nothing will appear because the first frame of this movie weighs about 8 KB. If you are making a full-fledged Flash site that takes some time to load, it is meant for users with a fast link to the Internet, in which case they won't have to wait, because the preloader will appear immediately. If you want to implement this preloader to a site that is built, among others, for users with slower connections, you should lower the quality of the image that is slowly appearing, because lowering its quality (during export in Photoshop or Fireworks) cuts down on its file size.
The size of the first frame of your movie (in kilobytes) is important, because if it is too big, the wait for the preloader alone to appear will take some time, which is bad. Users may just click the back button on their browsers and never come again, thinking your web site isn't alive at all. How can you check how much kilobytes does the first frame of your SWF movie weigh? Easy. While in test movie mode, select View > Bandwidth Profiler. You will see the following graph appear:
The column in the graph marked with 1 is the first frame of your movie. Every frame has its own column, which shows its particular size in kilobytes (KB). The first one weighs 8 KB. This is mostly because of the file size of the image, which weighs around 7 KB. That's why you have to lower the weight of the image if you want the preloader to appear more quickly. Both the ActionScript code and the vector outline you drew weigh no more then 1 KB.
The last keyframe weighs the most, with its size being about 100 KB. Depending on the file size of the image that you have imported in your movie to simulate some content, your column for frame 10 will differ from the one shown above. Every other frame between the first and last ones weighs zero kilobytes, because they are all completely empty.
Let me show you now how this gizmo works 🙂 !
Explaining the ActionScript code behind the preloader
The first line of code stops your Flash movie from playing:
stop();
The second one makes a change to the visual appearance of the rectangle movie clip (which is a mask, remember):
rectMask_mc._height = 1;
The _height
property defines the height of an object in pixels. The above line shrinks the rectMask_mc
movie clip to the minimum possible value: one. This is done so that none of the image of the bottle is visible at the start of preloading, which makes perfect sense, since the movie has just appeared and the content of the site has yet to load at all.
Now comes the piece of ActionScript that sets the preloader in motion:
this.onEnterFrame = function():Void {
var loadedData:Number = this.getBytesLoaded();
var allData:Number = this.getBytesTotal();
var percent:Number = Math.round(loadedData/allData*100);
rectMask_mc._yscale = percent;
if (loadedData >= allData) {
gotoAndStop(10);
delete this.onEnterFrame;
}
};
Inside the top line of this chunk of code, you can see a special ActionScript keyword: onEnterFrame
. This keyword refers to a special kind of event. Events in Flash are things that happen: a user pressing or moving his mouse, a sound being loaded, etc. While most of the events in Flash happen via some form of user interaction with your movie or during timeline playback, the onEnterFrame
event happens only when you make it so by writing it in ActionScript.
The event in question works in the following way: it executes all that is contained within itself as many times per second as the speed of your movie tells it to. This means that if your movie has a speed of 30 fps (you have set this speed at the very outset of this tutorial, remember), the onEnterFrame
event will fire 30 times in a second. And what will it execute this many times per second? To understand this, let's analyze the line of code it lies in:
this.onEnterFrame = function():Void {
The ActionScript keyword this
denotes the timeline it is sitting on. Since it is placed on the main or root timeline in this case, it is pointing to the SWF movie itself and not some movie clip or anything else. So, the construct this.onEnterFrame
means the onEnterFrame
event that is assigned to the main movie (the SWF file itself). You can choose any movie clip to attach this event to, but I have just decided to use the main timeline.
The code that follows says that a function
is assigned to this event. The result of this construct makes this function execute at the speed of the onEnterFrame
event, i.e. the speed of your movie. Thirty times in a second in this case.
The keyword Void
tells Flash that this function returns no value. Unlike this one, some functions do, like a number or a string of text, for example.
You assign a function to an event via the assignment operator (=
), which should not be confused with the equality operator, which is written as two equals signs (==
), and is actually used to check if two values are equal.
And finally, the code that gets executed at this speed is the code placed between the function's curly brackets - {
and }
. Let's examine it in more detail. Here it is:
var loadedData:Number = this.getBytesLoaded();
var allData:Number = this.getBytesTotal();
var percent:Number = Math.round(loadedData/allData*100);
rectMask_mc._yscale = percent;
if (loadedData >= allData) {
gotoAndStop(10);
delete this.onEnterFrame;
}
The first line looks up the amount of data that has been loaded so far and stores it in a variable that I chose to call loadedData
:
var loadedData:Number = this.getBytesLoaded();
The getBytesLoaded()
method is used to see how much of a SWF movie has been loaded up to that moment. You can see that the keyword this
is used once more, this time to tell Flash that it should check how much of the timeline this piece of ActionScript code resides in has been loaded so far - again meaning the SWF file itself.
Once this data is retrieved (note that this is a numerical value, the amount of bytes loaded so far), it is stored in a variable. When defining a variable in ActionScript 2.0, you must put the keyword var
in front of its name, and the type of data it will store after a colon (:
) that follows the name. Since the amount of bytes that have been loaded so far is a numerical one, you must put the keyword Number
here. To translate ActionScript into English:
var loadedData:Number
means the variable called loadedData will store a numerical value. Ok, the next line does a similar thing:
var allData:Number = this.getBytesTotal();
It looks up the total amount of data that has to be loaded, via the getBytesTotal()
method and than stores it in a variable that I named allData
.
To be able to put the preloader at work, you need both pieces of information - the amount of your SWF movie that has been loaded (this information is read by Flash each time the onEnterFrame
event fires and the function that is assigned to it gets executed) and the complete size of your SWF movie. From these two, you will be able to pull out the percentage of your movie that has been loaded, via a simple mathematical formula. All of this is contained in the following line of code:
var percent:Number = Math.round(loadedData/allData*100);
To obtain a percentage, you must divide the part by the whole and then multiply the result by 100: loadedData/allData*100
. The result of this simple operation is then rounded with the round
method of the Math
object. This is made because you will need round numbers to resize the rectangular mask movie clip properly. Finally, this data (the percentage) is stored in the percent
variable, which is of course a numerical one.
Now comes the beauty of it all: scaling the rectangular mask movie clip according to the percentage of your movie that has been loaded so far:
rectMask_mc._yscale = percent;
The _yscale
property of the rectMask_mc
movie clip will be the same as the number stored in the percent
variable (which is the percentage of your SWF that has been loaded up to this point). Let me explain you now what is this _yscale
property: it serves to resize the height of a movie clip in relation to its original height. The _height
property of a movie clip is its height expressed in pixels. The _yscale
property is its height expressed as a percentage value.
An actual example is the best way to clarify this: let's suppose that you have a movie clip that is 200 pixels high. When you created this movie clip, its original height of 200 pixels is considered to be from that moment on its _yscale
property at 100%. Later, if you want to change its height via ActionScript, you can do it in two ways: via the _height
property, by writing something like this:
myMovieClip._height = 100;
or via the _yscale
property, like this:
myMovieClip._yscale = 50;
The result is the same: the movie clip's height is cut down in half, the only difference being that a pixel value is used in the former, and a percentage value in the latter. Keep in mind that in both cases only the number is written, you never write the percentage sign, pixels or anything else. Flash knows what you are talking about! 🙂
To go back to the preloader, the _yscale
property is used because it will scale the height of the masking rectangle exactly by the amount of your movie that has been loaded so far. In plain English, if half (50%) of your movie has been loaded, the height of the rectangle mask will be exactly 50%, revealing just half of the image beneath it! Once the movie has fully been loaded, the height of the mask will be 100%, showing all of the bottle in the image below. All of the bottle can be seen - your movie has been completely loaded! Now ain't Flash great? 🙂
Flash has to know if everything has been loaded so it can proceed to the frame where the site content is placed. You will help him to decide if it can do that or not via a simple conditional statement:
if (loadedData >= allData) {
gotoAndStop(10);
delete this.onEnterFrame;
}
In plain words, the above conditional statement translates as the following:
if (this condition shows as being true) {
run all the code contained here
}
If this condition evaluates as false, the code between the curly brackets will simply be ignored and Flash will skip it as if it didn't exist at all. And this particular condition checks if the amount of your movie that has been loaded so far is greater than or equal to your movie's total size (these values are being looked up in the variables that keep them: loadedData
and allData
). It makes sense, doesn't it? Check this out:
User: Hey, Flash, can I see the site now?
Flash Player: Wait, let me see... I have loaded 100,000 bytes so far... and the movie's total size is 400,000 bytes. 100,000 is less than 400,000. I am sorry, but you will have to wait a little bit more. Don't worry, I will tell the preloader to show you how much more you have to wait.
User: That's no problem, I want to see this awesome site, so I'll wait.
Flash Player: Dude, that is so cool. Can't wait to show it to you!
Now that this little drama has explained the meaning of a conditional statement to you :), let me show you what gets executed once the condition evaluates as true. The first line,
gotoAndStop(10);
sends the playhead flying over to frame 10 and it stops it there. The Flash site is seen now by the user in all its glory. The next line,
delete this.onEnterFrame;
does an important thing. It deletes the onEnterFrame
event. Bye bye onEnterFrame
! Seriously, this has to be done, otherwise it would go on and on until the user leaves the page your SWF movie is displayed on. And this event gets executed 30 times per second in this example. By deleting it, you free some memory space on the user's computer and also put a less load on its processor.
Always remove the code that isn't of any use any more. Even if the functions and events that are being run don't seem to be putting much load on the processor and don't occupy much memory space, delete them if they don't have a purpose to exist. This is how great user experiences are made, by paying attention to the smallest detail. And I want to teach you exactly this, among many other things.
So if you are interested in many more ways that preloaders can be made, check out my Flash preloading tutorials on this subject. Bookmark my site, because you'll come back for more new Flash tutorials that are going to be posted here. And good luck!
Download the source FLA file for the preloader explained in this lesson.
The tutorial was definitely very helpful for my academic assignment, but I was wondering how to code should look for Flash CS6 version. For example, there is no _height property any more, but DisplayObject.height. Also, I could not find the View > Simulate Download. I would be grateful if anyone could help. Thanks in advance and happy holidays.
Hi
I love the tutorial, but would love it even more if it worked.
I am using Adobe CS6 Action Script 3, and the code you give does not work.
Do you have coding for this in CS6?
Thanks so much!
🙂
this is a fab tutorial…
im very sketchy at this, how do i link it to my main swf file..?? i already have a swf file created in after effects cs5… i exported to swf but want to have this as the preloader…. any idea?
It’s not working in AS3. allso downloaded the source and still not working.
Don’t know why exactly
But thanks for the explanations tough