Creating movie clips at runtime 361
For example, the following code creates a new child movie clip named new_mc at a depth of
10 in the movie clip named
parent_mc:
parent_mc.createEmptyMovieClip("new_mc", 10);
The following code creates a new movie clip named canvas_mc on the root timeline of the
SWF file in which the script is run, and then activates
loadMovie() to load an external JPEG
file into itself:
this.createEmptyMovieClip("canvas_mc", 10);
canvas_mc.loadMovie("http://www.helpexamples.com/flash/images/image1.jpg");
As shown in the following example, you can load the image2.jpg image into a movie clip and
use the
MovieClip.onPress() method to make the image act like a button. Loading an
image using
loadMovie() replaces the movie clip with the image but doesn’t give you access
to movie clip methods. To get access to movie clip methods, you must create an empty parent
movie clip and a container child movie clip. Load the image into the container and place the
event handler on the parent movie clip.
// Creates a parent movie clip to hold the container.
this.createEmptyMovieClip("my_mc", 0);
// Creates a child movie clip inside of "my_mc".
// This is the movie clip the image will replace.
my_mc.createEmptyMovieClip("container_mc",99);
// Use MovieClipLoader to load the image.
var my_mcl:MovieClipLoader = new MovieClipLoader();
my_mcl.loadClip("http://www.helpexamples.com/flash/images/image2.jpg",
my_mc.container_mc);
// Put event handler on the my_mc parent movie clip.
my_mc.onPress = function():Void {
trace("It works");
};
For more information, see createEmptyMovieClip (MovieClip.createEmptyMovieClip
method)
in the ActionScript 2.0 Language Reference.
For an example source file that creates and removes numerous movie clips at runtime, you can
find a sample source file, animation.fla, in the Samples folder on your hard disk
■ In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and
Tutorials\Samples\ActionScript\Animation.
■ On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples
and Tutorials/Samples/ActionScript/Animation.