29 November 2010
General experience using Flash and ActionScript 3.
Beginning
This Quick Start describes several strategies you can use that leverage ActionScript 3 to dynamically load images and assets from your Library, as well as from local and remote locations. When you use ActionScript, you have complete control over when and how assets will appear at runtime, and you can use scripts to determine which image asset is loaded programmatically. In other words, you can use ActionScript to add images to timelines or display containers, and then change their display dynamically using code and event handlers.
Note: While working in the Flash Professional authoring environment, you can drag image instances from the Library to the Stage and have them appear in the output SWF file. When you add images using ActionScript, you really are adding the image to an instance of the Timeline. Specifically, frames are part of the Timeline, and you can associate ActionScript code with a frame using the Actions panel. So, the Timeline becomes the parent of the display objects added using ActionScript, unless another display object container is specified (as described later in this article).
This Quick Start article explains how to add assets that exist in your Library, and how to load assets from a local folder on your hard drive or from a remote URL using ActionScript 3.
All display items (graphics, movie clips, and other SWF files) must be added to what is called the "display list" in our ActionScript documentation in order to appear in the SWF file output. Basically, the display list is a hierarchy of items that can be displayed to the user during runtime, and the hierarchy helps determine the relationship of the display items to one another. In ActionScript, you use the addChild() command to add a display item to the display list. You can use addChild() on the current Timeline or the Timeline of another target instance. Additionally, you can use addChild() on a display container, which becomes basically a "parent" display object. Changes that you make to a display container, such as resetting its position, can also change the display of the "children" inside that container.
Note: The Stage class is a subclass of DisplayObjectContainer, but we don't recommend using the syntax Stage.addChild() in your scripts. The best practice is to use addChild() or DisplayObjectContainer.addChild() to add items to the display list for flexible and predictable management of your display objects.
The following example from bee.fla takes a movie clip named bumblebee from the Library and creates an instance of it on the current Timeline:
Name: bumblebee
Type: Movie Clip
Note: An ActionScript class is necessary for this to work, so this is the desired behavior. However, it is important to understand that classes automatically generated by Flash Professional are not editable; they are available only for the Flash authoring tool to use when it publishes the SWF file.
var
mybee:bumblebee = new bumblebee();
addChild(mybee);
Result
To download the source files for this and all examples, download the loading_images_library.zip sample files at the top of this page. The Flash Professional CS5 versions of the FLA files have file names that end with "_CS5".
In the code example shown in Step 8, the first line uses the var statement to assign a name to the instance of the bumblebee movie clip. The second line uses the addChild() command to add the instance mybee to the display list. When a display container is not specified (as in the above example), the movie clip instance is added to the Timeline of the current frame.
In other words, you have two options for adding the movie clip:
addChild(mybee): Adds the movie clip instance named mybee to the Timeline at the current frame.myContainer.addChild(mybee): Adds the move clip instance to the myContainer object instance of the DisplayObjectContainer class. The movie clip for mybee is not added to the display list until myContainer is added to the display list using addChild(). An example of how to achieve this option is shown in the next section.Now that you've added the movie clip instance to the Timeline, you can assign properties to it with ActionScript and even create dynamic content. See the provided movingbee.fla file for an example of a bumblebee that moves in relation to the user's mouse. The movingbee.fla file uses event handling and function statements. Review the code in the Script window by opening the Actions panel. You can learn more about writing event handlers and functions by reading the ActionScript 3.0 Developer's Guide in the online Flash Professional documentation or by reviewing Event handling in ActionScript 3.
The following is an example showing drag-and-drop of the movie clip. Drag the bee with your mouse; when you mouse up, the bee will stop following the pointer. See the provided drag_and_drop_bee.fla file for the ActionScript. Open the Actions panel to review the code in the Script window.
To download the source files for this and all examples, download the loading_images_library.zip sample files at the top of this page. The Flash Professional CS5 versions of the FLA files have file names that end with "_CS5".
DisplayObjectContainer objects (and objects created by the classes that inherit from the DisplayObjectContainer class) can contain zero or more display items. As you move the container, all the display items in the containing object move relative to the container.
In the provided example beeContainer.fla, the bumblebee movie clip instance myBee is a child of the Sprite object named mySprite. You can use a Sprite object as a display container because the Sprite class inherits from DisplayObjectContainer class.
Download and open beeContainer.fla to review the code example on Frame 1:
var myBee:bumblebee = new bumblebee();
//create a display object that can be the container for myBee
var mySprite:Sprite = new Sprite();
//add myBee as a child of mySprite
mySprite.addChild(myBee);
//add mySprite to the display list
addChild(mySprite);
stage.addEventListener(MouseEvent.CLICK, clickhandler);
//move the container mySprite after a mouse click
function clickhandler(e:MouseEvent):void {
mySprite.x = 100;
mySprite.y = 100;
}
Note: Remember to add the display object container to the display list. In the above example, the display object container is added to the display list with this line:
addChild(mySprite);
While this reminder might seem obvious in a simple example, the more display objects and display object containers you create, the easier it is to forget this step. If you have trouble getting display objects to appear when you test your SWF file, check to make sure you have added the correct display object containers to the display list.
Follow these steps to add the bumblebee movie clip to a container:
Result
To download the source files for this and all examples, download the loading_images_library.zip sample files at the top of this page. The Flash Professional CS5 versions of the FLA files have file names that end with "_CS5".
Flash Player plays the SWF file. By default, the bumblebee movie clip is displayed in the upper left corner of the Stage. An event listener in the code is set to respond to mouse clicks, so when you click anywhere on the Stage, the bumblebee movie clip's registration point is repositioned to a location that is 100 pixels from the top and 100 pixels from the left side of the Stage.
Flash Professional CS4 treats images in the Library as BitmapData objects, which means that image instances, compared to movie clip instances, are a bit trickier to create dynamically. As the name implies, a BitmapData object contains information about each pixel in a bitmap—the data for generating a bitmap image. However, instances of the BitmapData class are not display objects (see flash.display.BitmapData for more information) and the BitmapData class does not inherit from the DisplayObject class. You can't add a BitmapData object to the display list. So, in order to place an instance of an image from the Library on the Timeline, you first need to create a Bitmap object (see the flash.display.Bitmap documentation). Bitmap objects do inherit from the DisplayObject class, and you can use them to reference the BitmapData information. Bitmap objects are display objects that reference the BitmapData object's image data, and the bitmap object can be added to the display list.
In other words, the critical points are as follows:
The following example describes how a bitmap image from the library is added to the display list. This example is illustrated in the addbee.fla sample file.
Note: When you import the PNG file, a graphic symbol named Symbol 1 is automatically also added to the Library.
// myBitmapData is the class name for the BitmapData symbol
// in the library.
// Create a new myBitmapData object instance called
// myBitmapDataObject:
var myBitmapDataObject:myBitmapData = new myBitmapData(100, 100);
// Create a bitmap object instance called myImage to
// contain the bitmap data:
var myImage:Bitmap = new Bitmap(myBitmapDataObject);
// Add myImage to the display list of the current Timeline
addChild(myImage);
Note: In Flash Professional CS4, you need to provide the width and height of the bitmap image in ActionScript, even though it is already set in the Library asset. Oddly enough, while these values are required, Flash Professional CS4 also ignores them. If you try to change the width and height values in the new BitmapData(width, height) statement, Flash Professional CS4 ignores them and the dimensions remain the same. The bitmap image's size is defined by the image in the Library, and the size of the instance on the stage is based on the actual size of the image in the Library. Flash Professional CS5 does not require you to provide width and height values.
Result
To download the source files for this and all examples, download the loading_images_library.zip sample files at the top of this page. The Flash Professional CS5 versions of the FLA files have file names that end with "_CS5".
Flash Player plays the SWF file, and by default the bumblebee.png bitmap image is displayed in the upper left corner of the Stage. When you publish the SWF file, Flash Professional automatically creates a class for the BitmapData object. As mentioned previously, the class generated by Flash Professional is not editable and is only available for Flash Professional to use when it publishes the SWF file.
Also, remember that there are many ways to achieve the same goal by writing slightly different code. You can choose to write more concise ActionScript if desired. For example, the previous code sample contains clearly defined steps that can be reduced to the following single statement:
addChild(new Bitmap(new myBitmapData(100, 100)));
External images (such as an image file that exists on your local machine or has been uploaded to a remote domain) are referenced directly as BitmapData object instances. As mentioned previously, you can't add a BitmapData object instance to the display list, so you need to create a display object (an instance of a class that inherits from the DisplayObject class) to reference the bitmap data. The display object is then added to the display list.
The previous section describes how to use a Bitmap object instance to reference the bitmap data, and then how to add the Bitmap object instance to the display list. To reference an image file that exists outside of the Library in the current document, you begin by creating a new Loader object instance. The Loader class is very useful because it inherits from the DisplayObject class (see flash.display.Loader), and you can add Loader object instances to the display list.
The following example shows how an image from the local file system is added to the display list using a Loader instance. This example is illustrated in the addFlowersLoader.fla sample file.
Download the addFlowersLoader.fla file, open it, and review the code in the Script window that is located on Frame 1 of the Timeline:
//create a Loader instance
var myImageLoader:Loader = new Loader();
//create a URLRequest instance to indicate the image source
var myImageLocation:URLRequest = new URLRequest("flowers.jpg");
// load the bitmap data from the image source in the Loader instance
myImageLoader.load(myImageLocation);
// add the Loader instance to the display list
addChild(myImageLoader);
Now follow these steps:
Result
To download the source files for this and all examples, download the loading_images_library.zip sample files at the top of this page. The Flash Professional CS5 versions of the FLA files have file names that end with "_CS5".
When Flash Player plays the SWF file, the flowers.jpg bitmap image is displayed by default on the Stage. Since the ActionScript is loading an external image file, it is imperative that the filename and the file's location match the path provided as a parameter of the new URLRequest, as specified in this line of code:
var myImageLocation:URLRequest = new URLRequest("flowers.jpg");
Note: You could also place the external file in a subfolder within the directory that contains the Flash file. The following code would load the flowers.jpg file that exists in a subfolder named images:
var myImageLocation:URLRequest = new URLRequest("images/flowers.jpg");
While the previous example is simple and functional (and you can continue to create new Loader object instances each time you add an external image), there are other, more robust strategies you can use. Creating Loader objects that are more flexible and efficient requires a thorough understanding of the loading process.
Within the Loader object instance, the bitmap data from the referenced image is placed within a Bitmap object. Loader objects load images as bitmap data, but then place the data in a Bitmap object (again, a Bitmap object references a BitmapData object). The Bitmap object instance is the content (child) of the Loader object instance. The hierarchy for this structure looks like this: Loader object > Bitmap object > BitmapData object.
The Loader is now the primary display object for the image data. Information about the referenced image, such as its URL or any query variables with which it was loaded, can be accessed with ActionScript through the contentLoaderInfo property of the Loader object.
Note: Properties like width and height are not accessible for the loaded image, or the loader that is loading the image, until the flash.display.LoaderInfo.init event is dispatched. If you try to get or set the width or height after the addChild() statement, you'll get 0 (and setting the property won't work) because time is required to read the file off a local or remote file system. So, set properties for the loaded image within a LoaderInfo.init or LoaderInfo.complete event handler.
The following example is far more complicated than the previous one, but it shows that the bitmap data is image data (not an instance of the image itself) contained within a Bitmap object instance. And, it also illustrates that the Bitmap object instance is the child of the Loader object instance. This example uses a single Loader object instance to reference a single image's bitmap data, and then reuses the image data to create several Bitmap object instances on the Stage. As a result, you can manipulate each Bitmap object instance independently and gain more control.
Note: Changes to the BitmapData object instance, such as changes resulting from the use of methods like BitmapData.setPixel() or BitmapData.draw(), are reflected in each Bitmap object instance that references the BitmapData object instance.
This example simply makes one call to the external image. After the data is initially loaded, Flash Player can reuse the image data several times. A single call to the image file is more efficient than making several calls, and this approach is especially useful when building more complex Flash applications that may reuse the same image file repeatedly. While the following example could create several Loader object instances and manipulate each Loader object instance independently, the point of this example is to show how you can take advantage of the Loader, Bitmap, and BitmapData relationship to save memory and loading time.
Specifically, the following example sets up some variables to use in the functions of the provided code. A listener is established for the LoaderInfo.complete event. The ldr.load() statement loads an external image's bitmap data (flowers.jpg) once in the Loader object instance. When the load method completes loading the image data, the Loader object instance automatically creates an internal Bitmap object to store and display the loaded bitmap data, saving that bitmap information to its own ldr.content property. However, the content property has the data type DisplayObject because a Loader object can load images and SWF files. So, the example below uses the as operator to save the image data to a custom bmp variable of the data type Bitmap. The bitmap data is then used to display five individual Bitmap object instances to form each side of a cube (except the front).
This example is illustrated in the bee_in_a_box.fla sample file. Download bee_in_a_box.fla and open the file. Review the code located on Frame 1 of the Timeline:
// Establish a variable for the external image filename
var IMAGE_URL:String = new String("flowers.jpg");
// Create a loader object to load the image data
var ldr:Loader = new Loader();
// Create variables for each instance of the image to add to the
// display list these images will form a cube, we need 5 instances:
// one for each side except the front
var bitmap1:Bitmap;
var bitmap2:Bitmap;
var bitmap3:Bitmap;
var bitmap4:Bitmap;
var bitmap5:Bitmap;
// Create a variable to hold an instance of the bumblebee movie clip
// in the library. The movie clip in the library is set to export
// for ActionScript
var mybee:bumblebee = new bumblebee();
// Set up an event listener to create instances of the image on
// the stage after the image data is completely loaded
ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, addSides);
// Load the image data from the image file
ldr.load(new URLRequest(IMAGE_URL));
// After the COMPLETE event is fired, start creating instances
// of the imported image on the stage
function addSides(evt:Event):void {
// Use the as operator to cast the loader data to a Bitmap object
var bmp:Bitmap = ldr.content as Bitmap;
// Create a bitmap instance
bitmap1 = new Bitmap(bmp.bitmapData);
// Rotate the instance to create a 3D effect
bitmap1.rotationX = 90;
// Add the instance to the display list
addChild(bitmap1);
bitmap2 = new Bitmap(bmp.bitmapData);
bitmap2.z = 400;
bitmap2.rotationY = 90;
addChild(bitmap2);
bitmap3 = new Bitmap(bmp.bitmapData);
bitmap3.z = 400;
addChild(bitmap3);
bitmap4 = new Bitmap(bmp.bitmapData);
bitmap4.z = 0;
bitmap4.x = 400;
bitmap4.rotationY = 270;
addChild(bitmap4);
bitmap5 = new Bitmap(bmp.bitmapData);
bitmap5.y = 400;
bitmap5.z = 400;
bitmap5.rotationX = 270;
addChild(bitmap5);
// Now that the sides of the cube are complete,
// add the bumblebee you add the bumblebee after
// the sides so it displays in front of the cube
addBee();
}
// This function adds an instance of the bumblebee
// movie clip from the Library to the display list.
function addBee(): void {
mybee.x = 100;
mybee.y = 100;
addChild(mybee);
}
Test the movie by choosing Control > Test Movie. Or press Ctrl+Enter (Windows) or Command+Return (Mac OS) to run the SWF file.
Now follow these steps:
Result
To download the source files for this and all examples, download the loading_images_library.zip sample files at the top of this page. The Flash Professional CS5 versions of the FLA files have file names that end with "_CS5".
Flash Player plays the SWF file. Five separate Bitmap object instances display the data from the external flowers.jpg file to form each side of a cube (except for the front face). The bumblebee movie clip from the Library is then loaded and positioned to appear in the middle of the box.
For more information about display objects and display containers—and to learn more about how visual items are managed in ActionScript, see the following chapters in the Programming ActionScript 3 for Flash online reference: