Flash As2 Learning
Flash As2 Learning
Flash As2 Learning
0
™
IN FLASH
®
© 2007 Adobe Systems Incorporated. All rights reserved.
If this guide is distributed with software that includes an end user agreement, this guide, as well as the software described in it, is
furnished under license and may be used or copied only in accordance with the terms of such license. Except as permitted by any
such license, no part of this guide may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means,
electronic, mechanical, recording, or otherwise, without the prior written permission of Adobe Systems Incorporated. Please note
that the content in this guide is protected under copyright law even if it is not distributed with software that includes an end user
license agreement.
The content of this guide is furnished for informational use only, is subject to change without notice, and should not be
construed as a commitment by Adobe Systems Incorporated. Adobe Systems Incorporated assumes no responsibility or liability
for any errors or inaccuracies that may appear in the informational content contained in this guide.
Please remember that existing artwork or images that you may want to include in your project may be protected under copyright
law. The unauthorized incorporation of such material into your new work could be a violation of the rights of the copyright
owner. Please be sure to obtain any permission required from the copyright owner.
Any references to company names in sample templates are for demonstration purposes only and are not intended to refer to any
actual organization.
Adobe®, Flash®, FlashHelp®, Flash® Player, JRun™, Macromedia® and Shockwave® are either registered trademarks or trademarks of Adobe Systems
Incorporated in the United States and/or other countries.
Macintosh® is a trademark of Apple Computer, Inc., registered in the United States and other countries. Windows® is either a
registered trademark or a trademark of Microsoft Corporation in the United States and/or other countries. All other trademarks
are the property of their respective owners.
Sorenson Spark™ video compression and decompression technology licensed from Sorenson Media, Inc.
Flash CS3 video is powered by On2 TrueMotion video technology. © 1992-2005 On2 Technologies, Inc.
All Rights Reserved. http://www.on2.com.
Adobe Systems Incorporated, 345 Park Avenue, San Jose, California 95110, USA. Notice to U.S. Government End Users. The
Software and Documentation are “Commercial Items,” as that term is defined at 48 C.F.R. §2.101, consisting of “Commercial
Computer Software” and “Commercial Computer Software Documentation,” as such terms are used in 48 C.F.R. §12.212 or 48
C.F.R. §227.7202, as applicable. Consistent with 48 C.F.R. §12.212 or 48 C.F.R. §§227.7202-1 through 227.7202-4, as
applicable, the Commercial Computer Software and Commercial Computer Software Documentation are being licensed to U.S.
Government end users (a) only as Commercial Items and (b) with only those rights as are granted to all other end users pursuant
to the terms and conditions herein. Unpublished-rights reserved under the copyright laws of the United States. Adobe Systems
Incorporated, 345 Park Avenue, San Jose, CA 95110-2704, USA. For U.S. Government End Users, Adobe agrees to comply with
all applicable equal opportunity laws including, if appropriate, the provisions of Executive Order 11246, as amended, Section
402 of the Vietnam Era Veterans Readjustment Assistance Act of 1974 (38 USC 4212), and Section 503 of the Rehabilitation
Act of 1973, as amended, and the regulations at 41 CFR Parts 60-1 through 60-60, 60-250, and 60-741. The affirmative action
clause and regulations contained in the preceding sentence shall be incorporated by reference.
Contents
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Intended audience . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
System requirements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Updating Flash XML files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
About the documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .11
Additional resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
3
Chapter 5: Functions and Methods . . . . . . . . . . . . . . . . . . . . . . . 163
About functions and methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
Understanding methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
4 Contents
Chapter 10: Working with Movie Clips . . . . . . . . . . . . . . . . . . . . . 313
About controlling movie clips with ActionScript . . . . . . . . . . . . . . . . . .314
Calling multiple methods on a single movie clip . . . . . . . . . . . . . . . . . .316
Loading and unloading SWF files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .316
Changing movie clip position and appearance . . . . . . . . . . . . . . . . . . .319
Dragging movie clips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
Creating movie clips at runtime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .321
Adding parameters to dynamically created movie clips. . . . . . . . . . . 325
Managing movie clip depths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
About caching and scrolling movie clips with ActionScript . . . . . . . 330
Using movie clips as masks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
Handling movie clip events. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
Assigning a class to a movie clip symbol. . . . . . . . . . . . . . . . . . . . . . . . 339
Initializing class properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
Contents 5
Chapter 13: Creating Interaction with ActionScript . . . . . . . . . . 519
About events and interaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 520
Controlling SWF file playback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 520
Creating interactivity and visual effects . . . . . . . . . . . . . . . . . . . . . . . . 524
Creating runtime data bindings using ActionScript . . . . . . . . . . . . . . . 537
Deconstructing a sample script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .546
6 Contents
Appendix A: Error Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . 707
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .737
Contents 7
8 Contents
Introduction
Adobe Flash CS3 Professional is the professional standard authoring tool for producing high-
impact web experiences. ActionScript is the language you use to add interactivity to Flash
applications, whether your applications are simple animated SWF files or more complex rich
Internet applications. You don’t have to use ActionScript to use Flash, but if you want to
provide basic or complex user interactivity, work with objects other than those built into Flash
(such as buttons and movie clips), or otherwise turn a SWF file into a more robust user
experience, you’ll probably want to use ActionScript.
For more information, see the following topics:
Intended audience . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Updating Flash XML files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
System requirements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
About the documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Additional resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Intended audience
This manual assumes that you have already installed Flash and know how to use the user
interface.You should know how to place objects on the Stage and manipulate them in the
Flash authoring environment. If you have used a scripting language before, ActionScript will
seem familiar. But if you’re new to programming, ActionScript basics are easy to learn. You
can start with simple commands and build more complexity as you progress. You can add a lot
of interactivity to your files without having to learn (or write) a lot of code.
9
System requirements
ActionScript 2.0 does not have any system requirements in addition to Flash.
Flash CS3 Professional introduces ActionScript 3.0. Flash Player 9 and ActionScript 3.0 are
the default publishing settings for Flash. This manual provides information on how to use
ActionScript 2.0 with Flash. You must change the publishing settings for your Flash files to
Flash Player 9 and ActionScript 2.0. If you do not change the default settings, explanations
and code samples in the documentation might not work correctly. If you develop applications
for earlier versions of Flash Player, see Appendix D, “Writing Scripts for Earlier Versions of
Flash Player,” on page 721.
10 Introduction
About the documentation
This manual provides an overview of ActionScript syntax and information on how to use
ActionScript when working with different types of objects. For details on the syntax and usage
of every language element, see the ActionScript 2.0 Language Reference.
For more information, see the following topics:
■ “Learning ActionScript 2.0 book overview” on page 11
■ “About the sample files” on page 14
■ “Terms used in this document” on page 13
■ “Copy and paste code” on page 13
12 Introduction
Typographical conventions
This manual uses the following typographical conventions:
■ Code font indicates ActionScript code.
■ Bold code font, typically within a procedure, indicates code that you need to modify or
add to code you have already added to your FLA file. In some case, it might be used to
highlight code to look at.
■ Boldface text indicates data you need to type into the user interface, such as a filename or
instance name.
■ Italic text indicates a new term defined in the text that follows. In a file path, it might
indicate a value that should be replaced (for example, with a directory name on your own
hard disk).
You might also encounter special quotation marks if you paste ActionScript from other
locations, such as a web page or a Microsoft Word document.
Additional resources
In addition to this manual about ActionScript, there are manuals on other Flash topics, such
as components and Adobe Flash Lite. You can access each manual in the Help panel (Help >
Flash Help), by viewing the default Table of Contents. Click the Clear button to see each
manual that’s available; for more information, see “Where to find documentation on other
subjects” on page 17.
For more information about other available resources, see the following topics:
■ “About the sample files” on page 14
■ “Where to find PDF files or printed documentation” on page 15
■ “About LiveDocs” on page 15
■ “Additional online resources” on page 16
■ “Where to find documentation on other subjects” on page 17
14 Introduction
For samples of ActionScript-focused sample source files, see the Flash Samples page at
www.adobe.com/go/learn_fl_samples. Download and decompress the Samples zip file and
navigate to the ActionScript2.0 folder to access the samples. For components-focused sample
files, navigate to the ComponentsAS2 folder.
About LiveDocs
You can access documentation at the LiveDocs website, in addition to accessing it from the
Help panel. The LiveDocs website contains all of the Flash Help pages and might contain
comments that clarify, update, or correct parts of the documentation. Click View Comments
on LiveDocs at the bottom of a page in the Help panel to display the equivalent page on the
LiveDocs website. Go to http://livedocs.macromedia.com to see a list of all of the available
documentation in the LiveDocs format.
Technical writers monitor the LiveDocs website. One of the advantages of LiveDocs is seeing
comments that clarify the documentation or correct any errata or issues that arise after a
software release. LiveDocs is not the place to make help requests, such as asking questions
about your code that doesn’t work, comment on problems with software or installation, or ask
how to create something with Flash. It is the correct place to provide feedback about the
documentation (for example, you notice a sentence or paragraph that could be clarified).
When you click the button to add a comment on LiveDocs, there are several points about the
kinds of comments that are acceptable on the system. Please read these guidelines closely, or
your comment might be removed from the website.
If you have a question about Flash, please ask it on the Adobe web forums: www.adobe.com/
support/forums/. The web forums are the best place to ask questions, because there are many
Adobe employees, Team Adobe volunteers, Adobe user group managers and members, and
even technical writers who monitor these forums.
Additional resources 15
Engineers do not monitor the LiveDocs system but do monitor the Flash wish list. If you
think you have found a bug in the software, or you would like to request an enhancement to
Flash, please fill out the wishform at www.adobe.com/go/wish. If you report your bug or
enhancement request on LiveDocs, it will not be officially added to the bug database. You
must use the wishform instead, if you want an engineer to see your bug or request.
Remember to be careful about special characters and line breaks when you paste from the
web, including LiveDocs. Adobe has made every effort to remove all special characters from
code samples, but if you have problems pasting code, see “Copy and paste code” on page 13.
16 Introduction
Where to find documentation on other subjects
The following manuals offer additional information on subjects commonly associated with
ActionScript 2.0:
■ For information about the elements that compose the ActionScript language, see the
ActionScript 2.0 Language Reference.
■ For information about working in the Flash authoring environment, see How to Use Help.
■ For information about working with components, see Using ActionScript 2.0 Components.
Additional resources 17
18 Introduction
CHAPTER 1
19
New in ActionScript 2.0 and
Flash Player 8
The ActionScript language has grown and developed since its introduction several years ago.
With each new release of Flash, additional keywords, objects, methods, and other language
elements were added to ActionScript. There are also ActionScript-related improvements to
the Flash 8 authoring environments. Flash Basic 8 and Flash Professional 8 introduced several
new language elements for expressive features, such as filters and blending modes, and
application development, such as JavaScript integration (ExternalInterface) and file input and
output (FileReference and FileReferenceList).
This section provides an overview of the ActionScript language elements and classes that are
new or changed in Flash 8 and ActionScript-related improvements to the authoring tool. For
a list of specific additions to ActionScript 2.0, see “Additions to the ActionScript language in
Flash Player 8” on page 22. To use any of the new language elements in your scripts, you must
target Flash Player 8 when you publish your documents.
The following features were added to both Flash Basic 8 and Flash Professional 8 (unless
noted otherwise):
■ ActionScript editor enhancements let you show hidden characters in your scripts. For
more information, see “Display hidden characters” in Using Flash.
■ Debug options are now available in the Script window, as well as the Actions panel, for
ActionScript files.
■ The Configuration directory that includes XML files and Class files is reorganized. See
“Configuration folders installed with Flash” in Using Flash for details.
■ You can set a preference to reload modified script files when working on an application,
which helps you avoid working with older versions of script files, and overwriting newer
script files. For more information, see “Set ActionScript preferences” in Using Flash.
■ The Script window feature is available in Flash. That means you can now create an
ActionScript file in either program.
■ Script Assist (similar to Normal Mode in earlier editions of Flash) helps you code without
needing to understand syntax. For more information on Script Assist, see “About Script
Assist mode” in Using Flash.
■ You can load new kinds of image files at runtime, which include progressive JPEG images,
and non-animated GIF and PNG files. If you load an animated file, the first frame of the
animation appears.
■ You can assign linkage identifiers to bitmap and sound files stored in the Library, which
means that you can attach images to the Stage or work with these assets in shared libraries.
New language elements, methods, and functions added to existing classes in ActionScript
include:
■ The showRedrawRegions global function provides the ability for the debugger player to
outline the regions of the screen that are being redrawn (that is, dirty regions that are
being updated). The function has the player show what was redrawn, but does not let you
control redraw regions.
■ The blendMode property in the Button class, which sets the blending mode for the
button instance.
■ The cacheAsBitmap property in the Button class, which lets you cache the object as an
internal bitmap representation of the instance.
In this description, a local SWF file is a SWF file that is locally installed on a user’s
computer, not served from a website, and does not include projector (EXE) files.
In previous versions of Flash Player, local SWF files could interact with other SWF files and
load data from any remote or local computer without configuring security settings. In Flash
Player 8 and later, a SWF file cannot make connections to the local file system and the
network (such as the Internet) in the same application without making a security setting. This
is for your safety, so a SWF file cannot read files on your hard disk and then send the contents
of those files across the Internet.
About ActionScript 2
The object-oriented programming (OOP) features in ActionScript 2.0 are based on the
ECMAScript 4 Draft Proposal currently in development by ECMA TC39-TG1 (see
www.mozilla.org/js/language/es4/index.html). Because the ECMA-4 proposal is not yet a
standard, and because it is still changing, ActionScript 2.0 is loosely based on this
specification.
ActionScript 2.0 supports all the standard elements of the ActionScript language; it lets you
write scripts that more closely adhere to standards used in other object-oriented languages,
such as Java. ActionScript 2.0 should be of interest primarily to intermediate or advanced
Flash developers who are building applications that require the implementation of classes and
subclasses. ActionScript 2.0 also lets you declare the object type of a variable when you create
it (see “About assigning data types and strict data typing” on page 45) and provides
significantly improved compiler errors (see Appendix A, “Error Messages,” on page 707).
Key facts about ActionScript 2.0 include the following points:
■ Scripts that use ActionScript 2.0 to define classes or interfaces must be stored as external
script files, with a single class defined in each script; that is, classes and interfaces cannot
be defined in the Actions panel.
■ You can import individual class files implicitly (by storing them in a location specified by
global or document-specific search paths and then using them in a script) or explicitly (by
using the import command); you can import packages (collections of class files in a
directory) by using wildcards.
■ Applications developed with ActionScript 2.0 are supported by Flash Player 6 and later.
CA UT ION
The default publish setting for new files created in Flash CS3 is ActionScript 3.0. If
you plan to modify an existing FLA file with ActionScript 1.0 or ActionScript 2.0 to
use ActionScript 2.0 syntax, ensure that the FLA file specifies ActionScript 2.0 in its
publish settings. If it does not, your file will compile incorrectly, although Flash will not
necessarily generate compiler errors.
31
For more information on using ActionScript 2.0 to write object-oriented programs in Flash,
see Chapter 6, “Classes,” on page 187.
Although Adobe recommends that you use ActionScript 3.0, you can continue to use
ActionScript 1.0 and ActionScript 2.0 syntax.
What is ActionScript
The main features of ActionScript 2.0 include the following:
Familiar object-oriented programming (OOP) model The primary feature of
ActionScript 2.0 is a familiar model for creating object-oriented programs. ActionScript 2.0
implements several object-oriented concepts and keywords such as class, interface, and
packages that will be familiar to you if you’ve programmed with Java.
The OOP model provided by ActionScript 2.0 is a “syntactic formalization” of the prototype
chaining method used in previous versions of Flash to create objects and establish inheritance.
With ActionScript 2.0, you can create custom classes and extend Flash’s built-in classes.
Strict data typing ActionScript 2.0 also lets you explicitly specify data types for variables,
function parameters, and function return types. For example, the following code declares a
variable named userName of type String (a built-in ActionScript data type, or class).
var userName:String = "";
Compiler warnings and errors The previous two features (OOP model and strict data
typing) enable the authoring tool and compiler to provide compiler warnings and error
messages that help you find bugs in your applications faster than was previously possible
in Flash.
When you use ActionScript 2.0, make sure that the publish settings for the FLA file specify
ActionScript 2.0 (the default for Flash CS3 is ActionScript 3.0). Additionally, if you open an
older FLA file that uses ActionScript 1.0 and begin rewriting it in ActionScript 2.0, change
the publish settings of the FLA file to ActionScript 2.0. If you don’t, your FLA file will not
compile correctly, and errors won’t be generated.
32 About ActionScript
About choosing between ActionScript
1.0 and ActionScript 2.0
When you start a new document or application in Flash, you must decide how to organize its
associated files. You might use classes in some projects, such as when you are building
applications or complex FLA files, but not all documents use classes. For example, many short
examples in the documentation do not use classes. Using classes to store functionality is not
the easiest or best solution for small applications or simple FLA files. It is often more efficient
to put ActionScript inside the document. In this case, try to put all your code on the Timeline
on as few frames as possible, and avoid placing code on or in instances (such as buttons or
movie clips) in a FLA file.
When you build a small project, it is often more work and effort to use classes or external code
files to organize ActionScript instead of adding ActionScript within the FLA file. Sometimes
it is easier to keep all the ActionScript code within the FLA file, rather than placing it within a
class that you import. This does not mean that you should necessarily use ActionScript 1.0.
You might decide to put your code inside the FLA file by using ActionScript 2.0 with its strict
data typing and its new methods and properties. ActionScript 2.0 also offers a syntax that
follows standards in other programming languages. This makes the language easier and more
valuable to learn. For example, you will feel familiar with ActionScript if you have
encountered another language that’s based on the same structure and syntax standards. Or,
you can apply this knowledge to other languages you learn in the future. ActionScript 2.0 lets
you use an object-oriented approach to developing applications by using an additional set of
language elements, which can be advantageous to your application development.
In some cases, you cannot choose which version of ActionScript to use. If you are building a
SWF file that targets an old version of Flash Player, such as a mobile device application, you
must use ActionScript 1.0, which is compatible with Flash Player for a number of devices.
Remember, regardless of the version of ActionScript, you should follow good practices. Many
of these practices, such as remaining consistent with case sensitivity, using code completion,
enhancing readability, avoiding keywords for instance names, and keeping a consistent
naming convention, apply to both versions.
If you plan to update your application in future versions of Flash, or make it larger and more
complex, you should use ActionScript 2.0 and classes, to make it easier to update and modify
your application.
34 About ActionScript
CHAPTER 3
About data
Data refers to the numbers, strings, and other information that you can manipulate within
Flash. Using data is usually essential when you create applications or websites. You also use
data when you create advanced graphics and script-generated animation, and you might have
to manipulate values that you use to drive your effects.
You can define data in variables within Flash, or you can load data from external files or sites
using XML, web services, built-in ActionScript classes, and so on. You can store data in a
database, and then represent that information in several ways in a SWF file. This can include
displaying the information in text fields or components, or displaying images in movie
clip instances.
35
Some of the most common kinds of data include strings (a sequence of characters, such as
names and passages of text), numbers, objects (such as movie clips), Boolean values (true and
false), and so on. In this chapter, you’ll also learn about the data types in Flash and how to
use them.
For information on types of data, see “About data types” on page 36. For information on
variables, see “About variables” on page 50.
MovieClip Complex. The MovieClip data type lets you control movie clip symbols
using the methods of the MovieClip class. For more information, see
“MovieClip data type” on page 40.
Number Primitive. This data type can represent integers, unsigned integers, and
floating point numbers. To store a floating point number, you should
include a decimal point in the number. Without the decimal point, the
number is stored as an integer. The Number data type can store values
from Number.MAX_VALUE (very high) to Number.MIN_VALUE (very low). For
more information, see ActionScript 2.0 Language Reference and
“Number data type” on page 42.
Object Complex. The Object data type is defined by the Object class. The
Object class serves as the base class for all class definitions in
ActionScript, and it lets you arrange objects inside each other (nested
objects). For more information, see “Object data type” on page 42.
undefined Primitive. The undefined data type contains one value: undefined. This is
the default value for instances of the Object class. You can only assign a
value of undefined to variables that belong to the Object class. For more
information, see “undefined data type” on page 44.
Void Complex. The Void data type contains only one value: void. You use this
data type to designate functions that don’t return a value. Void is a
complex data type that references the primitive Void data type. For
more information, see “Void data type” on page 44.
For a sample of the datatypes.fla file, see the Flash Samples page at www.adobe.com/go/
learn_fl_samples. Download and decompress the Samples zip file and navigate to the
ActionScript2.0/DataTypes folder to access the sample.
The following example checks that users enter values into two TextInput component
instances. Two Boolean variables are created, userNameEntered and isPasswordCorrect,
and if both variables evaluate to true, a welcome message is assigned to the titleMessage
String variable.
// Add two TextInput components, a Label, and a Button component on the
Stage.
// Strict data type the three component instances
var userName_ti:mx.controls.TextInput;
var password_ti:mx.controls.TextInput;
var submit_button:mx.controls.Button;
var welcome_lbl:mx.controls.Label;
The second example returns the width of a movie clip called my_mc on the Stage. The targeted
instance must be a movie clip, and the returned value must be a numeric value.
function getMCWidth(target_mc:MovieClip):Number {
return target_mc._width;
}
trace(getMCWidth(my_mc));
Creating movie clips dynamically Using ActionScript to create movie clips dynamically is
useful when you want to avoid manually creating movie clips on the Stage or attaching them
from the library. For example, you might create an image gallery with a large number of
thumbnail images that you want to organize on the Stage. Using
MovieClip.createEmptyMovieClip() lets you create an application entirely using
ActionScript.
To dynamically create a movie clip, use MovieClip.createEmptyMovieClip(), as shown in
the following example:
// Creates a movie clip to hold the container.
this.createEmptyMovieClip("image_mc", 9);
// Loads an image into image_mc.
image_mc.loadMovie("http://www.helpexamples.com/flash/images/image1.jpg");
For more information, see Chapter 10, “Working with Movie Clips,” on page 313 and the
MovieClip entry in the ActionScript 2.0 Language Reference.
The following example finds the percent of the intro_mc movie clip that is loaded and
represents it as an integer:
var percentLoaded:Number = Math.round((intro_mc.getBytesLoaded() /
intro_mc.getBytesTotal()) * 100);
The ActionScript MovieClip object has methods that let you control movie clip symbol
instances on the Stage. This example uses the play() and nextFrame() methods:
mcInstanceName.play();
mc2InstanceName.nextFrame();
For more information, see “Example: Writing custom classes” on page 223.
You can use the addition (+) operator to concatenate, or join, two strings. ActionScript treats
spaces at the beginning or end of a string as a literal part of the string. The following
expression includes a space after the comma:
var greeting_str:String = "Welcome, " + firstName;
To include a quotation mark in a string, precede it with a backslash character (\). This is called
escaping a character. There are other characters that cannot be represented in ActionScript
except by special escape sequences. The following table lists all the ActionScript escape
characters:
Strings in ActionScript are immutable, just as they are in Java. Any operation that modifies a
string returns a new string.
The String class is a built-in ActionScript class. For information on the methods and
properties of the String class, see the String entry in the ActionScript 2.0 Language Reference.
If your application has multiple frames, the code does not execute a second time because the
init variable is no longer undefined.
Because x was not declared using strict data typing, the compiler cannot determine the type;
to the compiler, the variable x can have a value of any type. (See “Assigning a data type”
on page 46.) A later assignment might change the type of x; for example, the statement
x = "hello" changes the type of x to String.
ActionScript always converts primitive data types (such as Boolean, Number, String, null, or
undefined) automatically when an expression requires the conversion and the variables aren’t
strictly typed.
Strict data typing offers several benefits at compile time. Declaring data types (strict data
typing) can help prevent or diagnose errors in your code at compile time. To declare a variable
using strict data typing, use the following format:
var variableName:datatype;
NO TE
Because data type mismatches trigger compiler errors, strict data typing helps you find bugs in
your code at compile time and prevents you from assigning the wrong type of data to an
existing variable. During authoring, strict data typing activates code hinting in the
ActionScript editor (but you should still use instance name suffixes for visual elements).
Using strict data typing helps ensure that you don’t inadvertently assign an incorrect type of
value to a variable. Flash checks for typing mismatch errors at compile time, and displays an
error message if you use the wrong type of value. Therefore, using strict typing also helps to
ensure that you do not attempt to access properties or methods that are not part of an object’s
type. Strict data typing means the ActionScript editor automatically shows code hints
for objects.
There are many possibilities for data types, ranging from the native data types such as
Number, String, Boolean, or built-in classes that are included in Flash Player 8, such as
BitmapData, FileReference, or even custom classes that you or other developers have written.
The most common types of data types you might need to specify are the built-in data types
such as Number, String, Boolean, Array, or Object, which are shown in the following
code examples.
To assign a specific data type to an item, specify its type using the var keyword and post-
colon syntax, as shown in the following example:
// Strict typing of variable or object
var myNum:Number = 7;
var birthday:Date = new Date();
When Flash compiles this script, a type mismatch error is generated because the SWF file
expects a Boolean value.
If you write a function that doesn’t have a return type, you can specify a return type of Void
for that function. Or if you create a shortcut to a function, you can assign a data type of
Function to the new variable. To specify that objects are of type Function or Void, see the
following example:
function sayHello(name_str:String):Void {
trace("Hello, " + name_str);
}
sayHello("world"); // Hello, world
var greeting:Function = sayHello;
greeting("Augustus"); // Hello, Augustus
Another advantage of strict data typing is that Flash automatically shows code hints for built-
in objects when they are strictly typed. For more information, see “About assigning data types
and strict data typing” on page 45.
Files published using ActionScript 1.0 do not respect strict data typing assignments at compile
time, so assigning the wrong type of value to a variable that you have strictly typed doesn’t
generate a compiler error.
var myNum:String = "abc";
myNum = 12;
/* No error in ActionScript 1.0, but type mismatch error in ActionScript 2.0
*/
In this example, you create a new String variable named myName, and then convert it into a
Number data type:
var myName:String = new String("17");
trace(myName instanceof String); // true
var myNumber:Number = new Number(myName);
trace(myNumber instanceof Number); // true
About variables
A variable is a container that holds information. The following ActionScript shows what a
variable looks like in ActionScript:
var myVariable:Number = 10;
This variable holds a numerical value. The use of :Number in the previous code assigns the
type of value that variable holds, called data typing. For more information on data typing, see
“About assigning data types and strict data typing” on page 45 and “Assigning a data type”
on page 46.
The container (represented by the variable name) is always the same throughout your
ActionScript, but the contents (the value) can change. You can change the value of a variable
in a script as many times as you want. When you change the value of a variable while the SWF
file plays, you can record and save information about what the user has done, record values
that change as the SWF file plays, or evaluate whether a condition is true or false. You
might need the variable to continually update while the SWF file plays, such as when a
player’s score changes in a Flash game. Variables are essential when you create and handle user
interaction in a SWF file.
It’s a good idea to assign a value to a variable the first time you declare the variable. Assigning
an initial value is called initializing the variable, and it’s often done on Frame 1 of the
Timeline or from within a class that loads when the SWF file begins to play. There are
different kinds of variables, which are affected by scope. For more information on different
kinds of variables and scope, see “About variables and scope” on page 60.
TI P
Initializing a variable helps you track and compare the variable’s value as the SWF file
plays.
NOT E
Flash Player 7 and later evaluate uninitialized variables differently than Flash Player 6
and earlier. If you have written scripts for Flash Player 6 and plan to write or port scripts
for Flash Player 7 or later, you should be understand these differences to avoid
unexpected behavior.
About variables 51
About default values
A default value is the value that a variable contains before you set its value. You initialize a
variable when you set its value for the first time. If you declare a variable, but do not set its
value, that variable is uninitialized. The value of an uninitialized variable defaults to the value
undefined. For more information on creating and using variables, see “About variables”
on page 50.
Because Pirate Eye is a string, the value needs to be enclosed in straight quotes
(quotation marks).
This example assigns the value of Pirate Eye to the catName variable. When you declare the
variable, you can also assign a value to it instead of assigning it afterwards (as in the previous
examples). You could set the catName variable when you declare it, as shown in the
following example:
var catName:String = "Pirate Eye";
If you want to display the value of the catName variable in the test environment, you can use
the trace() statement. This statement sends the value to the Output panel. You can trace the
value of the catName variable and see that the actual value doesn’t include the quotation
marks by using the following ActionScript:
var catName:String = "Pirate Eye";
trace(catName); // Pirate Eye
This error tells you that you attempted to set the wrong data type to a specified variable.
When you assign a numeric value to a variable, the quotation marks aren’t necessary, as shown
in the following code:
var numWrinkles:Number = 55;
If you want to change the value of numWrinkles later in your code, you can assign a new
value using the following ActionScript:
numWrinkles = 60;
When you reassign a value to an existing variable, you don’t need to use the var keyword or
define the variable’s data type (in this case, :Number).
If the value is numeric or Boolean (true or false), the value doesn’t use straight quotes
(quotation marks). Examples of numeric and Boolean values are shown in the
following snippet:
var age:Number = 38;
var married:Boolean = true;
var hasChildren:Boolean = false;
In the previous example, the variable age contains an integer (nondecimal) value, although
you could also use a decimal or floating-point value such as 38.4. Boolean variables (such as
married or hasChildren) have only two possible values, true or false.
If you want to create an array and assign values to it, the format is slightly different, as shown
in the following code:
var childrenArr:Array = new Array("Pylon", "Smithers", "Gil");
There is an alternative (shorthand) syntax for creating an array using array access operators,
which use the bracket ([]) punctuators. You can rewrite the previous example as follows:
var childrenArr:Array = ["Pylon", "Smithers", "Gil"];
For more information on creating arrays and the array access operators, see “About arrays”
on page 125 and “About using dot syntax to target an instance” on page 82.
About variables 53
Similarly, you can create a new object called myObj. You can use either of the following ways
to create a new object. The first (and longer) way to code an array is as follows:
var myObj:Object = new Object();
myObj.firstName = "Steve";
myObj.age = 50;
myObj.childrenArr = new Array("Mike", "Robbie", "Chip");
The second, shorthand way you can code the myObj array is as follows:
var myObj:Object = {firstName:"Steve", age:50, childrenArr:["Mike",
"Robbie", "Chip"]};
As you see in this example, using the shorthand method can save a lot of typing and time,
especially when you define instances of objects. It is important to be familiar with this
alternate syntax because you will encounter it if you work in teams or when you work with
third-party ActionScript code that you find, for example, on the Internet or in books.
NO TE
Not all variables need to be explicitly defined. Some variables are created by Flash
automatically for you. For example, to find the dimensions of the Stage, you could use
the values of the following two predefined values: Stage.width and Stage.height.
Another example is the addition (+) operator, which you use to add two or more numeric
values to produce a new value. If you use the + operator on two or more string values, the
strings will be concatenated. The values that operators manipulate are called operands.
When you assign a value, you use an operator to define a value to a variable. For example, the
following script uses the assignment operator to assign a value of 7 to the variable
numChildren:
var numChildren:Number = 7;
If you want to change the value of the numChildren variable, use the following code:
numChildren = 8;
N OTE
You don’t need to use var because the variable has previously been defined.
An identifier is the name of a variable, property, object, function, or method. The first
character of an indentifier must be a letter, underscore (_), or dollar sign ($). Each
subsequent character can be a number, letter, underscore, or dollar sign.
The ActionScript editor supports code hints for built-in classes and for variables that are based
on these classes. If you want Flash to provide code hints for a particular object type that you
assign to a variable, you can strictly type the variable. Code hints provide tooltip-style syntax
hints and a pop-up menu that helps you write your code quickly.
For example, type the following code:
var members:Array = new Array();
members.
As soon as you type the period (.) in the Actions panel, Flash displays a list of methods and
properties available for Array objects.
For recommended coding conventions for naming variables, see “Naming variables”
on page 670.
About variables 55
Using variables in an application
In this section, you use variables in short code snippets of ActionScript. You need to declare
and initialize a variable in a script before you can use it in an expression. Expressions are
combinations of operands and operators that represent a value. For example, in the expression
i+2, i and 2 are operands, and + is an operator.
If you do not initialize a variable before you use it in an expression, the variable is undefined
and may cause unexpected results. For more information on writing expressions, see Chapter
4, “Syntax and Language Fundamentals,” on page 77.
If you use an undefined variable, as shown in the following example, the variable’s value in
Flash Player 7 and later will be NaN, and your script might produce unintended results:
var squared:Number = myNum * myNum;
trace(squared); // NaN
var myNum:Number = 6;
In the following example, the statement that declares and initializes the variable myNum comes
first, so squared can be replaced with a value:
var myNum:Number = 6;
var squared:Number = myNum * myNum;
trace(squared); // 36
Similar behavior occurs when you pass an undefined variable to a method or function, as
shown next.
4. Select Control > Test Movie, and notice that the button does not work (it doesn’t open the
web page).
5. Drag another Button component onto the Stage. Select the button.
6. Open the Property inspector, and type good_button into the Instance Name text box.
8. Select Control > Test Movie and click the second button you added to the Stage.
This button properly opens the web page.
The type of data that a variable contains affects how and when the variable’s value changes.
Primitive data types, such as strings and numbers, are passed by value, which means the current
value of the variable is used rather than a reference to that value. Examples of complex data
types include the Array and Object data types.
In the following example, you set myNum to 15 and copy the value into otherNum. When you
change myNum to 30 (in line 3 of the code), the value of otherNum remains 15 because
otherNum doesn’t look to myNum for its value. The otherNum variable contains the value of
myNum that it receives (in line 2 of the code).
When you change myNum to 30 (in line 3 of the code), the value of otherNum remains 15
because otherNum doesn’t look to myNum for its value. The otherNum variable contains the
value of myNum that it receives (in line 2 of the code).
3. Select Control > Test Movie to see the values display in the Output panel.
About variables 57
4. Now add the following ActionScript after the code you added in step 2:
function sqr(myNum:Number):Number {
myNum *= myNum;
return myNum;
}
var inValue:Number = 3;
var outValue:Number = sqr(inValue);
trace(inValue); // 3
trace(outValue); // 9
In the this code, the variable inValue contains a primitive value, 3, so the value passes to
the sqr() function, and the returned value is 9. The value of the variable inValue does
not change, although the value of myNum in the function changes.
5. Select Control > Test Movie to see the values display in the Output panel.
The Object data type can contain such a large amount of complex information that a variable
with this type doesn’t hold an actual value; it holds a reference to a value. This reference is
similar to an alias that points to the contents of the variable. When the variable needs to know
its value, the reference asks for the contents and returns the answer without transferring the
value to the variable.
For information on passing a variable by reference, see “Passing a variable by reference”
on page 58.
Flash uses a zero-based index, which means that 0 is the first item in the array, 1 is
the second, and so on.
In the following example, myArray contains an Array object, so you pass the array to function
zeroArray() by reference. The function zeroArray() accepts an Array object as a
parameter and sets all the elements of that array to 0. It can modify the array because the array
is passed by reference.
About variables 59
About variables and scope
A variable’s scope refers to the area in which the variable is known (defined) and can be
referenced. The area in which the variable is known might be within a certain timeline or
inside a function, or it might be globally known throughout the entire application.For more
information about scope, see “About scope and targeting” on page 87.
Understanding variable scope is important when you develop Flash applications with
ActionScript. Scope indicates not only when and where you can refer to variables but also for
how long a particular variable exists in an application. When you define variables in the body
of a function, they cease to exist as soon as the specified function ends. If you try to refer to
objects in the wrong scope or to variables that have expired, you get errors in your Flash
documents, which lead to unexpected behavior or broken functionality.
There are three types of variable scopes in ActionScript:
■ Global variables and functions are visible to every timeline and scope in your document.
Therefore, a global variable is defined in all areas of your code.
■ Timeline variables are available to any script on that timeline.
■ Local variables are available within the function body in which they are declared
(delineated by curly braces). Therefore, local variables are only defined in a part of
your code.
For guidelines on using scope and variables, see Chapter 4, “About scope and targeting,” on
page 87.
NO TE
ActionScript 2.0 classes that you create support public, private, and static variable
scopes. For more information, see “About class members” on page 211 and “Controlling
member access in your classes” on page 233.
You cannot strict type global variables. For information and a workaround, see “Global
variables” on page 60.
Global variables
Global variables and functions are visible to every timeline and scope in your document. To
declare (or create) a variable with global scope, use the _global identifier before the variable
name and do not use the var = syntax. For example, the following code creates the global
variable myName:
var _global.myName = "George"; // Incorrect syntax for global variable
_global.myName = "George"; // Correct syntax for global variable
This example simply shows that the global variable is not accessed in the scope of the count()
function. However, you could access the global-scoped variable if you prefix it with _global.
For example, you could access it if you prefix the counter with _global as shown in the
following code:
trace(_global.counter);
You cannot assign strict data types to variables that you create in the _global scope, because
you have to use the var keyword when you assign a data type. For example, you couldn't do:
_global.foo:String = "foo"; //syntax error
var _global.foo:String = "foo"; //syntax error
The Flash Player version 7 and later security sandbox enforces restrictions when accessing
global variables from SWF files loaded from separate security domains. For more information,
see Chapter 16, “Understanding Security,” on page 631.
Timeline variables
Timeline variables are available to any script on that particular timeline. To declare timeline
variables, use the var statement and initialize them in any frame in the timeline. The variable
is available to that frame and all following frames, as shown in the following example.
About variables 61
6. Select Control > Test Movie to test the new document.
The value 15 appears in the Output panel after approximately a second. Because Flash
documents loop by default, the value 15 continually traces in the Output panel every time
the playhead reaches Frame 20 in the Timeline. To stop the looping action, add stop();
after the trace() statement.
You must declare a timeline variable before trying to access it in a script. For example, if you
put the code var myNum:Number = 15; in Frame 20, any scripts attached to a frame before
Frame 20 cannot access myNum and are undefined instead of containing the value 15.
Local variables
When you use the var statement inside a function block, you declare local variables. When
you declare a local variable within a function block (also called function definition), it is
defined within the scope of the function block, and expires at the end of the function block.
Therefore, the local variable only exists within that function.
For example, if you declare a variable named myStr within a function named localScope,
that variable will not be available outside of the function.
function localScope():Void {
var myStr:String = "local";
}
localScope();
trace(myStr); // Undefined, because myStr is not defined globally
If the variable name you use for your local variable is already declared as a timeline variable,
the local definition takes precedence over the timeline definition while the local variable is in
scope. The timeline variable will still exist outside of the function. For example, the following
code creates a timeline string variable named str1, and then creates a local variable of the
same name inside the scopeTest() function. The trace statement inside the function
generates the local definition of the variable, but the trace statement outside the function
generates the timeline definition of the variable.
var str1:String = "Timeline";
function scopeTest():Void {
var str1:String = "Local";
trace(str1); // Local
}
scopeTest();
trace(str1); // Timeline
In the next example, you can see how certain variables live only for the life of a specific
function and can generate errors if you try to refer to the variable outside the scope of
that function.
It’s also common to see the following syntax for a for loop: for (var i:Number = 0;
i < arrayLength; i++) {...}.
This example displays undefined in the Flash test environment because the variable i isn’t
defined in the main timeline. It exists only in the initArray() function.
You can use local variables to help prevent name conflicts, which can cause unexpected results
in your application. For example, if you use age as a local variable, you could use it to store a
person’s age in one context and the age of a person’s child in another context. There is no
conflict in this situation because you are using these variables in separate scopes.
About variables 63
It’s good practice to use local variables in the body of a function so the function can act as an
independent piece of code. You can change a local variable only within its own block of code.
If an expression in a function uses a global variable, code or events outside the function can
change its value, which changes the function.
You can assign a data type to a local variable when you declare it, which helps prevent
assigning the wrong type of data to an existing variable. For more information, see “About
assigning data types and strict data typing” on page 45.
When you publish your Flash document, an HTML document is created by default in the
same directory as the SWF file. If an HTML file was not created, select File > Publish
settings, and make sure you select HTML in the Formats tab. Then publish your
document again.
The following code demonstrates the HTML in the document that is responsible for
embedding a Flash document in an HTML page. You need to look at this HTML to
understand how URL variables work in the following step (where you add additional code
for URL variables).
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
codebase="http://fpdownload.adobe.com/pub/shockwave/cabs/flash/
swflash.cab#version=8,0,0,0" width="550" height="400"
id="urlvariables" align="middle">
<param name="allowScriptAccess" value="sameDomain" />
<param name="movie" value="urlvariables.swf" />
<param name="quality" value="high" />
<param name="bgcolor" value="#ffffff" />
<embed src="urlvariables.swf" quality="high" bgcolor="#ffffff"
width="550" height="400" name="urlvariables" align="middle"
allowScriptAccess="sameDomain" type="application/x-shockwave-flash"
pluginspage="http://www.adobe.com/go/getflashplayer" />
</object>
6. To pass variables from the generated HTML document to your Flash document, you can
pass variables after the path and filename (urlvariables.swf). Add the bold text to the
HTML file that was generated on your desktop.
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
codebase="http://fpdownload.adobe.com/pub/shockwave/cabs/flash/
swflash.cab#version=8,0,0,0" width="550" height="400"
id="urlvariables" align="middle">
About variables 65
<param name="allowScriptAccess" value="sameDomain" />
<param name="movie" value="urlvariables.swf?myURL=http://
weblogs.macromedia.com" />
<param name="quality" value="high" />
<param name="bgcolor" value="#ffffff" />
<embed src="urlvariables.swf?myURL=http://weblogs.macromedia.com"
quality="high" bgcolor="#ffffff" width="550" height="400"
name="urlvariables" align="middle" allowScriptAccess="sameDomain"
type="application/x-shockwave-flash" pluginspage="http://
www.adobe.com/go/getflashplayer" />
</object>
7. If you want to pass multiple variables to Flash, you need to separate the name/values pairs
with an ampersand (&). Find the following code from step 6:
?myURL=http://weblogs.macromedia.com
Remember, you need to make the same changes to both the object tag and the embed tag
to maintain consistency between all browsers. You might notice that the words are
separated by + punctuators. The words are separated this way because the values are URL-
encoded and the + punctuator represents a single blank space.
N OTE
For a list of common URL-encoded special characters, see the Flash TechNote,
URL Encoding: Reading special characters from a text file.
Because the ampersand (&) serves as a delimiter for different name/value pairs, if the values
you are passing contain ampersands, unexpected results might occur. Given the nature of
name/value pairs and parsing, if you had the following values being passed to Flash:
my.swf?name=PB+&+J&flavor=strawberry+rhubarb
Flash would build the following variables (and values) into the root scope:
'name': 'PB ' (note space at end of value)
' J': '' (note space at beginning of variable name and an empty value)
'flavor': 'strawberry rhubarb'
To avoid this, you need to escape the ampersand (&) character in the name/value pair with
its URL-encoded equivalent (%26).
8. Open the urlvariables.html document, and find the following code:
?myURL=http://weblogs.macromedia.com&myTitle=Adobe+News+Aggregator
All browsers will support string sizes as large as 64K (65535 bytes) in length.
FlashVars must be assigned in both the object and embed tags in order to work on
all browsers.
4. Select File > Publish to publish the SWF and HTML files.
5. Open the directory containing the published files (where you saved myflashvars.fla on your
hard drive) and open the HTML document (myflashvars.html by default) in an HTML
editor such as Dreamweaver or Notepad.
6. Add the code that appears in bold below, so your HTML document matches the following:
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
codebase="http://fpdownload.adobe.com/pub/shockwave/cabs/flash/
swflash.cab#version=8,0,0,0" width="550" height="400" id="myflashvars"
align="middle">
About variables 67
<param name="allowScriptAccess" value="sameDomain" />
<param name="movie" value="myflashvars.swf" />
<param name="FlashVars" value="myURL=http://weblogs.adobe.com/">
<param name="quality" value="high" />
<param name="bgcolor" value="#ffffff" />
<embed src="myflashvars.swf" FlashVars="myURL=http://weblogs.adobe.com/"
quality="high" bgcolor="#ffffff" width="550" height="400"
name="myflashvars" align="middle" allowScriptAccess="sameDomain"
type="application/x-shockwave-flash" pluginspage="http://
www.adobe.com/go/getflashplayer" />
</object>
This code passes a single variable called myURL, which contains the string
http://weblogs.macromedia.com. When the SWF file loads, a property named myURL
is created in the _level0 scope. One of the advantages of using FlashVars or passing
variables along the URL is that the variables are immediately available in Flash when the
SWF file loads. This means you don’t have to write any functions to check if the variables
have finished loading, which you would need to do if you loaded variables using LoadVars
or XML.
7. Save your changes to the HTML document, and then close it.
8. Double click myflashvars.html to test the application.
The text http://weblogs.macromedia.com, a variable in the HTML file, appears in the
SWF file.
NOT E
All browsers will support string sizes as large as 64K (65,535 bytes) in length.
FlashVars must be assigned in both the object and embed tags in order to work on
all browsers.
This code loads a text file from a remote server and parses its name/value pairs.
TI P
About variables 69
To use variables in a project:
1. Create a new Flash document, and save it as imgloader.fla.
2. Select Frame 1 of the Timeline, and add the following ActionScript to the Actions panel:
/* Specify default image in case there wasn't a value passed using
FlashVars. */
var imgUrl:String = "http://www.helpexamples.com/flash/images/
image1.jpg";
if (_level0.imgURL != undefined) {
// If image was specified, overwrite default value.
imgUrl = _level0.imgURL;
}
this.createEmptyMovieClip("img_mc", 10);
var mclListener:Object = new Object();
mclListener.onLoadInit = function(target_mc:MovieClip):Void {
target_mc._x = (Stage.width - target_mc._width) / 2;
target_mc._y = (Stage.height - target_mc._height) / 2;
}
mclListener.onLoadError = function(target_mc:MovieClip):Void {
target_mc.createTextField("error_txt", 1, 0, 0, 100, 20);
target_mc.error_txt.autoSize = "left";
target_mc.error_txt.text = "Error downloading specified image;\n\t" +
target_mc._url;
}
var myMCL:MovieClipLoader = new MovieClipLoader();
myMCL.addListener(mclListener);
myMCL.loadClip(imgUrl, img_mc);
The first line of code specifies the image that you want to dynamically load into your
Flash document. Next, you check whether a new value for imgURL was specified using
FlashVars or URL-encoded variables. If a new value was specified, the default image URL
is overwritten with the new value. For information on using URL variables, see “Using
variables from the URL” on page 64. For information on FlashVars, see “Using FlashVars
in an application” on page 67.
The next couple of lines of code define the MovieClip instance, and a Listener object for
the future MovieClipLoader instance. The MovieClipLoader’s Listener object defines two
event handlers, onLoadInit and onLoadError. The handlers are invoked when the image
successfully loads and initializes on the Stage, or if the image fails to load. Then you create
a MovieClipLoader instance, and use the addListener() method to add the previously
defined listener object to the MovieClipLoader. Finally, the image is downloaded and
triggered when you call the MovieClipLoader.loadClip() method, which specifies the
image file to load and the target movie clip to load the image into.
Make sure that Flash and HTML are both selected in the Publish Settings dialog box.
Select File > Publish Settings and then click the Formats tab. Then, select both
options.
5. If you test your document in the Flash tool (select Control > Test Movie) or in a local
browser (File > Publish Preview > HTML), you will see that the image centers itself both
vertically and horizontally on the Stage.
6. Edit the generated HTML document in an editor (such as Dreamweaver or Notepad), and
modify the default HTML to match the following text:
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
codebase="http://fpdownload.adobe.com/pub/shockwave/cabs/flash/
swflash.cab#version=8,0,0,0" width="550" height="400" id="imgloader"
align="middle">
<param name="allowScriptAccess" value="sameDomain" />
<param name="movie" value="imgloader.swf" />
<param name="FlashVars" value="imgURL=http://www.helpexamples.com/flash/
images/image2.jpg">
<param name="quality" value="high" />
<param name="bgcolor" value="#ffffff" />
<embed src="imgloader.swf" quality="high" FlashVars="imgURL=http://
www.helpexamples.com/flash/images/image2.jpg" bgcolor="#ffffff"
width="550" height="400" name="imgloader" align="middle"
allowScriptAccess="sameDomain" type="application/x-shockwave-flash"
pluginspage="http://www.adobe.com/go/getflashplayer" />
</object>
7. Test the HTML document to see the changes. An image that you specify in the HTML
code appears in the SWF file.
To modify this example to use your own images, you would modify the FlashVars value
(the string inside the double quotes).
About variables 71
Organizing data in objects
You might already be used to objects that you place on the Stage. For example, you might
have a MovieClip object on the Stage, and this object contains other movie clips inside it. Text
fields, movie clips, and buttons are often called objects when you place them on the Stage.
Objects, in ActionScript, are collections of properties and methods. Each object has its own
name, and it is an instance of a particular class. Built-in objects are from classes that are
predefined in ActionScript. For example, the built-in Date class provides information from
the system clock on the user’s computer. You can use the built-in LoadVars class to load
variables into your SWF file.
You can also create objects and classes using ActionScript. You might create an object to hold
a collection of data, such as a person’s name, address. and telephone number. You might create
an object to hold color information for an image. Organizing data in objects can help keep
your Flash documents more organized. For general information on creating a custom class to
hold a collection of methods and properties, see “Writing custom class files” on page 196. For
detailed information on both built-in and custom classes, see Chapter 6, “Classes,” on
page 187.
There are several ways to create an object in ActionScript. The next example creates simple
objects in two different ways, and then loops over the contents of those objects.
This code, which is one way to create a simple object, creates a new object instance and
defines a few properties within the object.
3. Now enter the following ActionScript after the code you entered in step 2.
// The second way
var secondObj:Object = {firstVar:"hello world", secondVar:28,
thirdVar:new Date(1980, 0, 1)};
This is another way of creating an object. Both objects are equivalent. This code above
creates a new object and initializes some properties using the object shorthand notation.
The variables might not necessarily appear in this order in the Output panel. You
cannot guarantee the ordering when you use a for..in loop; the player returns the
contents of an object in an unpredictable order.
You can also use arrays to create objects. Instead of having a series of variables such as
firstname1, firstname2, and firstname3 to represent a collection of variables, you can
make an array of objects to represent the same data. This technique is demonstrated next.
The benefit of organizing variables into arrays and objects is that it becomes much easier
to loop over the variables and see the values, as shown in the following step.
3. Type the following code after the ActionScript you added in step 2.
var i:Number;
for (i = 0; i < usersArr.length; i++) {
trace(usersArr[i].firstname); // George, John, Thomas
}
4. Select Control > Test Movie, and the following text appears in the Output panel:
George
John
Thomas
For information on creating for loops, see Chapter 4, “Using for loops,” on page 119. For
information on for..in loops, see “Using for..in loops” on page 120. For more information on
objects, see Chapter 6, “Classes,” on page 187.
About casting
ActionScript 2.0 lets you cast one data type to another. Casting an object to a different type
means you convert the value that the object or variable holds to a different type.
The results of a type cast vary depending on the data types involved. To cast an object to a
different type, you wrap the object name in parentheses (()) and precede it with the name of
the new type. For example, the following code takes a Boolean value and casts it to an integer.
var myBoolean:Boolean = true;
var myNumber:Number = Number(myBoolean);
In this example, you asserted to the compiler that foo is a Dog object, and therefore the
compiler assumes that foo.bark(); is a legal statement. However, the compiler doesn’t know
that the cast will fail (that is, that you tried to cast a Cat object to an Animal type), so no
compile-time error occurs. However, if you include a check in your script to make sure that
the cast succeeds, you can find casting errors at runtime, as shown in the following example.
function bark(myAnimal:Animal) {
var foo:Dog = Dog(myAnimal);
if (foo) {
foo.bark();
}
}
You can cast an expression to an interface. If the expression is an object that implements the
interface or has a base class that implements the interface, the cast succeeds. If not, the cast
fails.
NOT E
You can’t override primitive data types that have a corresponding global conversion function
with a cast operator of the same name. This is because the global conversion functions have
precedence over the cast operators. For example, you can’t cast to Array because the Array()
conversion function takes precedence over the cast operator.
About casting 75
This example defines two string variables (firstNum and secondNum), which are added
together. The initial result is that the numbers are concatenated instead of added because they
are a String data type. The second trace statement converts both numbers to a Number data
type before performing the addition that yields the proper result. Data conversion is
important when working with data loaded using XML or FlashVars, as shown in the following
example:
var firstNum:String = "17";
var secondNum:String = "29";
trace(firstNum + secondNum); // 1729
trace(Number(firstNum) + Number(secondNum)); // 46
For more information on data conversion functions, see the entry for each conversion
function in ActionScript 2.0 Language Reference: Array function, Boolean function,
Number function, Object function, and String function.
You add ActionScript directly to a frame on the Timeline within this chapter. In later
chapters, you use classes to separate your ActionScript from the FLA file.
77
For more information on working with ActionScript syntax and language fundamentals, see
the following topics:
About syntax, statements, and expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
About dot syntax and target paths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
About language punctuators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
About constants and keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
About statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
About arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
About operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
In the previous expression, x and 2 are operands and + is an operator. For more information
on operators and operands, see “About operators” on page 137. For more information on
objects and properties, see “Object data type” on page 42.
The way you format your ActionScript also determines how maintainable your code is. For
example, it’s difficult to read the logic of a FLA file that doesn’t contain indents or comments,
or contains inconsistent formatting and naming conventions. When you indent blocks of
ActionScript (such as loops and if statements), the code is easier to read and debug if you
encounter problems. For more information about formatting ActionScript, see “Formatting
ActionScript syntax” on page 697. You can also see proper formatting of ActionScript in
these sections.
For more information on syntax and language fundamentals, see the following topics:
■ “Differences between ActionScript and JavaScript”
■ “About case sensitivity”
Case sensitivity also affects external variables that you load into a SWF file, such as
those loaded with LoadVars.load().
Case sensitivity is implemented for external scripts, such as ActionScript 2.0 class files, scripts
that you import using the #include command, and scripts in a FLA file. If you encounter
runtime errors and are exporting to more than one version of Flash Player, you should review
both external script files and scripts in FLA files to confirm that you used consistent
capitalization.
Case sensitivity is implemented on a per-SWF file basis. If a strict (case-sensitive) Flash Player
8 application calls a nonstrict Flash Player 6 SWF file, ActionScript executed in the Player 6
SWF file is nonstrict. For example, if you use loadMovie() to load a Flash Player 6 SWF file
into a Flash Player 8 SWF file, the version 6 SWF file remains case-insensitive, while the
version 8 SWF file is treated as case-sensitive.
When syntax coloring is enabled, language elements written with correct capitalization are
blue by default. For more information, see “About reserved words” on page 103.
This code creates a new movie clip and assigns it the instance name pic_mc. Then, you can
manipulate the pic_mc instance using code, such as loading an image into it as demonstrated
in the previous code.
For more information on working with scope, see “About scope and targeting” on page 87
and “About variables and scope” on page 60.
Targeting an instance
If you want something to work in your SWF file, you need to target that instance and then
tell it to do something, such as assigning it an action or changing its properties. You usually
need to define where that instance is in the SWF file (for example, what timeline it’s on or
what instance it’s nested within) by creating the target path. Remember that you have given
many of the instances in your FLA file instance names, and then you added code to the FLA
file that uses those instance names. When you do this, you target that particular instance and
then tell it to do something (such as move the playhead or open a web page). For more
information on objects and properties, see “Object data type” on page 42.
To target an instance:
1. Select File > New and select Flash Document.
2. Select File > Save As and name the file target.fla.
3. Use the Oval tool to draw a shape on the Stage. Draw an oval of any size and color.
4. Use the Selection tool to select the oval on the Stage.
TIP
This line of code targets the myClip instance on the Stage. The ActionScript scales the
instance to half its original width. Because the ActionScript is on the same timeline as the
movie clip symbol, you only need to target the instance using the instance name. If the
instance was on a different timeline or nested within another instance, you would need to
modify the target path accordingly.
This ActionScript resizes the myOtherClip instance to 50% of its current width. Because
the target.fla file modified the myClip instances _xscale property, and the myOtherClip
is a nested symbol, you’ll notice that myOtherClip will be 25 percent of the
original width.
Notice that the clip that you manipulate (such as nestedClip) appears right before the
action. You’ll notice this trend in upcoming sections.
You aren’t limited to accessing predefined methods and properties of instances on the Stage, as
demonstrated in the previous examples. You can also set a variable within a movie clip, as seen
in the following code, which sets a variable in the starClip movie clip:
starClip.speed = 1.1;
starClip.gravity = 0.8;
If either the speed or gravity variables existed previously in the starClip movie clip instance,
the previous values would have been overwritten as soon as the new values were set. You are
able to add new properties to the starClip movie clip, because the MovieClip class was defined
with the dynamic keyword. The dynamic keyword specifies that objects based on the
specified class (in this case MovieClip) can add and access dynamic properties at runtime. For
more information about the dynamic statement, see dynamic statement in the ActionScript
2.0 Language Reference.
This code loads an image into the rotateClip movie clip that you created with code. You’re
targeting the rotateClip instance with ActionScript.
7. Select Control > Test Movie to test your document.
Now you should see an image on the Stage that rotates 50º clockwise.
You can also target or identify parts of SWF files that you load into a base SWF file.
It’s generally a good idea to avoid using levels if you can load content into movie clips
at different depths instead. Using the MovieClip.getNextHighestDepth() method
enables you to create new movie clip instances on the Stage dynamically without
having to check whether there is already an instance at a particular depth.
You can express a method or property of a particular object (such as a movie clip or text field)
using this pattern. For example, the property of an object would be
myClip._alpha = 50;
Optionally, you can drop the this keyword, and just use
myClip
You might choose to add the this keyword for readability and consistency. For more
information on recommended coding practices, see Chapter 17, “Best Practices and Coding
Conventions for ActionScript 2.0,” on page 665.
If you trace the movie clip, for either snippet above you see _level0.myClip in the Output
panel. However, if you have ActionScript that’s inside the myClip movie clip but you want to
target the main timeline, target the parent of the movie clip (which is the main Stage).
Double-click a movie clip, and place the following ActionScript on the movie clip’s timeline:
trace("me: " + this);
trace("my parent: " + this._parent);
Test the SWF file, and you’ll see the following message in the Output panel:
me: _level0.myClip
my parent: _level0
This indicates you targeted the main timeline. You can use parent to create a relative path to
an object. For example, if the movie clip dogClip is nested inside the animating movie
clip animalClip, the following statement on the instance dogClip tells animalClip to
stop animating:
this._parent.stop();
If you're familiar with Flash and ActionScript, you’ve probably noticed people using the
_root scope. The _root scope generally refers to the main timeline of the current Flash
document. You should avoid using the _root scope unless it’s absolutely necessary. You can
use relative target paths instead of _root.
If you use _root in your code, you can encounter errors if you load the SWF file into another
Flash document. When the SWF file loads into a different SWF file, _root in the loaded file
might point to the root scope of the SWF file it loads into, instead of referring to its own root
as you intend it to. This can lead to unpredictable results, or break functionality altogether.
You can omit the semicolon character and the ActionScript compiler assumes that each line of
code represents a single statement. However, it is good scripting practice to use semicolons
because it makes your code more readable. When you click the Auto Format button in the
Actions panel or Script window, trailing semicolons are appended to the end of your
statements by default.
NOT E
Using a semicolon to terminate a statement allows you to place more than one statement
on a single line, but doing so usually makes your code more difficult to read.
Another place you use semicolons is in for loops. You use the semicolon to separate
parameters, as shown in the following example. The example loops from 0 to 9 and then
displays each number in the Output panel:
var i:Number;
for (i = 0; i < 10; i++) {
trace(i); // 0,1,...,9
}
You use colons (:) in your code to assign data types to your variables. To assign a specific data
type to an item, specify its type using the var keyword and post-colon syntax, as shown in the
following example:
// strict typing of variable or object
var myNum:Number = 7;
var myDate:Date = new Date();
// strict typing of parameters
function welcome(firstName:String, myAge:Number) {
}
// strict typing of parameter and return value
function square(num:Number):Number {
var squared:Number = num * num;
return squared;
}
You can also specify that objects are of the Function or the Void data type. For more
information on assigning data types, see Chapter 3, “Data and Data Types,” on page 35.
Curly braces
You group ActionScript events, class definitions, and functions into blocks using curly brace
({}) punctuators. You put the opening brace on the same line as the declaration.
N OTE
You can also put the opening brace on the line that follows the declaration. Coding
conventions recommend that you put the opening brace on the same line for
consistency. For information on braces and code conventions, see Chapter 17, “Best
Practices and Coding Conventions for ActionScript 2.0,” on page 665.
Place braces around each statement when it is part of a control structure (such as if..else or
for), even if it contains only a single statement. This good practice helps you avoid errors in
your ActionScript when you forget to add braces to your code. The following example shows
code that is written using poor form:
var numUsers:Number;
if (numUsers == 0)
trace("no users found.");
Although this code validates, it is considered poor form because it lacks braces around
the statements.
TIP
Braces are added to this statement if you click the Auto Format button.
In this case, if you add a second statement after the trace statement, the second statement
executes regardless of whether the numUsers variable equals 0, which can lead to unexpected
results. For this reason, add braces so the code looks like the following example:
var numUsers:Number;
if (numUsers == 0) {
trace("no users found");
}
The next example displays a simple class file that could be used to create a Student object. You
learn more about class files in Chapter 6, “Classes,” on page 187.
You can also use empty curly braces as a syntax shortcut for the new Object() function. For
example, the following code creates an empty Object instance:
var myObject:Object = {};
TIP
Remember to make sure each opening curly brace has a matching closing brace.
Parentheses
When you define a function in ActionScript, you place parameters inside parentheses [()]
punctuators, as shown in the following lines of code:
function myFunction(myName:String, myAge:Number, happy:Boolean):Void {
// Your code goes here.
}
When you call a function, you also include any of the parameters you pass to the function in
parentheses, as shown in the following example:
myFunction("Carl", 78, true);
You can use parentheses to override the ActionScript order of precedence or to make your
ActionScript statements easier to read. This means you can change the order in which values
are computed by placing brackets around certain values, as seen in the following example:
var computedValue:Number = (circleClip._x + 20) * 0.8;
As with brackets and braces, you need to make sure each opening parentheses has a closing
parentheses.
About literals
A literal is a value that appears directly in your code. Literals are constant (unchanging) values
within your Flash documents. Examples of a literal include true, false, 0, 1, 52, or even the
string “foo”.
The following examples are all literals:
17
"hello"
-3
9.4
null
undefined
true
false
Literals can also be grouped to form compound literals. Array literals are enclosed in bracket
punctuators ([]) and use the comma punctuator (,) to separate array elements. An array
literal can be used to initialize an array. The following examples show two arrays that are
initialized using array literals. You can use the new statement and pass the compound literal as
a parameter to the Array class constructor, but you can also assign literal values directly when
instantiating instances of any built-in ActionScript class.
// using new statement
var myStrings:Array = new Array("alpha", "beta", "gamma");
var myNums:Array = new Array(1, 2, 3, 5, 8);
Use string literals unless you specifically need to use a String object for better performance.
For more information on strings, see “About strings and the String class” on page 411.
About comments
Comments are a way of annotating your code with plain-English descriptions that do not get
evaluated by the compiler. You can use comments within your code to describe what the code
is doing or to describe which data returns to the document. Using comments can help you
remember important coding decisions, and it can be helpful to anyone else who reads your
code. Comments must clearly explain the intent of the code and not just translate the code. If
something is not readily obvious in the code, you should add comments to it.
Using comments to add notes to scripts is highly recommended. Comments document the
decisions you make in the code, answering both how and why. They make ActionScript easier
to understand. For example, you might describe a work-around in comments. Therefore, you
or another developer can easily find sections of code to update or fix. Or, if the issue is fixed or
improved in a future version of Flash or Flash Player, you could improve the ActionScript by
removing the work-around.
Single-line comments
You use single-line comments to add a comment to a single line in your code. You might
comment out a single line of code, or add a short description of what a piece of code
accomplishes. To indicate that a line or portion of a line is a comment, precede the comment
with two forward slashes (//), as shown in the following code:
// The following sets a local variable for age.
var myAge:Number = 26;
Single-line comments are typically used to explain a small code snippet. You can use single-
line comments for any short comments that fit on a single line. The following example
includes a single-line comment:
while (condition) {
// handle condition with statements
}
If you place the comment characters (/* and */) on separate lines at the beginning and
end of the comment, you can easily comment them out by placing double slash
characters (//) in front of them (for example, ///* and //*/). These let you quickly and
easily comment and uncomment your code.
By placing large chunks of script in a comment block, called commenting out a portion of your
script, you can test specific parts of a script. For example, when the following script runs,
none of the code in the comment block executes:
// The following code runs.
var x:Number = 15;
var y:Number = 20;
Space the comments to the right so readers can distinguish them from the code. Try to have
the comments line up with each other, if possible, as shown in the following code.
var myAge:Number = 28; // my age
var myCountry:String = "Canada"; // my country
var myCoffee:String = "Hortons"; // my coffee preference
If you use autoformatting (click the Auto Format button in the Actions panel), trailing
comments move to the next line. Add these comments after you format your code, or you
must modify their placement after using the Auto Format button.
Use block comments to describe files, data structures, methods, and descriptions of files. They
are usually placed at the beginning of a file and before or within a method.
There are two kinds of comments in a typical class or interface file: documentation comments
and implementation comments. Documentation comments are used to describe the code’s
specifications and do not describe the implementation. You use documentation comments to
describe interfaces, classes, methods, and constructors. Implementation comments are used to
comment out code or to comment on the implementation of particular sections of code.
Don’t include comments that do not directly relate to the class being read. For example,
do not include comments that describe the corresponding package.
You can also use single-line comments, block comments, and trailing comments in class files.
For more information on these kinds of comments, see the following sections:
■ “Single-line comments” on page 96
■ “Multiline comments” on page 97
■ “Trailing comments” on page 98
Using constants
Constants are properties with a fixed value that cannot be altered; in other words, they are
values that don’t change throughout an application. The ActionScript language contains many
predefined constants. For example, the constants BACKSPACE, ENTER, SPACE, and TAB are
properties of the Key class and refer to keyboard keys. The constant Key.TAB always has the
same meaning: it indicates the Tab key on a keyboard. Constants are useful for comparing
values and for using values in your application that do not change.
To test whether the user is pressing the Enter key, you could use the following statement:
var keyListener:Object = new Object();
keyListener.onKeyDown = function() {
if (Key.getCode() == Key.ENTER) {
trace("Are you ready to play?");
}
};
Key.addListener(keyListener);
For the previous ActionScript to work, it may be necessary to disable keyboard shortcuts in
the authoring environment. Select Control > Test Movie from the main menu, then while
previewing the SWF file in the player, select Control > Disable Keyboard Shortcuts from the
SWF file’s preview window.
In Flash there is no way to create your own constant values except when you create your own
custom classes with private member variables. You cannot create a “read-only” variable
within Flash.
Variables should be lowercase or mixed-case letters; however, constants (variables that do not
change) should be uppercase. Separate words with underscores, as the following ActionScript
shows:
var BASE_URL:String = "http://www.adobe.com"; //constant
var MAX_WIDTH:Number = 10; //constant
Write static constants in uppercase, and separate words with an underscore. Do not directly
code numerical constants unless the constant is 1, 0, or -1, which you might use in a for loop
as a counter value.
You can use constants for situations in which you need to refer to a property whose value
never changes. This helps you find typographical mistakes in your code that you might not
find if you use literals. It also lets you change the value in a single place. For more information
on literals, see “About literals” on page 94.
The EXAMPLE_STATIC property is a static property, which means that the property applies
to the class as a whole instead of to a particular instance of the class. You must access a
static property of a class using the name of the class instead of the name of an instance.
You cannot access a static property through a class instance.
4. Create a new Flash document and save it as const.fla.
5. Open the Actions panel, and type the following code on Frame 1 of the Timeline:
trace(ConstExample.EXAMPLE_STATIC); // output: Global access
When you declare the EXAMPLE_STATIC property as static, you use this code to access the
value of the property.
6. Select Control > Test Movie to test your document.
You will see Global access in the Output panel.
7. In the Actions panel, type this code following the code you added in step 5.
trace(ConstExample.EXAMPLE_PUBLIC); // error
trace(ConstExample.EXAMPLE_PRIVATE); // error
To access a property that is not static, you must access the value through an instance of the
class. Because the EXAMPLE_PUBLIC property is a public property, it is available to code
outside of the class definition.
9. In the Actions panel, delete the trace statements that you added in steps 5 and 7.
This code instantiates the myExample instance and accesses the EXAMPLE_PUBLIC
property.
11. Select Control > Test Movie to test your document.
You see Public access in the Output panel.
12. In the Actions panel, delete the trace statement that you added in step 10.
13. Type the following code into the Actions panel.
trace(myExample.EXAMPLE_PRIVATE); // error
About keywords
Keywords are words in ActionScript that do one specific thing. For example, you use the var
keyword to declare a variable. The var keyword is shown in the following line of code:
var myAge:Number = 26;
A keyword is a reserved word that has a specific meaning: for example, you use the class
keyword to define new a new ActionScript class; and you use the var keyword to declare local
variables. Other examples of reserved keywords are: if, else, this, function, and return.
Keywords cannot be used as identifiers (such as variable, function, or label names), and you
should not use them elsewhere in your FLA files for other things (such as instance names).
You have already used the var keyword a lot, particularly if you read Chapter 3, “Data and
Data Types,” on page 35. ActionScript reserves words in the language for specific use.
Therefore, you can’t use keywords as identifiers (such as variable, function, or label names).
You can find a list of these keywords in “About reserved words” on page 103.
About statements
A statement is an instruction you give the FLA file to do something, such as to perform a
particular action. For example, you can use a conditional statement to determine whether
something is true or exists. Then your code might execute actions that you specify, such as
functions or expressions, based on whether the condition is true or not.
For example, the if statement is a conditional statement and evaluates a condition to
determine the next action that should occur in your code.
// if statement
if (condition) {
// statements;
}
Another example is the return statement, which returns a result as a value of the function in
which it executes.
There are many different ways for you to format or write ActionScript. You might differ from
someone else who writes ActionScript in the way you form syntax, such as the way you space
out your statements or where you put curly braces ({}) in your code. Even though there are
several different ways you can form statements without breaking your code, there are some
general guidelines you can follow to write well-formed ActionScript.
This ActionScript embeds an assignment within the code, which is difficult to read. If you
assign variables as separate statements, it improves readability, as the following example shows:
var a:Number = b + c;
var myNum:Number = a + d;
The following sections show you how to form specific statements in ActionScript. For
information on writing and formatting events, see Chapter 9, “Handling Events,” on
page 291.
For more information on each statement, see the following topics:
■ “About compound statements” on page 104
■ “About conditions” on page 105
■ “Repeating actions using loops” on page 115
This compound statement contains several statements, but acts like a single statement in your
ActionScript code. The opening brace is placed at the end of the compound statement. The
closing brace begins a line, and aligns with the beginning of the compound statement.
For more information on using braces, see “Curly braces” on page 90.
To optimize your code’s performance, check for the most likely conditions first.
The following statements test three conditions. The term else if specifies alternative tests to
perform if previous conditions are false.
if ((passwordTxt.text.length == 0) || (emailTxt.text.length == 0)) {
gotoAndStop("invalidLogin");
} else if (passwordTxt.text == userID){
gotoAndPlay("startProgram");
}
There are several times when you’ll use if statements when you work on a Flash project. For
example, if you are building a Flash site that requires users to log in before they can access
certain sections of a website, you can use an if statement to validate that the user enters some
text in the username and password fields.
If you need to validate user names and passwords using an external database, you probably
want to verify that the username/password combination a user submits matches a record in
the database. You also want to check whether the user has permission to access the specified
part of the site.
If you script animations in Flash, you might want to use the if statement to test whether an
instance on the Stage is still within the boundaries of the Stage. For example, if a ball moves
downward along the y-axis, you might need to detect when the ball collides with the bottom
edge of the Stage, so you can change the direction so that the ball appears to bounce upwards.
To use an if statement:
1. Select File > New and then select Flash Document.
If you do not want to execute an alternative block of code, you can use the if statement
without the else statement.
The if..else statement in Flash is similar to the if statement. For example, if you use the
if statement to validate that a user’s supplied user name and password matches a value stored
in a database, then you might want to redirect the user based on whether the user name and
password are correct. If the login is valid, you can redirect the user to a welcome page using
the if block. However, if the login was invalid, you can redirect the user to the login form and
display an error message using the else block.
You want to use an if..else if block in your Flash projects when you need to check a series
of conditions. For example, if you want to display a different image on the screen based on the
time of the day the user is visiting, you can create a series of if statements that determine if it’s
early morning, afternoon, evening, or night time. Then you can display an appropriate
graphic.
The following code not only tests whether the value of x exceeds 20 but also tests whether the
value of x is negative:
if (x > 20) {
trace("x is > 20");
} else if (x < 0) {
trace("x is negative");
}
The finally block executes even if the try block exits using a return statement
You write try..catch and try..catch..finally statements using the following format:
// try-catch
try {
// statements
} catch (myError) {
// statements
}
// try-catch-finally
try {
// statements
Any time your code throws an error, you can write custom handlers to handle the error
gracefully and take appropriate actions. You might need to try loading external data from a
web service or text file or to display an error message to the end user. You can even use the
catch block to try to connect to a web service that alerts an administrator that a particular
error occurred, so he or she can make sure the application works properly.
To use the try..catch..finally block for data validation before dividing some
numbers:
1. Select File > New and then select Flash Document.
2. Select Frame 1 of the Timeline, and then type the following ActionScript in the
Actions panel:
var n1:Number = 7;
var n2:Number = 0;
try {
if (n2 == 0) {
throw new Error("Unable to divide by zero");
}
trace(n1/n2);
} catch (err:Error) {
trace("ERROR! " + err.toString());
} finally {
delete n1;
delete n2;
}
5. Return to the authoring environment and change the following line of code:
var n2:Number = 0;
to
var n2:Number = 2;
6. Select Control > Enter to test the document again.
If the value of n2 equals zero, an error is thrown and is caught by the catch block, which
displays a message in the Output panel. If the value of y is not equal to zero, the Output
panel displays the result of n1 divided by n2. The finally block executes regardless of
whether an error occurs and deletes the values of the n1 and n2 variables from the
Flash document.
7. Save the Flash document and select Control > Test Movie to test the file in the test
environment.
Because the value of n2 equals 0, Flash throws your custom DivideByZeroException error
class and displays Divide By Zero error in the Output panel. If you change the value of
n2 in line two from 0 to -1, and retest the Flash document, you would see An unknown
error occurred; n2 cannot be less than zero in the Output panel. Setting the
value of n2 to any number greater than 0 causes the result of the division to appear in the
Output panel. For more information on creating custom classes, see Chapter 6, “Classes,”
on page 187.
Using a conditional expression, you would write the same code using this format:
var numOne:Number = 8;
var numTwo:Number = 0;
trace((numTwo > 0) ? numOne/numTwo : "carrot");
As you can see, the shortened syntax reduces readability, and so it is not preferable. If you
must use conditional operators, place the leading condition (before the question mark [?])
inside parentheses. This helps improve the readability of your ActionScript. The following
code is an example of ActionScript with improved readability:
var numOne:Number;
(numOne >= 5) ? numOne : -numOne;
You can write a conditional statement that returns a Boolean value, as the following
example shows:
if (cartArr.length > 0) {
return true;
} else {
return false;
}
However, compared with the previous code, the ActionScript in the following example
is preferable:
return (cartArr.length > 0);
The second snippet is shorter and has fewer expressions to evaluate. It’s easier to read
and understand.
The following code uses good form by adding parentheses around conditions:
if ((fruit == "apple") && (veggie == "leek")) {}
Loop Description
for loops Repeat an action using a built-in counter.
do..while loops Similar to while loops, except the expression evaluates at the bottom of
the code block, so the loop always runs at least once.
You can use the do..while statement to create the same kind of loop as a while loop. In
a do..while loop, the expression is evaluated at the bottom of the code block so that the
loop always runs at least once.
This is shown in the following example:
var i:Number = 4;
do {
myClip.duplicateMovieClip("newMC" + i, i, {_x:i*20, _y:i*20});
i--;
} while (i > 0);
For more information on the while statement, see “Using while loops” on page 122.
You might want your script to iterate over a particular type of child—for example, over
only movie clip children. You can do this using for..in with the typeof operator. In the
following example, a child movie clip instance (called instance2) is inside a movie clip
instance on the Stage. Add the following ActionScript to Frame 1 of the Timeline:
for (var myName in this) {
if (typeof (this[myName]) == "movieclip") {
trace("I have a movie clip child named " + myName);
}
}
Iterations in Flash execute very quickly in the Flash Player, but loops depend heavily
on the processor. The more iterations a loop has and the more statements executed
within each block, the more processor resources will be consumed. Poorly written
loops can cause performance problems and stability issues.
For more information on each statement, see the individual sections that follow in this
chapter, such as “Using while loops” on page 122, and their respective entries in the
ActionScript 2.0 Language Reference.
When you work with arrays, whether they’re simple or complex, you need to be aware of a
condition called an infinite loop. An infinite loop, as its name suggests, is a loop with no end
condition. This causes real problems—crashing your Flash application, causing your Flash
document to stop responding in a web browser, or causing very inconsistent behavior of your
Flash document. The following code is an example of an infinite loop:
// BAD CODE- creates an infinite loop
// USE AT OWN RISK!
var i:Number;
for (i = 0; i < 10; i--) {
trace(i);
}
The value of i is initialized to 0 and the end condition is met when i is greater than or equal
to 10 and after each iteration the value of i is decremented. You can probably see the obvious
error immediately: if the value of i decreases after each loop iteration, the end condition is
never met. The results vary on each computer you run it on, and the speed at which the code
fails depends on the speed of the CPU and other factors. For example, the loop executes about
142,620 times before displaying an error message on a given computer.
The following error message is displayed in a dialog box:
A script in this movie is causing Flash Player to run slowly. If it
continues to run, your computer may become unresponsive. Do you want to
abort the script?
You must supply three expressions to a for statement: a variable that is set to an initial value,
a conditional statement that determines when the looping ends, and an expression that
changes the value of the variable with each loop. For example, the following code loops five
times. The value of the variable i starts at 0 and ends at 4, and the output are the numbers 0
through 4, each on its own line.
var i:Number;
for (i = 0; i < 5; i++) {
trace(i);
}
In the next example, the first expression (i = 0) is the initial expression that evaluates before
the first iteration. The second expression (i < 5) is the condition that you check each time
before the loop runs. The third expression (i++) is called the post expression and is evaluated
each time after the loop runs.
6. Select Control > Test Movie to test the code in Flash Player.
Notice how five movie clips duplicate across the top of the Stage. This ActionScript
duplicates the movie clip symbol in the library and repositions the clips on the Stage at x
coordinates of 0, 100, 200, 300 and 400 pixels. The loop executes five times, with the
variable i assigned a value of 0 through 4. On the last iteration of the loop, the value of i
increments to 4 and the second expression (i < 5) is no longer true, which causes the
loop to exit.
Remember to include a space following each expression in a for statement. For more
information, see the for statement in the ActionScript 2.0 Language Reference.
For more information on objects and properties, see “Object data type” on page 42.
NOT E
The curly braces ({}) used to enclose the block of statements to be executed by the
for..in statement are not necessary if only one statement executes.
The following example uses for..in to iterate over the properties of an object:
3. Select Control > Test Movie to test the code in Flash Player.
When you test the SWF file, you should see the following text in the Output panel:
myObj.name = Tara
myObj.age = 27
myObj.city = San Francisco
If you write a for..in loop in a class file (an external ActionScript file), instance members are
not available within the loop, but static members are. However, if you write a for..in loop in
a FLA file for an instance of the class, instance members are available but static members are
not. For more information on writing class files, see Chapter 6, “Classes,” on page 187. For
more information, see the for..in statement in the ActionScript 2.0 Language Reference.
One disadvantage of using a while loop instead of a for loop is that infinite loops are easier
to write with while loops. The for loop example code does not compile if you omit the
expression that increments the counter variable, but the while loop example does compile if
you omit that step. Without the expression that increments i, the loop becomes an
infinite loop.
To create and use a while loop in a FLA file, follow this example.
For more information, see the while statement in the ActionScript 2.0 Language Reference.
1
name: Two
value: 2
You know how many items are in the array, so you can loop over each item using a simple
for loop. Because each object in the array can have different name/value pairs, you can
use a for..in loop to iterate over each value and display the results in the Output panel.
An array is like a structure for data. An array is like an office building, where each floor
contains a different piece of data (such as accounting on floor 3, and engineering on floor 5). As
such, you can store different kinds of data in a single array, including other arrays. Each floor
of this building can contain multiple kinds of content (executives and accounting might share
floor 3).
An array contains elements, which are equivalent to each floor of the building. Each element
has a numeric position (the index), which is how you refer to each element's position in the
array. This is similar to how each floor in a building has a floor number. Each element can
either hold a piece of data (which could be a number, string, Boolean value, or even an array
or object) or be empty.
You can also control and modify the array itself. For example, you might want to move the
engineering department to the basement of the building. Arrays let you move values around,
and they let you change the size of the array (say, renovate the building and add more floors or
remove floors). As such, you can add or remove elements and move values to different
elements.
Therefore, the building (the array) contains floors (the elements), which are numbered floors
(the index), and each floor contains one or more departments (the values).
Using arrays
There are several different ways you can use arrays in your work. You can use them to store
lists of objects, such as a bunch of returned items. If you load data from remote web servers,
you might even receive data as an array of nested objects. Often, arrays contain data in a
similar format. For example, if you build an audio application in Flash, you might have a
user’s playlist stored as an array of song information, stored in objects. Each object contains
the song name, artist name, song duration, location of a sound file (such as an MP3), or any
other information that you might need to associate with a particular file.
The location of an item in an array is called the index. All arrays are zero-based, which means
that the first element in the array is [0], the second element is [1], and so on.
There are different kinds of arrays, which you'll discover in the following sections. The most
common arrays use a numerical index to look up a particular item in an indexed array. The
second kind of array is called an associative array and uses a text index instead of a numerical
index to look up information. For more information on common arrays, see “About arrays”
on page 125. For more information on associative arrays, see “Creating associative arrays”
on page 134. For more information on multidimensional arrays, see “Creating
multidimensional arrays” on page 131. For information on the array access operator, see
“Using dot and array access operators” on page 145.
The built-in Array class lets you access and manipulate arrays. To create an Array object, you
use the constructor new Array() or the array access operator ([]). To access the elements of
an array, you also use the array access ([]) operator. The next example uses an indexed array.
In the first line of ActionScript, you define a new array to hold the values. Then, you
define data (value0 and value1) at two indexes of the array. You use a for..in loop to
iterate over each of the items in that array and display the key/value pairs in the Output
panel using a trace statement.
3. Select Control > Test Movie to test your code.
The following text is displayed in the Output panel:
key: 0, value: value0
key: 1, value: value1
For more information on for..in loops, see “Using for..in loops” on page 120.
For information on how to create different kinds of arrays, see the following sections:
■ “Creating indexed arrays” on page 130
■ “Creating multidimensional arrays” on page 131
■ “Creating associative arrays” on page 134
For a sample source file, array.fla, that illustrates array manipulation using ActionScript, see
the Flash Samples page at www.adobe.com/go/learn_fl_samples. Download and decompress
the Samples zip file and navigate to the ActionScript2.0/Arrays folder to access the sample.
The code in the sample creates an array and sorts, adds, and removes items of two List
components.
You might wonder why you need to create a temporary variable in the previous example. If
you copied the contents of array index 4 into array index 2 and vice versa, the original
contents of array index 2 would be lost. When you copy the value from one of the array
indexes into a temporary variable, you can save the value and safely copy it back later in your
code. For example, if you use the following code instead, you can see that the value of array
index 2 (Accounting) has been lost. Now you have two engineering teams but no accountants.
// wrong way (no temporary variable)
buildingArr[2] = buildingArr[4];
buildingArr[4] = buildingArr[2];
trace(buildingArr); //
undefined,undefined,Engineering,undefined,Engineering
For a sample source file, array.fla, that illustrates array manipulation using ActionScript, see
the Flash Samples page at www.adobe.com/go/learn_fl_samples. Download and decompress
the Samples zip file and navigate to the ActionScript2.0/Arrays folder to access the sample.
The code in the sample creates an array and sorts, adds, and removes items of two List
components.
In the previous example, you create an array and populate it with month names. The contents
are displayed, and also the array’s length. A for loop iterates over each item in the array and
converts the value to uppercase, and the array contents are displayed again.
For more information on for loops, see “Using for loops” on page 119. For information on
the array access operator, see “Using dot and array access operators” on page 145.
For a sample source file, array.fla, that illustrates array manipulation using ActionScript, see
the Flash Samples page at www.adobe.com/go/learn_fl_samples. Download and decompress
the Samples zip file and navigate to the ActionScript2.0/Arrays folder to access the sample.
The code in the sample creates an array and sorts, adds, and removes items of two List
components.
Even though you deleted the item at array index 5, the array length is still 12, and the item at
array index 5 changed to a blank string instead of disappearing completely.
In the first line of ActionScript, you define a new array to hold the values.
3. Select Control > Test Movie to test your code.
The following text is displayed in the Output panel:
one,two,three
4. Return to the authoring tool, and delete the code in the Actions panel.
5. Add the following ActionScript to Frame 1 of the Timeline:
var myArray:Array = ["one", "two", "three"];
trace(myArray); // one,two,three
In this code you use the array literal to define a new array for your code. This code is the
equivalent of the ActionScript you wrote in step 2. When you test the code, you see the
same output appear in the Output panel.
If you want to store a separate list of tasks for each day of the week, you can create a
multidimensional array with one element for each day of the week. Each element contains an
indexed array that stores the list of tasks.
C A U T IO N
When you use the array access operator, the ActionScript compiler cannot check
whether the accessed element is a valid property of the object.
To create a basic multidimensional array and retrieve elements from the array:
1. Create a new Flash document, and save it as multiArray1.fla.
2. Add the following ActionScript to Frame 1 of the Timeline:
var twoDArray:Array = new Array(new Array("one","two"), new
Array("three", "four"));
trace(twoDArray);
This array, twoDArray, consists of two array elements. These elements are themselves
arrays consisting of two elements. In this case, twoDArray is the main array that contains
two nested arrays.
3. Select Control > Test Movie to test the code. You see the following display in the
Output panel.
one,two,three,four
4. Return to the authoring tool and open the Actions panel. Comment out the trace
statement, as shown below:
// trace(twoDArray);
To retrieve elements of a multidimensional array, you use multiple array access ([])
operators after the name of the top-level array. The first [] refers to the index of the top-
level array. Subsequent array access operators refer to elements of nested arrays.
6. Select Control > Test Movie to test the code. You see the following display in the
Output panel.
one
four
You can use nested for loops to create multidimensional arrays. The next example shows
you how.
This ActionScript creates a 3 x 3 array and sets the value of each array node to its index.
Then you trace the array (mainArr).
3. Select Control > Test Movie to test the code.
You see the following display in the Output panel:
[0][0],[0][1],[0][2],[1][0],[1][1],[1][2],[2][0],[2][1],[2][2]
You can also use nested for loops to iterate through the elements of a multidimensional array,
as shown in the next example.
In this code, seen in the previous example, the outer loop iterates through each element
of mainArray. The inner loop iterates through each nested array and outputs each
array node.
3. Add the following ActionScript to Frame 1 of the Timeline, following the code you entered
in step 2:
// iterate through elements
var outerArrayLength:Number = mainArr.length;
for (i = 0; i < outerArrayLength; i++) {
var innerArrayLength:Number = mainArr[i].length;
for (j = 0; j < innerArrayLength; j++) {
trace(mainArr[i][j]);
}
}
This ActionScript iterates through the elements of the array. You use the length property
of each array as the loop condition.
4. Select Control > Test Movie to view the elements that are displayed in the Output panel.
You will see the following in the Output panel:
[0][0]
[0][1]
[0][2]
[1][0]
[1][1]
[1][2]
[2][0]
[2][1]
[2][2]
For information on using arrays, see “Using arrays” on page 126. For information on array
elements, see “About adding and removing elements” on page 129. For information on the
array access operator, see “Using dot and array access operators” on page 145.
Associative arrays are unordered collections of key and value pairs. Your code should
not expect the keys of an associative array to be in a specific order.
When you use associative arrays, you can call the array element you need using a string rather
than a number, which is often easier to remember. The downside is that these arrays aren't as
useful in a loop because they do not use numbers as the index value. They are useful when you
need to look up by key values frequently. For example, if you had an array of names and ages
that you needed to refer to a lot, you might use an associative array.
The following example demonstrates how to create an object and define a series of properties
in an associative array.
You can access variables in an associative array using two different methods: dot
syntax (someObj.myColor) and array syntax (someObj[‘myColor’]).
If you use the Object constructor to create an associative array, you can take advantage of
initializing your array with an object literal. An instance of the Object class, also called a
generic object, is functionally identical to an associative array. In fact, Object instances are
essentially associative arrays. You might use associative arrays for dictionary-like functionality,
when it’s more convenient to have string keys rather than numerical indices. Each property
name of the generic object serves as the key that provides access to a stored value. For more
information on literals, see “About literals” on page 94. For more information on classes, see
Chapter 6, “Classes,” on page 187.
If you do not need to initialize the array at declaration time, you can use the Object
constructor to create the array:
4. Add the following ActionScript to Frame 1 of the Timeline, following the code you entered
previously:
monitorInfo["aspectRatio"] = "16:10";
monitorInfo.colors = "16.7 million";
trace(monitorInfo["aspectRatio"] + ", " + monitorInfo.colors);
After you use using either an object literal or the Object class constructor to create the
array, you can add new values to the array using either the bracket operator ([]) or the dot
operator (.), as demonstrated in this code. The code you just typed adds two new values
to monitorInfo array.
5. Select Control > Test Movie.
The Output panel displays the following text:
16:10, 16.7 million
Note that a key can contain a space character. This is possible with the bracket operator,
but generates an error if you attempt this with the dot operator. Using spaces in your key
names is not recommended. For more information on bracket operators and dot
operators, see “About operators” on page 137. For more information on well-formatted
code, see “Formatting ActionScript syntax” on page 697.
The second way to create an associative array is to use the Array constructor and then use
either the bracket operator ([]) or the dot operator (.) to add key and value pairs to the array.
If you declare your associative array to be of type Array, you cannot use an object literal to
initialize the array.
NO TE
There is no advantage to using the Array constructor to create an associative array. The
Array constructor is best for creating indexed arrays.
The next example demonstrates how to use the Array constructor to create an
associative array.
This code creates an associative array named monitorInfo using the Array constructor
and adds a key called type and a key called resolution, along with their values.
3. Select Control > Test Movie.
The Output panel displays the following text:
Flat Panel, 1600 x 1200
NO TE
Associative arrays are essentially instances of the Object class, and there is no advantage of
creating associative arrays using the Array constructor. Even though you create an associative
array using the new Array() constructor, you cannot use any of the Array class’s methods and
properties (such as sort() or length) when using an associative array. If you want to use key/
value pairs instead of a numeric index, you should use the Object class instead of an
associative array.
About operators
This section describes general rules about common types of operators, operator precedence,
and operator associativity.
Operators are characters that specify how to combine, compare, or change values in an
expression. An expression is any statement that Flash can evaluate and that returns a value.
You can create an expression by combining operators and values or by calling a function. For
more information on expressions, see “About syntax, statements, and expressions” on page 78.
For example, a mathematical expression uses numerical operators to manipulate the values
you use. Examples of operator characters are +, <, *, and =. An expression consists of operators
and operands, and they are any legal combination of ActionScript symbols that represent a
value. An operand is the part of your code that the operator performs actions on. For example,
in the expression x + 2, x and 2 are operands and + is an operator.
This section describes how to use each type of operator; however, there isn't space to
cover each one. For information on every operator, including special operators that don’t
fall into the following categories, see the ActionScript 2.0 Language Reference.
The parts of your code that the operator performs actions on are called operands. For example,
you can use the addition (+) operator to add values of a numeric literal. You could do this to
add the value of a variable called myNum.
myNum + 3;
// example two
var secondScore:Number = 1;
secondScore += 3;
trace("Example two: " + secondScore); // 4
The addition operator is fairly straightforward, because it adds two values together. In the
first code example, it adds the current value of myScore and the number 1, and then stores
the result into the variable myScore.
Notice that the previous code snippet doesn’t have assignment operators. It relies on the
increment operator instead.
You can manipulate the value of a variable using operators while a condition is true. For
example, you can use the increment operator (++) to increment the variable i while the
condition is true. In the following code, the condition is true while i is less than the value of
10. While that is true, you increment i one number higher using i++.
var i:Number;
for (i = 1; i < 10; i++) {
trace(i);
}
The Output panel displays the numbers 1 through 9, which is i incrementing in value until it
reaches the end condition (i is equal to 10), when it stops. The last value displayed is 9.
Therefore, the value of i is 1 when the SWF file starts playing, and 9 after the trace completes.
For more information on conditions and loops, see “About statements” on page 103.
You see the output of this statement is 14, because multiplication has a higher operator
precedence. Therefore, 4 * 3 is evaluated first and the result is added to 2.
You can control what happens by enclosing expressions in parentheses. ActionScript defines a
default operator precedence that you can alter using the parentheses (()) operator. When you
put parentheses around the addition expression, ActionScript performs the addition first:
var mySum:Number;
mySum = (2 + 4) * 3;
trace(mySum); // 18
You might encounter situations in which two or more operators of the same precedence
appear in the same expression. In these cases, the compiler uses the rules of associativity to
determine which operator to process first. All of the binary operators, except the assignment
operators, are left-associative, which means that operators on the left are processed before
operators on the right. The assignment operators and the conditional (?:) operator are right-
associative, which means that the operators on the right are processed before operators on the
left. For more information on assignment operators, see “Using assignment operators”
on page 155. For more information on the conditional (?:) operator, see “About the
conditional operator” on page 160.
The greater than (>) operator is processed first, which results in a value of true because the
operand 3 is greater than the operand 2. The value true is then passed to the less than (<)
operator, along with the operand 1. The less than (<) operator converts the value true to the
numeric value 1 and compares that numeric value to the second operand 1 to return the value
false (the value 1 is not less than 1).
Consider the order of operands in your ActionScript, particularly when you set up complex
conditions and you know how often one of those conditions is true. For example, if you know
that i will be greater than 50 in your condition, you need to write i<50 first. Therefore, it’s
checked first, and the second condition that you write doesn’t need to be checked as often.
The following table lists the operators for ActionScript 2.0 in order of decreasing precedence.
Each row of the table contains operators of the same precedence. Each row of operators has
higher precedence than the row appearing below it in the table. For more information and
guidelines on using operators and parentheses, see Chapter 17, “Formatting ActionScript
syntax,” on page 697.
Group Operators
Primary [] {x:y} () f(x) new x.y x[y]
Multiplicative * / %
Additive + -
Bitwise XOR ^
Bitwise OR |
Logical OR ||
Comma ,
In this ActionScript, the sort() method of the Array class reorders the contents of the array
alphabetically. You can see that the value “Egg” comes before the value “chicken” because
uppercase E comes before a lowercase c. If you want to compare the strings regardless of case,
you need to convert the strings to uppercase or lowercase before you compare them. For more
information on comparison operators, see “About equality operators” on page 150 and “Using
relational and equality operators” on page 151.
Comparison operators compare only two strings. For example, the operators do not
compare the values if one operand is a numerical value. If one of the operands is a string,
ActionScript converts both operands to numbers and then compares them numerically.
You can use operators to manipulate strings. You can use the addition (+) operator to
concatenate string operands. You might have already used the addition operator to
concatenate strings when you write trace statements. For example, you might write the
following:
var myNum:Number = 10;
trace("The variable is " + myNum + ".");
When you test this code, the Output panel displays the following:
The variable is 10.
In the previous example, the trace statement uses the + operator to concatenate instead of
add. When you deal with strings and numbers, Flash sometimes concatenates instead of
adding numerically.
For example, you might concatenate two strings from different variables in a single text field.
In the following ActionScript code, the variable myNum concatenates with a string, and the
string is displayed in the myTxt text field on the Stage.
this.createTextField("myTxt", 11, 0, 0, 100, 20);
myTxt.autoSize = "left";
var myNum:Number = 10;
myTxt.text = "One carrot. " + myNum + " large eggplants.";
myTxt.text += " Lots of vegetable broth.";
This code outputs the following in a text field with the instance name myTxt:
One carrot. 10 large eggplants. Lots of vegetable broth.
The previous example shows how you can use the addition (+) and addition assignment (+=)
operators to concatenate strings. Notice how the third line of code uses the addition operator
to concatenate the value of the myNum variable into the text field, and the fourth line of code
uses the addition assignment operator to concatenate a string onto the existing value of the
text field.
ActionScript treats spaces at the beginning or end of a string as a literal part of the string.
For example, the following ActionScript uses the dot operator to set certain properties
within objects:
myTextField.border = true;
year.month.day = 9;
myTextField.text = "My text";
The dot operator and the array access operator are very similar. The dot operator takes an
identifier as its property, but the array access operator evaluates the contents to a name and
then accesses the value of that named property. The array access operator lets you dynamically
set and retrieve instance names and variables.
The array access operator is useful if you don’t know exactly what keys are in an object. When
this occurs, you can use a for..in loop to iterate through an object or movie clip and display
its contents.
This ActionScript toggles the visibility of each of the nested movie clips.
12. Select Control > Test Movie to test the ActionScript you just added.
Now the four nested instances are invisible. You’re using the array access operator to
iterate over each nested movie clip in the myClip instance and set its visible property
dynamically. You save time, because you don’t have to specifically target each instance.
You can also use the array access operator on the left side of an assignment, which lets you set
instance, variable, and object names dynamically:
myNum[i] = 10;
In ActionScript 2.0, you can use the bracket operator to access properties on an object that are
created dynamically, in case the class definition for that object is not given the dynamic
attribute. You can also create multidimensional arrays using this operator. For more
information on creating multidimensional arrays using array access operators, see “Creating
multidimensional arrays” on page 131.
When you trace this code, the text in the Output panel reads:
0
1
For information on using additive operators, see “Using numeric operators” on page 149.
Flash concatenates the values 5 and 2 instead of adding them. To work around this, you can
wrap the expression 5+2 in a pair of parentheses, as shown in the following code:
trace("the sum of 5 + 2 is: " + (5 + 2)); // the sum of 5 + 2 is: 7
For more information on operator precedence, see “About operator precedence and
associativity” on page 140.
For information on using relational operators, see “Using relational and equality operators”
on page 151.
For information on using equality operators, see “Using relational and equality operators”
on page 151.
When you select Control > Test Movie, the string the array is empty appears in the
Output panel.
You can use the equality operator to compare values, but you cannot use the equality operator
to set values. You might try to use the assignment operator (=) to check for equality.
In this ActionScript, you use the equality operator (==) to check for equality. You check
whether the variable myNum equals 2.
3. Select Control > Test Movie.
The string It equals 2 appears in the Output panel.
4. Return to the authoring environment and change:
var myNum:Number = 2;
to:
var myNum:Number = 4;
to
if (myNum = 2) {
First, you define numeric variables: num1, and num2. If you compare the variables using the
equality operator, Flash tries to convert the values to the same data type and then compare the
values to see whether they are equal. When you use the strict equality operator (===) Flash
doesn’t attempt to do any data type conversion before it compares the values. As a result, Flash
sees the variables as two separate values.
In the following example, you’ll use the greater than or equal to (>=) operator to compare
values and execute code based on the value a user enters into a text field.
this.createEmptyMovieClip("submit_mc", 30);
submit_mc.beginFill(0xFF0000);
submit_mc.moveTo(0, 0);
submit_mc.lineTo(100, 0);
submit_mc.lineTo(100, 20);
submit_mc.lineTo(0, 20);
submit_mc.lineTo(0, 0);
submit_mc.endFill();
submit_mc._x = 110;
submit_mc.onRelease = function(evt_obj:Object):Void {
var myNum:Number = Number(myTxt.text);
if (isNaN(myNum)) {
trace("Please enter a number");
return;
}
if (myNum >= 10) {
trace("Your number is greater than or equal to 10");
} else {
trace("Your number is less than 10");
}
};
You can also use the assignment operator to assign several variables in the same expression. In
the following statement, the value of 10 is assigned the variables numOne, numTwo, and
numThree.
var numOne:Number;
var numTwo:Number;
var numThree:Number;
numOne = numTwo = numThree = 10;
You can also use compound assignment operators to combine operations. These operators
perform the operation on both operands, and then they assign the new value to the first
operand. For example, both of these statements do the same thing:
var myNum:Number = 0;
myNum += 15;
myNum = myNum + 15;
For information on using logical operators, see “Using logical operators” on page 156.
this.createEmptyMovieClip("submit_mc", 30);
submit_mc.beginFill(0xFF0000);
submit_mc.moveTo(0, 0);
submit_mc.lineTo(100, 0);
submit_mc.lineTo(100, 20);
submit_mc.lineTo(0, 20);
submit_mc.lineTo(0, 0);
submit_mc.endFill();
submit_mc._x = 110;
submit_mc.onRelease = function():Void {
var myNum:Number = Number(myTxt.text);
if (isNaN(myNum)) {
trace("Please enter a number");
return;
}
if ((myNum > 10) && (myNum < 20)) {
trace("Your number is between 10 and 20");
} else {
trace("Your number is NOT between 10 and 20");
}
};
In this ActionScript, you create a text field at runtime. If you type a number into the text
field and click the button on the Stage, Flash uses the logical operator to display a message
in the Output panel. The message depends on the value of the number you type into the
text field.
For information on using bitwise operators, see “Using bitwise operators” on page 158. For
specific information on each bitwise operator, see its entry in the ActionScript 2.0 Language
Reference.
For information on using bitwise operators, see “Using bitwise operators” on page 158. For
specific information on each bitwise operator, see its entry in the ActionScript 2.0 Language
Reference.
Although it might not be immediately obvious, the number values for the sort options are
actually bitwise digits (binary or base 2). The constant value Array.CASEINSENSITIVE equals
the numeric value of 1, which also happens to be the binary value of 1. The constant value
Array.DECENDING has a numeric value of 2 or a binary value of 10.
Working with binary numbers can get confusing. Binary only has two possible values, 1 or 0,
which is why the value 2 is represented as 10. If you want to display the number 3 in binary, it
would be 11 (1+10). The number 4 represented in binary is 100, representing 5 in binary is
101, and so on.
The following ActionScript demonstrates how to sort an array of numeric values in
descending order by using the bitwise AND operator to add the Array.DESCENDING and
Array.NUMERIC constants together.
var scores:Array = new Array(100,40,20,202,1,198);
trace(scores); // 100,40,20,202,1,198
trace(scores.sort()); // 1,100,198,20,202,40
var flags:Number = Array.NUMERIC|Array.DESCENDING;
trace(flags); // 18 (base 10)
trace(flags.toString(2)); // 10010 (binary -- base2)
trace(scores.sort(flags)); // 202,198,100,40,20,1
For information on using the conditional operator and an example, see “About the
conditional operator and alternative syntax” on page 114.
When you call Math.round() in this example, the score rounds to the nearest integer (85)
and is displayed in the Output panel. If you multiply the number by an additional 100,
before you call Math.round(), and then divide by 100, you can make Flash round the
number to 2 decimal places. This results in a more accurate score.
4. Try changing the correctAnswers variable to 3 and select Control > Test Movie to test
the SWF file again.
If you are building a testing application, you might want to create a series of true/false or
multiple choice questions using the RadioButton and Label components. After users finish
answering each of the questions and click the submit button, you can compare their answers
to an answer key and then calculate their score.
163
If you pass values as parameters to a function, the function can perform calculations using the
supplied values. Each function has individual characteristics, and some functions require that
you pass certain types or numbers of values. If you pass more parameters than the function
requires, the function ignores the extra values. If you don’t pass a required parameter, the
function assigns the undefined data type to the empty parameters. This can cause errors
during runtime. A function can also return values (see “Returning values from functions”
on page 182).
NOT E
To call a function, that function’s definition must be in a frame that the playhead has
reached.
You can think of a well-written function as a “black box.” If the function contains carefully
placed comments about its input, output, and purpose, a person using the function does not
need to understand exactly how it works internally.
The basic syntax for a simple named function is:
function traceMe() {
trace("your message");
}
traceMe();
For information on writing named functions, see “Writing named functions” on page 168.
The basic syntax for a simple named function that builds on the previous example by passing
a parameter, yourMessage, is:
function traceMe(yourMessage:String) {
trace(yourMessage);
}
traceMe("How you doing?");
Alternatively, if you want to pass multiple parameters, you could use the following code:
var yourName:String = "Ester";
var yourAge:String = "65";
var favSoftware:String = "Flash";
function traceMe(favSoftware:String, yourName:String, yourAge:String) {
trace("I'm " + yourName + ", I like " + favSoftware + ", and I'm " +
yourAge + ".");
}
traceMe(favSoftware,yourName,yourAge);
For information on writing code using Script Assist, see Using Flash.
For more information about functions and methods, see the following topics:
■ “About types of methods and functions” on page 165
For information on writing class files, such as the following, see Chapter 6, “Classes,” on
page 187.
class Person {
public static var numPeople:Number = 0;
// instance members
private var _speed:Number;
// constructor
public function Person(speed:Number) {
Person.numPeople++;
this._speed = speed;
}
// static methods
public static function getPeople():Number {
return Person.numPeople;
// instance methods
public function walk(speed:Number):Void {
this._speed = speed;
}
public function run():Void {
this._speed *= 2;
}
public function rest():Void {
this._speed = 0;
}
For a full demonstration of how to write methods like the ones in the previous code sample,
see Chapter 6, “Classes,” on page 187. The methods that you use in your code might belong
to a class that is built into the ActionScript language. MovieClip and Math are examples of
top-level classes that you might use in an application. When you use methods from these
classes in your code, they are functions written in the built-in class (similar to the previous
code sample). Alternatively, you could use methods from a custom class that you
wrote yourself.
Functions that don’t belong to a class are called top-level functions (sometimes called predefined
or built-in functions), meaning that you can call them without a constructor. Examples of
functions that are built in to the top level of the ActionScript language are trace() and
setInterval().
To add a top-level function call to your code, just add a single line of code in the Script pane
of the Actions panel. For example, type the following:
trace("my message");
When you test the SWF file with this single line of code, the top-level trace() function is
called, and text appears in the Output panel.
Remember: when you want to assign a method to a property, you omit the parentheses after
the method name because you’re passing a reference to the function:
my_mc.myMethod = aFunction;
For more information on top-level functions, see “About built-in and top-level functions”
on page 167.
You can also define functions in numerous other ways. For more information on each kind of
function, see the following sections:
■ “About built-in and top-level functions” on page 167
■ “Writing named functions” on page 168
■ “Writing anonymous and callback functions” on page 170
■ “About function literals” on page 172
■ “Targeting and calling user-defined functions” on page 174
■ “About constructor functions” on page 173
For information on writing and using functions and methods, see the following related
sections. For information on using functions, see “Using functions in Flash” on page 176. For
information on using methods, see “Understanding methods” on page 184.
N OTE
For information on writing code using Script Assist, see Using Flash.
To call a function, that function’s definition must be in a frame that the playhead has
reached.
Top-level functions are easy to use. To call a function, simply use the function name and pass
any parameters required by that function. (For information on required parameters, see the
entry for the function in the ActionScript 2.0 Language Reference). For example, add the
following ActionScript to Frame 1 of the Timeline:
trace("my message");
When you test the SWF file, my message appears in the Output panel. Two other examples
of top-level functions are setInterval() and getTimer(). The next example shows how to
use both of these functions together. Add the following code to Frame 1 of the Timeline:
function myTimer():Void {
trace(getTimer());
}
var intervalID:Number = setInterval(myTimer, 100);
This code creates a simple timer using getTimer(), and uses the setInterval() and
trace() top-level functions to display the number of milliseconds since the SWF file began
to play in Flash Player.
Calling a top-level function is like calling a user-defined function. For more information, see
“Targeting and calling user-defined functions” on page 174. For information on each
function, see its entry in ActionScript 2.0 Language Reference.
In this code you create a named function called myMessage, which you use later in the
script to call a trace() function.
6. Select Control > Test Movie to test the SWF file.
You use the function statement to create your own function in ActionScript. Remember that
parameters are optional; however, if you don’t have parameters, you still need to include the
brackets. The content between the curly braces ({}) is called the function block.
You can write functions on the main timeline or within external ActionScript files, including
class files.
You also write constructor functions in class files using this format (however, the name of the
function matches the class). For more information on constructor functions, see “Writing the
constructor function” on page 228. Also see Chapter 6, “Classes,” on page 187 for
information on and examples of writing functions in classes.
You can see from the previous code snippet that the onLoad() event handler uses an
anonymous function to handle the onLoad() event.
For more information on callback functions, see Chapter 9, “Handling Events,” on page 291.
You could also use anonymous functions with the setInterval() function, as seen in the
following code, which uses setInterval() to call the anonymous function approximately
every 1000 milliseconds (1 second):
setInterval(function() {trace("interval");}, 1000);
You can use named functions instead of anonymous functions. Named functions are often
easier to read and understand (except in some circumstances, such as callback functions). You
can also forward-reference a named function, which means you reference it before the
function exists on a timeline.
You cannot reference an anonymous function anywhere in your code (unless you assign it to a
variable), as you can when you use a named function. For example, suppose that you have
anonymous functions on Frame 5 of your FLA file, such as the following:
//with a movie clip called my_mc that spans the timeline
stop();
var myWidth = function () {
trace(my_mc._width);
};
If you place the following code on Frame 1, it cannot reference the function:
myWidth();
Similarly, the following code placed on any frame does not work:
myWidth();
var myWidth:Function = function () {
trace(my_mc._width);
};
You could also place myWidth() on any frame that is after the frame that contains the
myWidth function.
When defining a named function, calling it in a frame script works, even though the
equivalent code with an anonymous function does not work:
// the following does work because you are calling a named function:
myWidth();
function myWidth() {
trace("foo");
}
// the following does not work because you are calling an anonymous
function:
myWidth();
var myWidth:Function = function () {
trace("foo");
};
For information on writing code using Script Assist, see Using Flash.
When you redefine a function literal, the new function definition replaces the old
definition.
If you do not explicitly declare a constructor function in your class file—that is, if you don’t
create a function whose name matches that of the class—the compiler automatically
creates an empty constructor function for you.
A class can contain only one constructor function; overloaded constructor functions are not
allowed in ActionScript 2.0. Also, a constructor function cannot have a return type. For more
information on writing constructor functions in class files, “Writing the constructor function”
on page 228.
For information on _global and scope, “About variables and scope” on page 60.
You can also define functions in numerous other ways. For more information on each kind of
function, see the following sections:
■ “About built-in and top-level functions” on page 167
■ “Writing named functions” on page 168
■ “Writing anonymous and callback functions” on page 170
■ “About function literals” on page 172
■ “About constructor functions” on page 173
■ “Targeting and calling user-defined functions” on page 174
For information on naming functions, see “Naming functions” on page 176. For a detailed
example of using functions in an external class file, see “Using functions in Flash” on page 176
and Chapter 6, “Classes,” on page 187.
NOT E
For information on writing code using Script Assist, see Using Flash.
The following example uses a relative path to call the list() function, which was defined in
the functionsClip movie clip:
this._parent.functionsClip.list(6);
For information on writing named functions, see “Writing named functions” on page 168.
For more information on parameters, see “Passing parameters to a function” on page 180.
You can also define your own named functions. For example, the following named function
helloWorld() is user defined:
function helloWorld() {
trace("Hello world!");
};
The following example shows you how to use a user-defined function in a FLA file.
The previous code creates a user-defined function named traceHello() that takes one
argument, name, and traces a greeting message. To call the user-defined function, you can
call traceHello from the same timeline as the function definition and pass a single
string value.
3. Select Control > Test Movie to test the Flash document.
For more information on named functions, see “Writing named functions” on page 168.
Classes contain many user-defined functions. For information on writing functions in class
files, see “Using functions in Flash” on page 176. Also see the following sections in Chapter 6,
“Classes”: “Using methods and properties from a class file” on page 206, “About public,
private, and static methods and properties (members)” on page 208, and “About class
members” on page 211.
By packing your code into class files or code-based components, you can easily share,
distribute, or reuse blocks of code. Users can install your component, drag it onto the
Stage, and use the code that you store in the file, such as the workflow for code-based
components available in Flash (Window > Common Libraries > Classes).
The following example shows you how to create and call a function in a FLA file.
Anonymous functions are often more difficult to read. Compare the following code to the
preceding code.
var myCircle:Function = function(radius:Number):Number {
// function block here
return (Math.PI * radius * radius);
};
trace(myCircle(5));
You can also place functions in class files when you use ActionScript 2.0, as the following
example shows:
class Circle {
public function area(radius:Number):Number {
return (Math.PI * Math.pow(radius, 2));
}
public function perimeter(radius:Number):Number {
return (2 * Math.PI * radius);
For more information on writing functions in a class file, see Chapter 6, “Classes,” on
page 187.
As you can see in the previous code sample, you don’t need to place functions on a timeline.
The following example also puts functions in a class file. This is a good practice to adopt
when you create large applications by using ActionScript 2.0, because it lets you reuse your
code easily in several applications. When you want to reuse the functions in other
applications, you can import the existing class rather than rewrite the code from scratch or
duplicate the functions in the new application.
7. Select Control > Test Movie to test the documents. The following text is displayed in the
Output panel:
month: 7
min: -3
max: 34
NOT E
For information on writing code using Script Assist, see Using Flash.
You can also use regular variables in a function. However, if you modify regular variables,
it is good practice to use script comments to document these modifications.
After passing the parameter, you can pass a value to the function when you call the function.
This value traces in the Output panel, as follows:
myFunc("This is what traces");
When you call the function, you should always pass the specified number of parameters unless
your function checks for undefined values and sets default values accordingly. The function
substitutes the passed values for the parameters in the function definition; if any parameters
are missing, Flash sets their value to undefined. You regularly pass parameters into functions
when you write ActionScript code.
You can also pass multiple parameters to a function, which can be as simple as the following:
var birthday:Date = new Date(1901, 2, 3);
trace(birthday);
The first few lines of code create a user-defined function called traceMe(), which takes a
single parameter, yourMessage. The last line of code calls the traceMe() function and
passes the string value “How are you doing?”.
3. Select Control > Test Movie to test the Flash document.
The next example demonstrates how to pass multiple parameters to a function.
The getArea() function call assigns the values 10 and 12 to the width and height,
respectively, and you save the return value in the area instance. Then you trace the values
that you save in the area instance.
4. Select Control > Test Movie to test the SWF file.
You see 120 in the Output panel.
The parameters in the getArea() function are similar to values in a local variable; they
exist while the function is called and cease to exist when the function exits.
In the next example, the ActionScript returns the value NaN (not a number) if you don’t pass
enough parameters to the addNumbers() function.
If you don’t pass enough parameters to the addNumbers function, the missing arguments
are assigned a default value of undefined. If you pass too many parameters, the excess
parameters are ignored.
3. Select Control > Test Movie to test the Flash document.
Flash displays the following values: 11, NaN, 11.
Some functions perform a series of tasks without returning a value. The next example returns
the processed value. You are capturing that value in a variable, and then you can use that
variable within your application.
The getArea() function call assigns the values 10 and 12 to the width and height,
respectively, and you save the return value in the area instance. Then you trace the values
that you save in the area instance.
4. Select Control > Test Movie to test the SWF file.
You see 120 in the Output panel.
The parameters in the getArea() function are similar to values in a local variable; they
exist while the function is called and cease to exist when the function exits.
Select Control > Test Movie to test the nested function. The formatText() and
changeString() functions are both applied to the string when you call the formatText()
function.
You use the sortOn() method of the Array class to create a new Array object named
userArr. The array is populated by three objects that contain a first name and age, and
then the array is sorted based on the value of each object’s firstname property. Finally,
you loop over each item in the array and display the first name in the Output panel and
sort the names alphabetically by first letter.
3. Select Control > Test Movie to test the SWF file.
This code displays the following in the Output panel:
Dan
George
Socks
As demonstrated in “Writing named functions” on page 168, when you write the following
code on Frame 1 of the Timeline, your ActionScript code defines a function called
eatCabbage().
function eatCabbage() {
trace("tastes bad");
}
eatCabbage();
However, if you write the eatCabbage() function within a class file and, for example, call
eatCabbage() in the FLA file, then eatCabbage() is considered to be a method.
When you use this ActionScript, you are calling the eatCabbage() method of the
EatingHabits class.
NO TE
When you use methods of any built-in class (in addition to the custom class you
wrote earlier in this procedure), you are using a method on a timeline.
Naming methods
You should use verbs to name methods, and words with mixed cases for concatenated words,
making sure that the first letter is lowercase. For example, you might name methods in the
following ways:
sing();
boogie();
singLoud();
danceFast();
Classes 6
This chapter introduces you to using and writing classes using ActionScript 2.0. Classes are
the backbone of ActionScript 2.0, and are more important than they were in earlier versions
of Flash. You will learn how important classes are in Flash throughout this chapter.
This chapter begins by explaining some fundamental terminology and how it relates to classes
and object-oriented programming (OOP). Next you walk through a sample class file and
understand how each section of the class file works and how the class is organized. The rest of
the chapter shows you how to create your own custom classes and how to use them within
your Flash documents. You learn about the Flash classpath and how a class should be
documented so that other people who read or use your code can easily understand the code
and the class’s overall purpose.
This section contains code examples that you can use to become familiar with creating classes
in ActionScript 2.0. By the end of this chapter, you should be able to write a typical class file,
understand and recognize Flash classes, and also feel comfortable reading other people’s
class files.
If you’re not familiar with ActionScript 2.0 scripting, see Chapter 4, “Syntax and Language
Fundamentals,” on page 77 and Chapter 17, “Best Practices and Coding Conventions for
ActionScript 2.0,” on page 665.
For more information on working with custom and built-in classes, see the following topics:
About object-oriented programming and Flash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
Writing custom class files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
About working with custom classes in an application . . . . . . . . . . . . . . . . . . . . . . . . 199
Example: Writing custom classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .223
Example: Using custom class files in Flash. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .236
Assigning a class to symbols in Flash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .239
Compiling and exporting classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
Understanding classes and scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .243
About top-level and built-in classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .246
About working with built-in classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .256
187
About object-oriented programming and
Flash
ActionScript 2.0 is an object-oriented language. Like ActionScript, OOP languages are based
on the concept of classes and instances. A class defines all of the properties that distinguish a
series of objects. For example, a User class represents a bunch of users who are using your
application. Then, you have an instantiation of the class, which, for the User class, is one of
the individual users—one of its members. The instantiation produces an instance of the User
class, and that instance has all of the properties of the User class.
Classes are also considered like data types or templates that you can create to define a new type
of object. For example, if you need a data type of Lettuce in your application, you might write
the Lettuce class. This defines the Lettuce object, and then you can assign your Lettuce
methods (wash()) and properties (leafy or bugs). To define a class, you use the class
keyword in an external script file. You can create an external script file in the Flash authoring
tool by selecting File > New and then selecting ActionScript File.
ActionScript 2.0 includes features such as filter effects, file upload and download, and the
External API, and also provides several powerful and familiar OOP concepts and keywords
(such as class, interface, and package) found in other programming languages, such as
Java. The programming language lets you build program structures that are reusable, scalable,
robust, and maintainable. It can also decrease development time by providing users with
thorough coding assistance and debugging information. You can use ActionScript 2.0 to
create objects and establish inheritance and to create custom classes and extend the Flash top-
level and built-in classes. You learn how to create classes and use custom classes in this chapter.
Flash includes approximately 65 top-level and built-in classes that provide everything from
basic, or “primitive,” data types (Array, Boolean, Date, and so on), to custom errors and
events, as well as several ways to load external content (XML, images, raw binary data, and
more). You can also write your own custom classes and integrate them into your Flash
documents or even extend the top-level classes and add your own functionality or modify
existing functionality. For example, “About class members” on page 211 in this chapter shows
you how to make a custom Person class that contains custom properties for the person’s name
and age. You can then treat this custom class as a new data type in your documents and create
a new instance of the class using the new operator.
For more information on working with OOP, see the following topics:
■ “The benefits of using classes” on page 189
■ “About packages” on page 189
188 Classes
■ “About values and data types” on page 193
■ “Object-oriented programming fundamentals” on page 193
About packages
When you are creating classes, you organize your ActionScript class files in packages. A
package is a directory that contains one or more class files and that resides in a designated
classpath directory (see “About importing class files” on page 201 and “About setting and
modifying the classpath” on page 202). A package can, in turn, contain other packages, called
subpackages, each with its own class files.
// In Circle.as:
class Circle {}
// In Triangle.as:
class Triangle {}
Because these three class files are related, you might decide to put them in a package
(directory) called Shapes. In this case, the fully qualified class name would contain the
package path, as well as the simple class name. Package paths are denoted with dot (.) syntax,
where each dot indicates a subdirectory.
For example, if you placed each ActionScript file that defines a shape in the Shapes directory,
you would need to change the name of each class file to reflect the new location, as follows:
// In Shapes/Square.as:
class Shapes.Square {}
// In Shapes/Circle.as:
class Shapes.Circle {}
// In Shapes/Triangle.as:
class Shapes.Triangle {}
To reference a class that resides in a package directory, you can either specify its fully qualified
class name or import the package by using the import statement. For more information, see
“Working with packages” on page 191.
190 Classes
A comparison of classes and packages
In OOP, a class defines a category of object. Classes are essentially data types that you can
create if you want to define a new type of object in your application. A class describes the
properties (data) and behaviors (methods) for an object, much like an architectural blueprint
describes the characteristics of a building. The properties (variables defined within a class) and
methods of a class are collectively called the class’s members. To use the properties and
methods defined by a class, you generally first create an instance of that class (except for
classes that have all static members (see “About class (static) members” on page 258, such as
the top-level Math class, and “Static methods and properties” on page 210). The relationship
between an instance and its class is similar to the relationship between a house and its
blueprints.
Packages in Flash are directories that contain one or more class files and reside in a designated
file path. You might place related custom class files within a single directory. For example, you
might have three related classes called SteelWidget, PlasticWidget, and WoodWidget that are
defined in SteelWidget.as, PlasticWidget.as, and WoodWidget.as. You would organize these
classes in the Widget package. For more information on packages, see “Working with
packages” on page 191 and “Creating and packaging your class files” on page 226.
To use the import statement, you must specify ActionScript 2.0 and Flash Player 6 or
later in the Flash tab of your FLA file’s Publish Settings dialog box.
The import statement lets you access classes without specifying their fully qualified names.
For example, if you want to use the BlurFilter class in a script, you must refer to it by its fully
qualified name (flash.filters.BlurFilter) or import it; if you import it, you can refer to it by its
class name (BlurFilter). The following ActionScript code demonstrates the differences
between using the import statement and using fully qualified class names.
If you don’t import the BlurFilter class, your code needs to use the fully qualified class name
(package name followed by class name) in order to use the filter:
// without importing
var myBlur:flash.filters.BlurFilter = new flash.filters.BlurFilter(10, 10,
3);
If you were importing several classes within a package (such as the BlurFilter,
DropShadowFilter, and GlowFilter) you could use one of two methods of importing each
class. The first method of importing multiple classes is to import each class using a separate
import statement, as seen in the following snippet:
import flash.filters.BlurFilter;
import flash.filters.DropShadowFilter;
import flash.filters.GlowFilter;
Using individual import statements for each class within a package can quickly become very
time consuming and prone to typing mistakes. The second method of importing classes
within a package is to use a wildcard import that imports all classes within a certain level of a
package. The following ActionScript shows an example of using a wildcard import:
import flash.filters.*; // imports each class within flash.filters package
The import statement applies only to the current script (frame or object) in which it’s called.
For example, suppose on Frame 1 of a Flash document you import all the classes in the
macr.util package. On that frame, you can reference classes in that package by their class
names instead of their fully qualified names. If you wanted to use the class name on another
frame script, however, you would need to reference classes in that package by their fully
qualified names or add an import statement to the other frame that imports the classes in
that package.
When using import statements, it’s also important to note that classes are imported only for
the level specified. For example, if you imported all classes in the mx.transitions package, only
those classes within the /transitions/ directory are imported, not all classes within
subdirectories (such as the classes in the mx.transitions.easing package).
TI P
If you import a class but don't use it in your script, the class isn't exported as part of the
SWF file. This means you can import large packages without being concerned about the
size of the SWF file; the bytecode associated with a class is included in a SWF file only if
that class is actually used.
192 Classes
About values and data types
Data, values, and types are important when you start writing classes and using them. You
learned about data and types in Chapter 3, “Data and Data Types,” on page 35. When you
work with classes, remember that data types describe the kind of information a variable or
ActionScript element can contain, such as Boolean, Number, and String. For more
information, see “About data types” on page 36.
Expressions have values, while values and properties have types. The values that you can set
and get to and from a property in your class must be compatible with that property. Type
compatibility means the type of a value is compatible with the type that is in use, such as the
following example:
var myNum:Number = 10;
For more information on strict data typing, see “About assigning data types and strict data
typing” on page 45.
Objects
Think of a real-world object, such as a cat. A cat could be said to have properties (or states),
such as name, age, and color; a cat also has behaviors such as sleeping, eating, and purring. In
the world of OOP, objects also have properties and behaviors. Using object-oriented
techniques, you can model a real-world object (such as a cat) or a more abstract object (such as
a chemical process).
N OTE
The word behaviors is used generically here and does not refer to the Behaviors panel in
the Flash authoring environment.
For more information on objects, see “Object data type” on page 42.
Inheritance
One of the primary benefits of OOP is that you can create subclasses of (or extend) a class; the
subclass then inherits all the properties and methods of the class. The subclass typically
defines additional methods and properties or overrides methods or properties defined in the
superclass. Subclasses can also override (provide their own definitions for) methods defined in
a superclass.
One of the major benefits of using a superclass/subclass structure is that it is easier to reuse
similar code between various classes. For example, you could build a superclass called Animal,
which contains common characteristics and behaviors of all animals. Next you could build
several subclasses that inherit from the Animal superclass and add characteristics and
behaviors specific to that type of animal.
You might create a Cat class that inherits from another class. For example, you might create a
Mammal class that defines certain properties and behaviors common to all mammals. You
could then create a Cat subclass that extends the Mammal class. Another subclass, say, the
Siamese class, could extend (subclass) the Cat class, and so on.
Writing subclasses lets you reuse code. Instead of recreating all the code common to both
classes, you can simply extend an existing class.
TI P
194 Classes
Interfaces
Interfaces in OOP can be described as templates of class definitions, and classes that
implement interfaces are required to implement that template of methods. Using the cat
analogy, an interface is similar to a blueprint of a cat: the blueprint tells you which parts you
need, but not necessarily how those parts are assembled, or how the parts work.
You can use interfaces to add structure and ease of maintenance to your applications. Because
ActionScript 2.0 supports extending only from a single superclass, you can use interfaces as a
form of limited multiple inheritance.
You can also think of an interface as a “programming contract” that you can use to enforce
relationships between otherwise unrelated classes. For example, suppose you are working with
a team of programmers, each of whom is working on a different part (class) of the same
application. While designing the application, you agree on a set of methods that the different
classes use to communicate. So you create an interface that declares these methods, their
parameters, and their return types. Any class that implements this interface must provide
definitions for those methods; otherwise, a compiler error results.
For more information on inheritance, see Chapter 7, “Inheritance,” on page 263. For more
information on interfaces, see Chapter 8, “Interfaces,” on page 275.
Encapsulation
In elegant object-oriented design, objects are seen as “black boxes” that contain, or
encapsulate, functionality. A programmer should be able to interact with an object by knowing
only its properties, methods, and events (its programming interface), without knowing the
details of its implementation. This approach enables programmers to think at higher levels of
abstraction and provides an organizing framework for building complex systems.
Encapsulation is why ActionScript 2.0 includes, for example, member access control, so
details of the implementation can be made private and invisible to code outside an object.
The code outside the object is forced to interact with the object’s programming interface
rather than with the implementation details (which can be hidden in private methods and
properties). This approach provides some important benefits; for example, it lets the creator
of the object change the object’s implementation without requiring any changes to code
outside of the object—that is, as long as the programming interface doesn’t change.
For more information on encapsulation, see “About using encapsulation” on page 221.
196 Classes
■ Add instance variables. Write the public member variables first, and follow them with
private member variables.
■ Add the constructor statement, such as the one in the following example:
public function UserClass(username:String, password:String) {...}
■ Write your methods. Group methods by their functionality, not by their accessibility or
scope. Organizing methods this way helps improve the readability and clarity of
your code.
■ Write the getter/setter methods into the class file.
The following example looks at a simple ActionScript class named User.
This code defines a custom User class that allows you to create new
users and specify user login information.
*/
class User {
// private instance variables
private var __username:String;
private var __password:String;
// constructor statement
public function User(p_username:String, p_password:String) {
this.__username = p_username;
this.__password = p_password;
}
Because the User class you created previously is very basic, the ActionScript in the Flash
document is also very straightforward. The first line of code imports the custom User class
into your Flash document. Importing the User class lets you use the class as a custom data
type.
198 Classes
A single instance of the User class is defined and assigned to a variable named user1. You
assign the user1 User object a value and define a username of un1 and a password of
pw1. The following two trace statements display the current value of user1.username
and user1.password using the User class’s getter functions, which both return strings.
The next two lines use the User class’s setter functions to set new values for the username
and password variables. Finally, you trace the values for username and password to the
Output panel. The trace statements display the modified values that you set using the
setter functions.
8. Save the FLA file, and then select Control > Test Movie to test the files.
You see the results of the trace statements in the Output panel. In the next examples, you
use these files in an application.
For samples that demonstrates how to create a dynamic menu with XML data and a custom
class file, see the Flash Samples page at www.adobe.com/go/learn_fl_samples. The sample
calls the ActionScript XmlMenu() constructor and passes it two parameters: the path to the
XML menu file and a reference to the current timeline. Download and decompress the
Samples zip file and navigate to the ActionScript2.0/XML_Menu folder to access these
samples:
■ XmlMenu.as
■ xmlmenu.fla
200 Classes
About importing class files
In order to use a class or interface that you’ve defined, Flash must locate the external
ActionScript files that contain the class or interface definition so that it can import the file.
The list of directories in which Flash searches for class, interface, function, and variable
definitions is called the classpath. Flash has two classpath settings—a global classpath and a
document-level classpath:
■ Global classpath is a classpath that’s shared by all Flash documents. You set it in the
Preferences dialog box (Edit > Preferences (Windows) or Flash > Preferences (Macintosh),
click ActionScript in the Category list, and then click ActionScript 2.0 Settings).
■ Document-level classpath is a classpath that you specifically define for a single Flash
document. It is set in the Publish Settings dialog box (File > Publish Settings, select the
Flash tab, and then click the Settings button).
When you import class files, the following rules apply:
■ The import statements can exist in the following locations:
■ Anywhere before the class definition in class files
■ Anywhere in frame or object scripts
■ Anywhere in ActionScript files that you include in an application (using the #include
statement).
■ You import individual, packaged definitions using this syntax:
import flash.display.BitmapData;
You can also include ActionScript code in a Flash document (FLA) file using an include
statement. The following rules apply to the include statement:
■ include statements are essentially a copy and paste of the content inside the included
ActionScript file.
■ include statements inside ActionScript class files are relative to the subdirectory that
contains the file.
For more information on the include statement, see #include directive in the ActionScript 2.0
Language Reference. For more information on classpaths, see “About setting and modifying the
classpath” on page 202.
When you click the Check Syntax button above the Script pane while editing an
ActionScript file, the compiler looks only in the global classpath. ActionScript files aren't
associated with FLA files in Edit mode and don't have their own classpath.
202 Classes
Using a global classpath
The global classpath is a classpath that’s shared by all of your Flash documents.
You can modify the global classpath using the Preferences dialog box. To modify the
document-level classpath setting, you use the Publish Settings dialog box for the FLA file. In
both cases, you can add absolute directory paths (for example, C:/my_classes) and relative
directory paths (for example, ../my_classes or “.”). The order of directories in the dialog
box reflects the order in which they are searched.
By default, the global classpath contains one absolute path and one relative path. The absolute
path is denoted by $(LocalData)/Classes in the Preferences dialog box. The location of the
absolute path is shown here:
■ Windows: Hard Disk\Documents and Settings\user\Local Settings\Application
Data\Adobe\Adobe Flash CS3\language\Configuration\Classes.
NOT E
In Windows, the Application Data folder is hidden by default. To show hidden folders
and files, select My Computer to open Windows Explorer, select Tools>Folder
Options and then select the View tab. Under the View tab, select the Show hidden
files and folders radio button.
Do not delete the absolute global classpath. Flash uses this classpath to access
built-in classes. If you accidentally delete this classpath, reinstate it by adding
$(LocalData)/Classes as a new classpath.
The relative path portion of the global classpath is denoted by a single dot (.) and points to
the current document directory. Be aware that relative classpaths can point to different
directories, depending on the location of the document being compiled or published.
You can use the following steps to add a global classpath or edit an existing classpath.
Do not delete the absolute global classpath. Flash uses this classpath to access
built-in classes. If you accidentally delete this classpath, you can reinstate it by
adding $(LocalData)/Classes as a new classpath.
For information on importing packages, see “Working with packages” on page 191.
204 Classes
4. You can either manually type a file path or you can click the Browse to Path button to
browse to the directory you want to add to the classpath.
NOT E
To edit an existing classpath directory, select the path in the Classpath list, click the
Browse to Path button, browse to the directory you want to add, and click OK.
N OTE
To delete a directory from the classpath, select the path in the Classpath list, and
click the Remove Selected Path (-) button.
In some cases, you don’t need to create an instance of a class to use its properties and
methods. For more information on class (static) members, see “About class (static)
members” on page 258 and “Static methods and properties” on page 210.
Use the dot (.) operator to access the value of a property in an instance. Type the name of the
instance on the left side of the dot, and the name of the property on the right side. For
example, in the following statement, firstUser is the instance and username is the property:
firstUser.username
For more information on using custom classes in Flash, see “Example: Using custom class files
in Flash” on page 236. For information on the constructor function, see “Writing the
constructor function” on page 228.
Next you could invoke that method in your document. To invoke an instance method or
access an instance property, you reference an instance of the class. In the following example,
picture01, an instance of the custom Picture class (available in the following exercise),
invokes the showInfo() method:
var img1:Picture = new Picture("http://www.helpexamples.com/flash/images/
image1.jpg");
// Invoke the showInfo() method.
img1.showInfo();
The next example demonstrates how you can write a custom Picture class to hold various
pieces of information about a photo.
206 Classes
To use the Picture and PictureClass classes in a FLA file:
1. Select File > New and then select ActionScript File. Save the document as Picture.as and
then click OK.
You write your custom Picture class in this document.
2. Type the following ActionScript code into the Script window:
/**
Picture class
author: John Doe
version: 0.53
modified: 6/24/2005
copyright: Adobe Systems Incorporated
The Picture class is used as a container for an image and its URL.
*/
class Picture {
private var __infoObj:Object;
For samples that demonstrates how to create a dynamic menu with XML data and a custom
class file, see the Flash Samples page at www.adobe.com/go/learn_fl_samples. The sample
calls the ActionScript XmlMenu() constructor and passes it two parameters: the path to the
XML menu file and a reference to the current timeline. Download and decompress the
Samples zip file and navigate to the ActionScript2.0/XML_Menu folder to access these
samples:
■ XmlMenu.as
■ xmlmenu.fla
208 Classes
Public methods and properties
The public keyword specifies that a variable or function is available to any caller. Because
variables and functions are public by default, the this keyword is used primarily for stylistic
and readability benefits, indicating that the variable exists in the current scope. For example,
you might want to use the this keyword for consistency in a block of code that also contains
private or static variables. The this keyword can be used with either the public or
private keyword.
The following Sample class already has a public method named myMethod():
class Sample {
private var ID:Number;
public function myMethod():Void {
this.ID = 15;
trace(this.ID); // 15
trace("myMethod");
}
}
If you want to add a public property, you use the word “public” instead of “private,” as you
can see in the following sample code:
class Sample {
private var ID:Number;
public var email:String;
public function myMethod():Void {
trace("myMethod");
}
}
Because the email property is public, you can change it within the Sample class, or directly
within a FLA.
If you attempt to access the private ID property from outside the Sample class, you get a
compiler error and a message in the Output panel. The message indicates that the member is
private and cannot be accessed.
If you type this single line of code in the script pane of the Actions panel, you see a result trace
in the Output panel.
For example, in the previous Sample class example, you could create a static variable to keep
track of how many instances of the class have been created, as demonstrated in the
following code:
class Sample {
public static var count:Number = 0;
private var ID:Number;
public var email:String;
public function Sample() {
Sample.count++;
trace("count updated: " + Sample.count);
}
public function myMethod():Void {
trace("myMethod");
}
}
Every time you create a new instance of the Sample class, the constructor method traces the
total number of Sample class instances that have been defined so far.
Some of the top-level ActionScript classes have class members (or static members), as you saw
earlier in this section when you called the Math.PI property. Class members (properties and
methods) are accessed or invoked on the class name, not on an instance of the class.
Therefore, you don’t create an instance of the class to use those properties and methods.
210 Classes
For example, the top-level Math class consists only of static methods and properties. To call
any of its methods, you don’t create an instance of the Math class. Instead, you simply call the
methods on the Math class itself. The following code calls the sqrt() method of the
Math class:
var squareRoot:Number = Math.sqrt(4);
trace(squareRoot); // 2
The following code invokes the max() method of the Math class, which determines the larger
of two numbers:
var largerNumber:Number = Math.max(10, 20);
trace(largerNumber); // 20
For more information on creating class members, see “About class members” on page 211 and
“Using class members” on page 214.
For samples that demonstrates how to create a dynamic menu with XML data and a custom
class file, see the Flash Samples page at www.adobe.com/go/learn_fl_samples. The sample
calls the ActionScript XmlMenu() constructor and passes it two parameters: the path to the
XML menu file and a reference to the current timeline. Download and decompress the
Samples zip file and navigate to the ActionScript2.0/XML_Menu folder to access these
samples:
■ XmlMenu.as
■ xmlmenu.fla
In the previous code snippet the Person class’s getInfo() method, as well as the age and
username properties, are all public instance members. The age property would not be a good
class member, because each person has a different age. Only properties and methods that are
shared by all individuals of the class should be class members.
Suppose that you want every class to have a species variable that indicates the proper Latin
name for the species that the class represents. For every Person object, the species is Homo
sapiens. It would be wasteful to store a unique copy of the string "Homo sapiens" for every
instance of the class, so this member should be a class member.
Class members are declared with the static keyword. For example, you could declare the
species class member with the following code:
class Person {
public static var species:String = "Homo sapiens";
// ...
}
You can also declare methods of a class to be static, as shown in the following code:
public static function getSpecies():String {
return Person.species;
}
Static methods can access only static properties, not instance properties. For example, the
following code results in a compiler error because the class method getAge() references the
instance variable age:
class Person {
public var age:Number = 15;
// ...
public static function getAge():Number {
return age; /* **Error**: Instance variables cannot be accessed in
static functions. */
}
}
To solve this problem, you could either make the method an instance method or make the
variable a class variable.
212 Classes
For more information on class members (also called static properties), see “Static methods and
properties” on page 210.
For samples that demonstrates how to create a dynamic menu with XML data and a custom
class file, see the Flash Samples page at www.adobe.com/go/learn_fl_samples. The sample
calls the ActionScript XmlMenu() constructor and passes it two parameters: the path to the
XML menu file and a reference to the current timeline. Download and decompress the
Samples zip file and navigate to the ActionScript2.0/XML_Menu folder to access these
samples:
■ XmlMenu.as
■ xmlmenu.fla
214 Classes
In the following example, you’ll create a class called Widget that defines a single, static
instance counter named widgetCount. Each time a new instance of the class is created, the
value of widgetCount increments by 1 and the current value of widgetCount is displayed in
the Output panel.
The widgetCount variable is declared as static, so it initializes to 0 only once. Each time
the Widget class’s constructor statement is called, it adds 1 to widgetCount and then
shows the number of the current instance that’s being created.
3. Save your file as Widget.as.
4. Select File > New and then select Flash Document to create a new FLA, and save it as
widget_test.fla in the same directory as Widget.as.
5. In widget_test.fla, type the following code into Frame 1 of the Timeline:
// Before you create any instances of the class,
// Widget.widgetCount is zero (0).
trace("Widget count at start: " + Widget.widgetCount); // 0
var widget1:Widget = new Widget(); // 1
var widget2:Widget = new Widget(); // 2
var widget3:Widget = new Widget(); // 3
trace("Widget count at end: " + Widget.widgetCount); // 3
Instead of allowing instances of the class to directly access this property (user.userName =
"Buster", for example), the class might have two methods, getUserName() and
setUserName(), that would be implemented as shown in the next example.
216 Classes
To use getter and setter methods:
1. Select File > New and then select ActionScript File, and then click OK.
2. Type the following code into the Script window:
class Login {
private var __username:String;
public function Login(username:String) {
this.__username = username;
}
public function getUserName():String {
return this.__username;
}
public function setUserName(value:String):Void {
this.__username = value;
}
}
However, if you want to use a more concise syntax, you can use implicit getter and setter
methods. Implicit getter and setter methods let you access class properties in a direct manner,
while maintaining good OOP practice.
Implicit getter and setter methods are syntactic shorthand for the Object.addProperty()
method found in ActionScript 1.0.
218 Classes
Unlike ordinary methods, you invoke getter and setter methods without any parentheses
or arguments. You invoke getter and setter methods as you would a property by the
same name.
6. Save the Flash document and select Control > Test Movie to test the file.
Flash displays the following information in the Output panel:
RickyM
EnriqueI
NOT E
You cannot use getter and setter method attributes in interface method declarations.
If, in another script, you create an instance of the Person class and try to access a property
of the class that doesn’t exist, the compiler generates an error.
3. Save the file on your hard disk as Person.as.
This ActionScript adds the dynamic keyword to the Person class in the previous example.
Instances of the Person2 class can add and access properties and methods that are not
defined in this class.
4. Save your changes to the ActionScript file.
5. Select File > New and then select Flash Document to create a new FLA file, and then
click OK.
6. Select File > Save As and name the new file person2_test.fla. Save it in the same directory
as Person2.as.
220 Classes
7. Type the following code to create a new instance of the Person2 class (firstPerson), and
assign a value to a property called hairColor (which doesn’t exist in the Person2 class).
var firstPerson:Person2 = new Person2();
firstPerson.hairColor = "blue";
trace(firstPerson.hairColor); // blue
222 Classes
You can also use a class name prefix for static variables and methods, even within a class. This
helps qualify the references you make, which makes code readable. Depending on the coding
environment you use, adding prefixes might also trigger code hints.
N OTE
You do not have to add these prefixes, and some developers feel it is unnecessary.
Adobe recommends adding the this keyword as a prefix, because it can aid readability
and helps you write clean code by providing context for your methods and variables.
ActionScript code in external files is compiled into a SWF file when you publish, export,
test, or debug a FLA file. Therefore, if you make any changes to an external file, you must
save the file and recompile any FLA files that use it.
As discussed in “Writing custom class files” on page 196, a class consists of two main parts:
the declaration and the body. The class declaration consists minimally of the class statement,
followed by an identifier for the class name, and then left and right curly braces ({}).
Everything inside the braces is the class body, as shown in the following example:
class className {
// class body
}
Remember: you can define classes only in external ActionScript files. For example, you can’t
define a class in a frame script in a FLA file. Therefore, you create a new file for this example.
In its most basic form, a class declaration consists of the class keyword, followed by the class
name (Person, in this case), and then left and right curly braces ({}). Everything between the
braces is called the class body and is where the class’s properties and methods are defined.
By the end of this example, the basic ordering of your class files is as follows:
■ Documentation comments
■ Class declaration
■ Constructor function
■ Class body
You do not write subclasses in this chapter. For more information on inheritance and
subclassing, see Chapter 7, “Inheritance,” on page 263.
■ Initialize local variables when you declare them, unless that initial value is determined by a
calculation. For information on initializing variables, see “Adding methods and
properties” on page 230.
■ Declare variables before you first use them (including loops). For example, the following
code predeclares the loop iterator variable (i) before using it in the for loop:
var my_array:Array = new Array("one", "two", "three");
var i:Number;
for (i = 0 ; i < my_array.length; i++) {
trace(i + " = " + my_array[i]);
}
224 Classes
■ Avoid using local declarations that hide higher-level declarations. For example, do not
declare a variable twice, as the following example shows:
// bad code
var counter:Number = 0;
function myMethod() {
var counter:Number;
for (counter = 0; counter <= 4; counter++) {
// statements;
}
}
or
// bad form
class User {
private var m_username:String, m_password:String;
}
■ Have a good reason for making public instance variables, or public static, class, or member
variables. Make sure that these variables are explicitly public before you create them
this way.
■ Set most member variables to private unless there is a good reason to make them public. It
is much better from a design standpoint to make member variables private and allow
access only to those variables through a small group of getter and setter functions.
The name of a class (ClassA) must exactly match the name of the AS file that contains it
(ClassA.as). This is very important; if these two names don’t match exactly, including
capitalization, the class won’t compile.
226 Classes
5. Type the following code into the Script window:
class com.adobe.utils.ClassA {
}
The preceding code creates a new class named ClassA in the com.adobe.utils package.
6. Save the ClassA.as ActionScript document.
7. Select File > New and then select ActionScript File, and then click OK.
8. Select File > Save As, name the new file ClassB.as, and save it in the same directory as
ClassA.as created in an earlier step.
9. Type the following code into the Script window:
class com.adobe.utils.ClassB {
}
The previous code creates a new class named ClassB in the com.adobe.utils package.
10. Save your changes to both the ClassA.as and ClassB.as class files.
The class files you use in a FLA file import into a SWF file when you compile it. The code
you write in a class file should have a certain methodology and ordering, which are discussed
in the following sections.
If you are creating multiple custom classes, use packages to organize your class files. A package
is a directory that contains one or more class files and resides in a designated classpath
directory. A class name must be fully qualified within the file in which it is declared—that is,
it must reflect the directory (package) in which it is stored. For more information on
classpaths, see “About setting and modifying the classpath” on page 202.
For example, a class named com.adobe.docs.YourClass is stored in the com/adobe/docs
directory. The class declaration in the YourClass.as file looks like this:
class com.adobe.docs.YourClass {
// your class
}
N OTE
You write the class declaration that reflects the package directory in the following
section, “Example: Writing custom classes” on page 223.
For this reason, it’s good practice to plan your package structure before you begin creating
classes. Otherwise, if you decide to move class files after you create them, you will have to
modify the class declaration statements to reflect their new location.
You learn how to write the comments, statements, and declarations in later sections.
Constructors are functions that you use to initialize (define) the properties and methods of a
class. By definition, constructors are functions within a class definition that have the same
name as the class. For example, the following code defines a Person class and implements a
constructor function. In OOP, the constructor function initializes each new instance of
a class.
A class’s constructor is a special function that is called automatically when you create an
instance of a class using the new operator. The constructor function has the same name as the
class that contains it. For example, the Person class you created contained the following
constructor function:
// Person class constructor function
public function Person (uname:String, age:Number) {
this.__name = uname;
this.__age = age;
}
228 Classes
Consider the following points when you write constructor functions:
■ If no constructor function is explicitly declared—that is, if you don’t create a function
whose name matches that of the class—the compiler automatically creates an empty
constructor function for you.
■ A class can contain only one constructor function; overloaded constructor functions are
not allowed in ActionScript 2.0.
■ A constructor function should have no return type.
The term constructor is also typically used when you create (instantiate) an object based on a
particular class. The following statements are calls to the constructor functions for the top-
level Array class and the custom Person class:
var day_array:Array = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri",
"Sat");
var somePerson:Person = new Person("Tom", 30);
The following exercise is part of “Example: Writing custom classes” on page 223. If you
do not wish to progress through the example, you can download the class files from
www.helpexamples.com/flash/learnas/classes/.
The previous code defines a constructor method for the ClassA class. This constructor
traces a simple string to the Output panel, which will let you know when a new instance
of the class has been created.
3. Open the ClassB.as class file in the Flash authoring tool.
4. Modify the class file so it matches the following code (the changes to make appear
in boldface):
class com.adobe.utils.ClassB {
function ClassB() {
trace("ClassB constructor");
}
}
The following three exercises are part of “Example: Writing custom classes”
on page 223. If you do not wish to progress through the example, you can download the
class files from www.helpexamples.com/flash/learnas/classes/.
The previous block of code adds a single new static variable, _className, which contains
the name of the current class.
3. Modify the ClassB class and add the static variable so it is similar to the previous code.
4. Save both ActionScript files before you proceed.
TIP
By convention, class properties are defined at the top of the class body. Defining
them at the top makes the code easier to understand, but isn’t required.
You use the post-colon syntax (for example, var username:String and var age:Number) in
the variable declarations. This is an example of strict data typing. When you type a variable
using the var variableName:variableType format, the ActionScript compiler ensures that
any values assigned to that variable match the specified type. If the correct data type is not
used in the FLA file importing this class, the compiler throws an error. For more information
on strict data typing, see “About assigning data types and strict data typing” on page 45.
230 Classes
A class’s members consist of properties (variable declarations) and methods (function
definitions). You must declare and define all properties and methods inside the class body (the
curly braces [{}]); otherwise, an error occurs during compilation. For information on
members, see “About public, private, and static methods and properties (members)”
on page 208.
function ClassA() {
trace("ClassA constructor");
}
function doSomething():Void {
trace("ClassA - doSomething()");
}
}
The block of code in boldface creates a new method in the class, which traces a string to
the Output panel.
3. In ClassA.as, select Tools > Check Syntax to check the syntax of your ActionScript file.
If any errors are reported in the Output panel, compare the ActionScript in your script to
the complete code written in the previous step. If you cannot fix the code errors, copy and
paste the complete code into the Script window before you proceed.
4. Check the syntax of ClassB.as as you did in ClassA.as.
If any errors appear in the Output panel, copy and paste the complete code into the Script
window before you proceed:
class com.adobe.utils.ClassB {
static var _className:String;
function ClassB() {
trace("ClassB constructor");
}
function doSomething():Void {
trace("ClassB - doSomething()");
}
}
When you initialize properties inline, the expression on the right side of an assignment must
be a compile-time constant. That is, the expression cannot refer to anything that is set or
defined at runtime. Compile-time constants include string literals, numbers, Boolean values,
null, and undefined, as well as constructor functions for the following top-level classes: Array,
Boolean, Number, Object, and String.
function ClassA() {
trace("ClassA constructor");
}
function doSomething():Void {
trace("ClassA - doSomething()");
}
}
The only difference between the existing class file and the previous block of code is there is
now a value defined for the static _className variable, “ClassA”.
3. Modify the ClassB class file and add the inline property, changing the value to “ClassB”.
4. Save both ActionScript files before you proceed.
This rule applies only to instance variables (variables that are copied into each instance of a
class), not class variables (variables that belong to the class).
NO TE
When you initialize arrays inline, only one array is created for all instances of the class.
To continue writing your class file, see “Controlling member access in your classes”
on page 233.
232 Classes
Controlling member access in your classes
By default, any property or method of a class can be accessed by any other class: all members
of a class are public by default. However, in some cases you might want to protect data or
methods of a class from access by other classes. You need to make those members private
(available only to the class that declares or defines them).
You specify public or private members using the public or private member attribute. For
example, the following code declares a private variable (a property) and a private method (a
function). The following class (LoginClass) defines a private property named userName and a
private method named getUserName():
class LoginClass {
private var userName:String;
private function getUserName():String {
return this.userName;
}
// Constructor:
public function LoginClass(user:String) {
this.userName = user;
}
}
Private members (properties and methods) are accessible only to the class that defines those
members and to subclasses of that original class. Instances of the original class, or instances of
subclasses of that class, cannot access privately declared properties and methods; that is,
private members are accessible only within class definitions, not at the instance level. In the
following example, you change member access in your class files.
NOT E
This exercise is part of “Example: Writing custom classes” on page 223. If you do not
wish to progress through the example, you can download the class files from
www.helpexamples.com/flash/learnas/classes/.
This previous code sets both methods (the ClassA constructor and the doSomething()
method) as public, meaning that they can be accessed by external scripts. The static
_className variable is set as private, meaning the variable can be accessed only from
within the class and not from external scripts.
3. Modify the ClassB.as ActionScript file and add the same method and property access as the
ClassA class.
4. Save both ActionScript files before you proceed.
An instance of ClassA or ClassB cannot access the private members. For example, the
following code, added to Frame 1 of the Timeline in a FLA file, would result in a compiler
error indicating that the method is private and can’t be accessed:
import com.adobe.utils.ClassA;
var a:ClassA = new ClassA();
trace(a._className); // Error. The member is private and cannot be accessed.
Member access control is a compile-time-only feature; at runtime, Flash Player does not
distinguish between private or public members.
To continue writing your class file, see “Documenting the classes” on page 234.
234 Classes
Use documentation comments to describe interfaces, classes, methods, and constructors.
Include one documentation comment per class, interface, or member, and place it directly
before the declaration.
If you have to document additional information that does not fit into the documentation
comments, use implementation comments (in the format of block comments or single-line
comments, as described in “About comments” on page 95). Implementation comments, if
you add them, directly follow the declaration.
NOT E
Do not include comments that do not directly relate to the class being read. For example,
do not include comments that describe the corresponding package.
NO TE
The following exercise is part of “Example: Writing custom classes” on page 223. If you
do not wish to progress through the example, you can download the class files from
www.helpexamples.com/flash/learnas/classes/.
The code above added a comment to the top of the class file. It’s always a good idea to add
comments to your ActionScript and Flash files so that you can add useful information
such as the author of the class, date last modified, copyright information, or any potential
issues/bugs that may be present in the file.
3. Add a similar comment to the top of the ClassB.as ActionScript file, changing the class
name and any other information as you see fit.
4. Save both ActionScript files before you proceed.
236 Classes
To specify package paths, use dot (.) notation to separate package directory names. Package
paths are hierarchical; that is, each dot represents a nested directory. For example, suppose you
create a class named ClassName that resides in a com/adobe/docs/learnAs2 package in your
classpath. To create an instance of that class, you could specify the fully qualified class name.
You can also use the fully qualified class name to type your variables, as shown in the
following example:
var myInstance:com.adobe.docs.learnAs2.ClassName = new
com.adobe.docs.learnAs2.ClassName();
You can use the import statement to import packages into a script, which lets you use a class’s
abbreviated name rather than its fully qualified name. You can also use the wildcard character
(*) to import all the classes in a package. If you use the wildcard character, you don’t need to
use the fully qualified class name each time you use the class.
For example, suppose that in a script you imported the above class using the import
statement, as shown in the following example:
import com.adobe.docs.learnAs2.util.UserClass;
Later, in the same script, you could reference that class by its abbreviated name, as shown in
the following example:
var myUser:UserClass = new UserClass();
You can use the wildcard character (*) to import all the classes in a given package. Suppose
you have a package named com.adobe.utils that contains two ActionScript class files,
ClassA.as and ClassB.as. In another script, you could import both classes in that package
using the wildcard character, as shown in the following code:
import com.adobe.utils.*;
The following example shows that you can then reference either of the classes directly in the
same script:
var myA:ClassA = new ClassA();
var myB:ClassB = new ClassB();
The import statement applies only to the current script (frame or object) in which it’s called.
If an imported class is not used in a script, the class is not included in the resulting SWF file’s
bytecode, and the class isn’t available to any SWF files that the FLA file containing the import
statement might load.
NO TE
The following exercise is part of “Example: Using custom class files in Flash”
on page 236 which continues the examples “Example: Writing custom classes”. If you
need ClassA and ClassB, you can download the class files from
www.helpexamples.com/flash/learnas/classes/.
The previous block of code begins by importing each of the classes within the
com.adobe.utils package by using the wildcard (*) character. Next, you create a new
instance of the ClassA class, which causes the constructor method to trace a message to the
Output panel. An instance of the ClassB class is also created, which sends debugging
messages to the Output panel.
3. Save your changes to the Flash document before you proceed.
To continue using these class files in a Flash file, see “Creating instances of classes in an
example” on page 238.
The following exercise is part of “Example: Using custom class files in Flash”
on page 236 which continues the examples “Example: Writing custom classes”.
238 Classes
To create a new instance of the ClassA and ClassB classes:
1. Open the file called package_test.fla.
2. Type the following boldface code into the Script window:
import com.adobe.utils.*;
var a:ClassA = new ClassA(); // ClassA constructor
a.doSomething(); // call the ClassA's doSomething() method
var b:ClassB = new ClassB(); // ClassB constructor
b.doSomething(); // call the ClassB's doSomething() method
Data typing your objects in this code example enables the compiler to ensure that you
don’t try to access properties or methods that aren’t defined in your custom class. For more
information on strict data typing, see “About assigning data types and strict data typing”
on page 45. The exception to data typing your objects is if you declare the class to be
dynamic using the dynamic keyword. See “Creating dynamic classes” on page 219.
3. Save your changes to the FLA file before you proceed.
You should now have a basic understanding of how to create and use classes in your Flash
documents. Remember that you can also create instances of top-level ActionScript or built-in
classes (see “About working with built-in classes” on page 256).
To continue using these class files in a Flash file, see “Assigning a class to symbols in Flash”
on page 239.
This ActionScript creates a new class called Animal that has a constructor method that
traces a string to the Output panel.
4. Save your changes to the ActionScript file.
If you need to modify the Movie Clip’s Linkage properties, you can right-click the
symbol in the document’s library and select Properties or Linkage from the context
menu.
240 Classes
2. Rename the default layer to content, drag a ProgressBar component from the Components
panel to the Stage, and give it an instance name of my_pb.
3. Create a new layer, drag it above the content layer, and rename it actions.
4. Add the following ActionScript code to Frame 1 of the actions layer on the main Timeline:
my_pb.indeterminate = true;
5. Create a new keyframe on Frame 2 of the actions layer and add the following ActionScript
code:
var classesFrame:Number = 10;
if (_framesloaded < classesFrame) {
trace(this.getBytesLoaded() + " of " + this.getBytesTotal() + " bytes
loaded");
gotoAndPlay(1);
} else {
gotoAndStop(classesFrame);
}
6. Create a new keyframe on Frame 10 of the actions layer and add the following
ActionScript:
stop();
7. Create a new keyframe on Frame 10 of the content layer and drag several components onto
the Stage.
8. Right-click each component (except the ProgressBar) in the Library panel and select
Linkage from the context menu to launch the Linkage Properties dialog box.
9. In the Linkage Properties dialog box, make sure that Export for ActionScript is selected,
deselect the Export in First Frame check box, and click OK.
10. Select File > Publish Settings.
11. In the Publish Settings dialog box, select the Flash tab.
12. Click the Settings button next to the ActionScript version pop-up menu to open the
ActionScript Settings dialog box.
13. In the Export Frame for Classes text box, enter the number of the frame where you want
to export your class code (Frame 10).
If the frame specified does not exist in the timeline, you get an error message when you
publish your SWF file.
14. Click OK to close the ActionScript Settings dialog box, and then click OK to close the
Publish Settings dialog box.
242 Classes
To delete ASO files:
If you are editing a FLA file, and you want to delete an ASO file, select one of the following in
the authoring environment:
■ Select Control > Delete ASO Files to delete ASO files and continue editing.
■ Select Control > Delete ASO Files and Test Movie to delete ASO files and test
the application.
If you are editing an ActionScript document in the Script window:
■ Select Control > Delete ASO Files to delete ASO files and continue editing.
■ Select Control > Delete ASO Files and Test Project to delete ASO files and then test
the application.
There is a limit to how much code you can place in a single class: the bytecode for a class
definition in an exported SWF file cannot be larger than 32,767 bytes. If the bytecode is
larger than that limit, a warning message appears.
You can’t predict the size of the bytecode representation of a given class, but classes up to
1,500 lines usually don’t go over the limit.
If your class goes over the limit, move some of the code into another class. In general, it is
good OOP practice to keep classes relatively short.
Because you are trying to reference the private member variable within an onLoad handler,
the this keyword actually refers to the prodXml instance and not the Product class, which
you might expect. For this reason, you must create a pointer to the local class file so that
you can directly reference the class from the onLoad handler. You can now use this class
with a Flash document.
244 Classes
3. Save the previous ActionScript code as Product.as.
4. Create a new Flash document named testProduct.fla in the same directory.
5. Select Frame 1 of the main Timeline.
6. Type the following ActionScript into the Actions panel:
var myProduct:Product = new Product("http://www.helpexamples.com/
crossdomain.xml");
7. Select Control > Test Movie to test this code in the test environment.
The contents of the specified XML document appear in the Output panel.
Another type of scope you encounter when working with these classes is static variables and
static functions. The static keyword specifies that a variable or function is created only once
per class rather than being created in every instance of that class. You can access a static class
member without creating an instance of the class by using the syntax
someClassName.username. For more information on static variables and functions, see
“About public, private, and static methods and properties (members)” on page 208 and
“Using class members” on page 214.
Another benefit of static variables is that static variables don’t lose their values after the
variable’s scope has ended. The following example demonstrates how you can use the static
keyword to create a counter that tracks how many instances of the class Flash has created.
Because the numInstances variable is static, the variable is created only once for the entire
class, not for every single instance.
The previous code defines a User class that tracks the number of times the constructor has
been called. A private, static variable (User.numInstances) is incremented within the
constructor method.
3. Save the document as User.as.
The first line of code calls the static instances() getter method, which returns the value
of the private static numInstances variable. The rest of the code creates new instances of
the User class and displays the current value returned by the instances() getter method.
6. Select Control > Test Movie to test the documents.
For information on using the this keyword in classes, see “About using the this keyword in
classes” on page 222.
246 Classes
You can find the ActionScript classes installed on your hard disk. You can find the classes
folders here:
■ Windows: Hard Disk\Documents and Settings\user\Local Settings\Application
Data\Adobe\Flash CS3\language\Configuration\Classes.
N OTE
In Windows, the Application Data folder is hidden by default. To show hidden folders and
files, select My Computer to open Windows Explorer, select Tools>Folder Options and
then select the View tab. Under the View tab, select the Show hidden files and folders
radio button.
248 Classes
Top-level classes
The top level contains the ActionScript classes and global functions, many of which provide
core functionality for your applications. Core classes, borrowed directly from ECMAScript,
include Array, Boolean, Date, Error, Function, Math, Number, Object, String, and System.
To find more information on each class, see the following table.
NOT E
The CustomActions and XMLUI classes are available only in the Flash authoring
environment.
Class Description
Accessibility The Accessibility class manages communication between SWF files
and screen reader applications. You use the methods of this class with
the global _accProps property to control accessible properties for movie
clips, buttons, and text fields at runtime. See Accessibility.
Array The Array class represents arrays in ActionScript and all array objects
are instances of this class. The Array class contains methods and
properties for working with array objects. See Array.
Boolean The Boolean class is a wrapper for Boolean (true or false) values. See
Boolean.>.
Button The Button class provides methods, properties, and event handlers for
working with buttons. See Button. Note that the built-in Button class is
different from the Button component class, associated with the version
2 component, Button.
Camera The Camera class provides access to the user’s camera, if one is
installed. When used with Flash Media Server, your SWF file can
capture, broadcast, and record images and video from a user’s camera.
See Camera.
Color The Color class lets you set the RGB color value and color transform of
movie clip instances and retrieve those values after you set them. The
Color class is deprecated in Flash Player 8 in favor of the
ColorTransform class. For information on color transforms, see
ColorTransform (flash.geom.ColorTransform).
ContextMenuItem The ContextMenuItem class lets you create new menu items that
appear in the Flash Player context menu. You add new menu items that
you create with this class to the Flash Player context menu by using the
ContextMenu class. See ContextMenuItem.
CustomActions The CustomActions class lets you manage any custom actions that are
registered with the authoring tool. See CustomActions.
Date The Date class shows how dates and times are represented in
ActionScript, and it supports operations for manipulating dates and
times. The Date class also provides the means for obtaining the current
date and time from the operating system. See Date.
Error The Error class contains information about runtime errors that occur in
your scripts. You typically use the throw statement to generate an error
condition, which you can handle using a try..catch..finally
statement. See Error.
Key The Key class provides methods and properties for getting information
about the keyboard and key presses. See Key.
LoadVars The LoadVars class lets you transfer variables between a SWF file and
a server in name-value pairs. See LoadVars.
LocalConnection The LocalConnection class lets you develop SWF files that send
instructions to each other without using the fscommand() method or
JavaScript. See LocalConnection.
Microphone The Microphone class provides access to the user’s microphone, if one
is installed. When used with Flash Media Server, your SWF file can
broadcast and record audio from a user’s microphone. See
Microphone.
250 Classes
Class Description
Mouse The Mouse class provides control over the mouse in a SWF file; for
example, this class lets you hide or show the mouse pointer. See
Mouse.
MovieClip Every movie clip in a SWF file is an instance of the MovieClip class.
You use the methods and properties of this class to control movie clip
objects. See MovieClip.
MovieClipLoader This class lets you implement listener callbacks that provide status
information while SWF, JPEG, GIF, and PNG files load into movie clip
instances. See MovieClipLoader.
NetStream The NetStream class controls playback of FLV files from a local file
system or HTTP address. See NetStream.
Number The Number class is a wrapper for the primitive number data type. See
Number.
Object The Object class is at the root of the ActionScript class hierarchy; all
other classes inherit its methods and properties. See Object.
PrintJob The PrintJob class lets you print content from a SWF file, including
content that is rendered dynamically, and multipage documents. See
PrintJob.
Selection The Selection class lets you set and control the text field in which the
insertion point is located (the text field that has focus). See Selection.
SharedObject The SharedObject class offers persistent local data storage on the
client computer, similar to cookies. This class offers real-time data
sharing between objects on the client’s computer. See SharedObject.
Sound The Sound class provides control over sounds in a SWF file. See
Sound.
Stage The Stage class provides information about a SWF file’s dimensions,
alignment, and scale mode. It also reports Stage resize events. See
Stage.
String The String class is a wrapper for the string primitive data type, which
lets you use the methods and properties of the String object to
manipulate primitive string value types. See String.
TextField The TextField class provides control over dynamic and input text fields,
such as retrieving formatting information, invoking event handlers, and
changing properties such as alpha or background color. See TextField.
TextFormat The TextFormat class lets you apply formatting styles to characters or
paragraphs in a TextField object. See TextFormat.
TextSnapshot The TextSnapshot object lets you access and lay out static text inside a
movie clip. See TextSnapshot.
Video The Video class lets you show video objects in a SWF file. You can use
this class with Flash Media Server to display live streaming video in a
SWF file, or within Flash to display a Flash Video (FLV) file. See Video.
XML This class contains methods and properties for working with XML
objects. See XML.
XMLSocket The XMLSocket class lets you create a persistent socket connection
between a server computer and client running Flash Player. Client
sockets enable low-latency data transfer, such as that which is required
for real-time chat applications. See XMLSocket.
XMLUI The XMLUI object enables communication with SWF files that are
used as a custom user interface for the Flash authoring tool’s
extensibility features (such as Behaviors, Commands, Effects, and
Tools). See XMLUI.
Class Description
BitmapData The BitmapData class lets you create arbitrarily sized transparent or
opaque bitmap images in the document and manipulate them in various
ways at runtime. See BitmapData (flash.display.BitmapData).
252 Classes
The flash.external package
The flash.external package lets you communicate with the Flash Player container using
ActionScript code. For example, if you embed a SWF file in an HTML page, that HTML
page is the container. You would be able to communicate with the HTML page using the
ExternalInterface class and JavaScript. Also called the External API.
Class Description
ExternalInterface The ExternalInterface class is the External API, a subsystem that
enables communications between ActionScript and the Flash Player
container (such as an HTML page using JavaScript) or a desktop
application that uses Flash Player. See ExternalInterface
(flash.external.ExternalInterface).
Class Description
BevelFilter The BevelFilter class lets you add a bevel effect to a movie clip
instance. See BevelFilter (flash.filters.BevelFilter).
BitmapFilter The BitmapFilter class is a base class for all filter effects. See
BitmapFilter (flash.filters.BitmapFilter).
BlurFilter The BlurFilter class lets you apply a blur effect to movie clip
instances. See BlurFilter (flash.filters.BlurFilter).
DisplacementMapFilter The DisplacementMapFilter class lets you use the pixel values
from a specified image (the displacement map image) to spatially
displace the original instance (a movie clip) that you apply the filter
to. See DisplacementMapFilter
(flash.filters.DisplacementMapFilter).
GlowFilter The GlowFilter class lets you add a glow effect to a movie clip. See
GlowFilter (flash.filters.GlowFilter).
GradientBevelFilter The GradientBevelFilter class lets you apply a gradient bevel effect
to a movie clip. See GradientBevelFilter
(flash.filters.GradientBevelFilter).
GradientGlowFilter The GradientGlowFilter class lets you apply a gradient glow effect
to a movie clip. See GradientGlowFilter
(flash.filters.GradientGlowFilter).
Class Description
ColorTransform The ColorTransform class lets you mathematically set the RGB color
value and color transform of an instance. You can retrieve these values
after they have been set. See ColorTransform
(flash.geom.ColorTransform).
Rectangle The Rectangle class is used to create and modify Rectangle objects.
See Rectangle (flash.geom.Rectangle).
254 Classes
The flash.net package
The flash.net package contains classes that let you upload and download one or more files
between a user’s computer and the server. For more information on each class, see the cross
references provided in the following table.
Class Description
FileReference The FileReference class lets you upload and download one or more
files between a user’s computer and a server. See FileReference
(flash.net.FileReference).
FileReferenceList The FileReferenceList class lets you upload one or more files from a
user’s computer to a server. See FileReferenceList
(flash.net.FileReferenceList).
Class Description
TextRenderer This class provides functionality for the advanced anti-aliasing
capability in Flash Player 8. See TextRenderer
(flash.text.TextRenderer).
Class Description
Locale This class lets you control how multilanguage text displays in a SWF
file. See Locale (mx.lang.Locale).
Class Description
capabilities The capabilities class determines the abilities of the system and Flash
Player that’s hosting the SWF file. This lets you customize content for
different formats. See capabilities (System.capabilities).
IME The IME class lets you directly manipulate the operating system’s input
method editor (IME) that’s within the Flash Player application running
on a client computer. See IME (System.IME).
security The security class contains methods that specify how SWF files in
different domains can communicate with each other. See security
(System.security).
The TextField package contains the StyleSheet class that you can use to apply CSS styles
to text.
Class Description
StyleSheet The StyleSheet class lets you create a style sheet object that contains
text formatting rules such as font size, color, and other formatting
styles. See StyleSheet (TextField.StyleSheet).
256 Classes
For more information on using classes that are built into Flash, see the following topics:
■ “About creating a new instance of a built-in class” on page 257
■ “Accessing built-in object properties” on page 257
■ “About calling built-in object methods” on page 258
■ “About class (static) members” on page 258
■ “Preloading class files” on page 260
■ “Excluding classes” on page 259
In some cases, you don’t need to create an instance of a class to use its properties and methods.
For more information, see “About class (static) members” on page 258.
The following code creates a new Array object and then shows its length property:
var my_array:Array = new Array("apples", "oranges", "bananas");
trace(my_array.length); // 3
You can also use the array access operator ([]) to access the properties of an object, such as
using the array access operator for debugging purposes. The following example loops over an
object to display each of its properties.
The previous code defines a new Object named results and defines values for firstName,
lastName, age, avg, b, and t. A for..in loop traces each property in the results object
and traces their value to the Output panel.
3. Select Control > Test movie to test the Flash document.
For more information on operators, including dot and array access operators, see “About
operators” on page 137. For more information on methods and properties, see Chapter 5,
“Functions and Methods,” on page 163. For examples of working with properties of the built-
in MovieClip class, see Chapter 10, “Working with Movie Clips,” on page 313 For examples
of working with the properties of the TextField, String, TextRenderer, and TextFormat classes,
see Chapter 11, “Working with Text and Strings,” on page 343.
For examples of working with methods of the built-in MovieClip class, see Chapter 10,
“Working with Movie Clips,” on page 313. For examples of working with methods of the
built-in TextField, String, TextRenderer, and TextFormat classes, see Chapter 11, “Working
with Text and Strings,” on page 343.
For more information on static methods of the Math class, and examples of using them, see
Math in the ActionScript 2.0 Language Reference.
258 Classes
Excluding classes
To reduce the size of a SWF file, you might want to exclude classes from compilation but still
be able to access and use them for type checking. For example, you might want to do this if
you are developing an application that uses multiple SWF files or shared libraries, especially
those that access many of the same classes. Excluding classes helps you avoid duplicating
classes in those files.
For more information on excluding classes, see the following topics:
■ “Preloading class files” on page 260
The values you specify for the name attributes in the <asset> tags are the names of classes
you want to exclude from the SWF file. Add as many as you require for your application.
For example, the following XML file excludes the mx.core.UIObject and mx.screens.Slide
classes from the SWF file:
<excludeAssets>
<asset name="mx.core.UIObject" />
<asset name="mx.screens.Slide" />
</excludeAssets>
For information on preloading classes, see “Preloading class files” on page 260.
To select a different frame for the classes to load into a SWF file:
1. Select File > Publish Settings.
2. Select the Flash tab, and click the Settings button.
3. In the Export Frame for Classes text box, type the number of a new frame to determine
when to load the classes.
4. Click OK.
You cannot use any classes until the playhead reaches the frame you choose to load them into.
For example, version 2 components require classes for their functionality, so you must load
components after the Export frame for ActionScript 2.0 classes. If you export for Frame 3,
you cannot use anything from those classes until the playhead reaches Frame 3 and loads
the data.
260 Classes
If you want to preload a file that uses classes, such as version 2 component classes, you must
preload the components in the SWF file. To accomplish this, you must set your components
to export for a different frame in the SWF file. By default, the UI components export in
Frame 1 of the SWF file, so make sure that you deselect Export in First Frame from the
component’s Linkage dialog box.
NOT E
If you add a component to the Stage using ActionScript, then you need to drag an
instance of the component you want to add onto the pasteboard (the area around the
Stage). This tells Flash that you’re using the component in your application, and that its
not an unused library item. Remember, Flash does not add unused library items to SWF
files.
If components do not load on the first frame, you can create a custom progress bar for the first
frame of the SWF file. Do not reference any components in your ActionScript or include any
components on the Stage until you load the classes for the frame you specified in the Export
Frame for Classes text box.
C A UTI ON
You must export components after the ActionScript classes that they use.
Inheritance 7
In Chapter 6, “Classes,” you learned how to write class files and how classes help you organize
code into external files. The chapter also demonstrated how you can organize class files into
related packages. This chapter aims to show you how to write more advanced classes that
extend the functionality of an existing class. This is a useful subject, because you might find
yourself extending your own custom classes or existing classes so that you can add new
methods and properties.
For more information on inheritance, see “About inheritance” on page 263. For more
information on methods and properties, see Chapter 5, “Functions and Methods,” on
page 163.
For more information on inheritance, see the following topics:
About inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .263
About writing subclasses in Flash. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .265
Using polymorphism in an application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271
About inheritance
In Chapter 6, “Classes,” you saw how you could create a class file to create your own custom
data types. Learning how to create custom class files shows you how to move code off the
timeline and into external files. Moving code into external files makes it easier to edit your
code. Now that you’re familiar with the basics of creating your own custom classes, you learn
about an object-oriented programming (OOP) technique called subclassing or extending a
class, which lets you create new classes based on an existing class.
One of the benefits of OOP is that you can create subclasses of a class. The subclass inherits all
the properties and methods of a superclass. For example, if you extend (or subclass) the
MovieClip class, you are creating a custom class that extends the MovieClip class. Your
subclass inherits all of the properties and methods of the MovieClip class. Or you might create
a set of classes that extends from a custom superclass. For example, the Lettuce class might
extend from the Vegetable superclass.
263
Your subclass typically defines additional methods and properties that you can use in your
application, hence it extends the superclass. Subclasses can also override (provide their own
definitions for) methods inherited from a superclass. If a subclass overrides a method inherited
from its superclass, you can no longer access the superclass’s definition within the subclass.
The only exception to the above rule is that, if you are within the subclass’s constructor
function, you call the superclass’s constructor using the super statement. For more
information on overriding, see “Overriding methods and properties” on page 268.
For example, you might create a Mammal class that defines certain properties and behaviors
that are common to all mammals. You could then create a Cat subclass that extends the
Mammal class. Using subclasses lets you reuse code so that instead of re-creating all the code
common to both classes you could simply extend an existing class. Another subclass, the
Siamese class, could extend the Cat class, and so on. In a complex application, determining
how to structure the hierarchy of your classes is a large part of the design process.
Inheritance and subclassing are very useful in larger applications, because they let you create a
series of related classes that can share functionality. For example, you could create an
Employee class that defines the basic methods and properties of a typical employee within a
company. You could then create a new class called Contractor that extends the Employee class
and inherits all of its methods and properties. The Contractor class could add its own specific
methods and properties, or it could override methods and properties that are defined in the
Employee superclass. You could then create a new class called Manager, which also extends the
Employee class and defines additional methods and properties such as hire(), fire(),
raise(), and promote(). You could even extend a subclass, such as Manager, and create a
new class called Director, which again adds new methods or overrides existing methods.
Each time that you extend an existing class, the new class inherits all the current methods and
properties of the subclass. If each class wasn’t related, you’d have to rewrite each method and
property in each separate class file, even if the functionality was the same in the fellow classes.
You would have to spend a lot more time not only coding, but also debugging your
application and maintaining a project if similar logic changed in multiple files.
In ActionScript, you use the extends keyword to establish inheritance between a class and its
superclass, or to extend an interface. For more information on using the extends keyword,
see “About writing subclasses in Flash” on page 265 and “About writing a subclass”
on page 265. For additional information on the extends keyword, see extends statement in
the ActionScript 2.0 Language Reference.
264 Inheritance
About writing subclasses in Flash
In object-oriented programming, a subclass can inherit the properties and methods of another
class, called the superclass. You can extend your own custom classes as well as many of the core
and Flash Player ActionScript classes. You cannot extend the TextField class.
To create this kind of relationship between two classes, you use the class statement’s extends
clause. To specify a superclass, you use the following syntax:
class SubClass extends SuperClass {}
The class you specify in SubClass inherits all the properties and methods defined
in SuperClass.
For example, you might create a Mammal class that defines properties and methods common
to all mammals. To create a variation of the Mammal class, such as a Marsupial class, you
would extend the Mammal class—that is, create a subclass of the Mammal class, as follows:
class Marsupial extends Mammal {}
The subclass inherits all the properties and methods of the superclass, including any
properties or methods that you have declared to be private using the private keyword.
For more information on extending classes, see the following topics:
■ “About writing a subclass” on page 265
■ “Overriding methods and properties” on page 268
For more information on private members, see “About public, private, and static methods and
properties (members)” on page 208. For an example that creates a subclass, see “Example:
Extending the Widget class” on page 266.
// allowed
class B extends A {}
class C extends B {}
You can also use interfaces to implement a limited form of multiple inheritance. For more
information on interfaces, see Chapter 8, “Interfaces,” on page 275. For an example that
creates a subclass, see “Example: Extending the Widget class” on page 266. For additional
information on super, see super statement in the ActionScript 2.0 Language Reference.
266 Inheritance
5. In SubWidget.as, type the following code into the Script window:
class SubWidget extends Widget {
public function SubWidget() {
trace("Creating subwidget #" + Widget.widgetCount);
}
}
The previous code creates two instances of the SubWidget class: sw1 and sw2. Each call to
the SubWidget constructor traces the current value of the static Widget.widgetCount
property. Because the SubWidget class is a subclass of the Widget class, you can access the
widgetCount property through the SubWidget class, and the compiler rewrites the
reference (in the bytecode, not in your ActionScript file) as Widget.widgetCount. If you
try to access the static widgetCount property off of instances of the Widget or SubWidget
class, like sw1 or sw2, the compiler throws an error.
9. Save your changes to the document.
10. Select Control > Test Movie to test the Flash document.
The Output panel displays the following output:
Creating subwidget #1
Creating subwidget #2
Widget.widgetCount = 2
SubWidget.widgetCount = 2
You see this output because even though the Widget class’s constructor is never explicitly
called, the SubWidget class’s constructor calls it for you. This causes the Widget class’s
constructor to increment the Widget class’s static widgetCount variable.
The ActionScript 2.0 compiler can resolve static member references within
class definitions.
If you try to access the static widgetCount variable from the Widget class using the
sw1 or sw2 instances, Flash generates an error telling you that static members can
be accessed only directly through classes.
For optimal readability of your code, Adobe recommends that you always use explicit
references to static member variables in your code, as shown in the previous example. Using
explicit references means that you can easily identify where the definition of a static
member resides.
class Widget {
public static var widgetCount:Number = 0;
public function Widget() {
Widget.widgetCount++;
}
public function doSomething():Void {
trace("Widget::doSomething()");
}
}
268 Inheritance
3. Save your changes to the ActionScript document.
The Widget class now defines a constructor and a public method called doSomething().
4. Create a new ActionScript file named SubWidget.as and save it in the same directory
as Widget.as.
N OTE
If you created the SubWidget class in “Example: Extending the Widget class”
on page 266, you can use this file instead.
5. In SubWidget.as, type the following ActionScript code into the Script window:
class SubWidget extends Widget {
public function SubWidget() {
trace("Creating subwidget # " + Widget.widgetCount);
doSomething();
}
}
This output shows that the SubWidget class’s constructor calls the constructor of its
superclass (Widget), which increments the static widgetCount property. The SubWidget’s
constructor traces the superclass’s static property and calls the doSomething() method,
which inherits from the superclass.
12. Save your changes to the class file, and then open subwidgetTest.fla again.
13. Select Control > Test Movie to test the file. You see the following output in the
Output panel:
Creating subwidget # 1
SubWidget::doSomething()
Creating subwidget # 2
SubWidget::doSomething()
The previous output shows that the doSomething() method in the SubWidget class’s
constructor is calling the doSomething() method in the current class instead of
the superclass.
Open the SubWidget class again, and modify the SubWidget class’s constructor to call the
superclass’s doSomething() method (add the code that’s in boldface):
public function SubWidget() {
trace("Creating subwidget # " + Widget.widgetCount);
super.doSomething();
}
As demonstrated, you can add the super keyword to call the superclass’s doSomething()
method instead of the doSomething() method in the current class. For additional
information on super, see the super entry in the ActionScript 2.0 Language Reference.
14. Save the SubWidget class file with the modified constructor and select Control > Test
Movie to republish the Flash document.
The Output panel displays the contents of the Widget class’s doSomething() method.
270 Inheritance
Using polymorphism in an application
Object-oriented programming lets you express differences between individual classes using a
technique called polymorphism, by which classes can override methods of their superclasses
and define specialized implementations of those methods.
For example, you might start with a class called Mammal that has play() and sleep()
methods. You then create Cat, Monkey, and Dog subclasses to extend the Mammal class. The
subclasses override the play() method from the Mammal class to reflect the habits of those
particular kinds of animals. Monkey implements the play() method to swing from trees; Cat
implements the play() method to pounce at a ball of yarn; Dog implements the play()
method to fetch a ball. Because the sleep() functionality is similar among the animals, you
would use the superclass implementation. The following procedure demonstrates this
example in Flash.
// constructor
public function Mammal(gender:String) {
this._gender = gender;
}
The previous class defines two private variables, _gender and _name, which are used to
store the animal’s gender and mammal type. Next, the Mammal constructor is defined. The
constructor takes a single parameter, gender, which it uses to set the private _gender
variable defined earlier. Three additional public methods are also specified: toString(),
play(), and sleep(), each of which returns string objects. The final three methods are
getter and setter methods for the mammal’s _gender and _name properties.
3. Save the ActionScript document.
This class serves as the superclass for the Cat, Dog, and Monkey classes, which you create
shortly. You can use the toString() method of the Mammal class to display a string
representation of any Mammal instance (or any instance that extended the
Mammal class).
4. Create a new ActionScript file and save it as Cat.as in the same directory as the Mammal.as
class file you created in step 1.
5. In Cat.as, type the following ActionScript code into the Script window:
class Cat extends Mammal {
// constructor
public function Cat(gender:String) {
super(gender);
speciesName = "Cat";
}
Notice that you are overriding the play() method in the Mammal superclass. The Cat
class defines only two methods, a constructor and a play() method. Since the Cat class
extends the Mammal class, the Mammal classes’s methods and properties are inherited by
the Cat class. For more information on overriding, see “Overriding methods and
properties” on page 268.
6. Save your changes to the ActionScript document.
7. Create a new ActionScript document and save it as Dog.as in the same directory as the two
previous class files.
272 Inheritance
8. In Dog.as, type the following ActionScript code into the Script window:
class Dog extends Mammal {
// constructor
public function Dog(gender:String) {
super(gender);
speciesName = "Dog";
}
Notice that the Dog class is very similar in structure to the Cat class, except that a few of
the values have changed. Again, the Dog class extends the Mammal class and inherits all
its methods and properties. The Dog constructor takes a single property, gender, which it
passes to the Dog class’s parent class, Mammal. The speciesName variable is also
overridden and set to the string Dog. The play() method is also overridden from the
parent class.
9. Save your changes to the ActionScript document.
10. Create another ActionScript document in the same directory as your other files, and save
it as Monkey.as.
11. In Monkey.as, type the following ActionScript code into the Script window:
class Monkey extends Mammal {
// constructor
public function Monkey(gender:String) {
super(gender);
speciesName = "Monkey";
}
Similar to the previous two classes, Cat and Dog, the Monkey class extends the Mammal
class. The Monkey class’s constructor calls the constructor for the Mammal class, passing
the gender to the Mammal’s constructor, as well as setting speciesName to the string
Monkey. The Monkey class also overrides the behavior of the play() method.
12. Save your changes to the ActionScript document.
13. Now that you’ve created three subclasses of the Mammal class, create a new Flash
document called mammalTest.fla.
createMammals()
createReport()
function createMammals():Void {
mammals_arr.push(new Dog("Female"));
mammals_arr.push(new Cat("Male"));
mammals_arr.push(new Monkey("Female"));
mammals_arr.push(new Mammal("Male"));
}
function createReport():Void {
var i:Number;
var len:Number = mammals_arr.length;
// Display Mammal info in 4 columns of HTML text using tab stops.
info_txt.htmlText = "<textformat tabstops='[110, 200, 300]'>";
info_txt.htmlText += "<b>Mammal\tGender\tSleep\tPlay</b>";
for (i = 0; i < len; i++) {
info_txt.htmlText += "<p>" + mammals_arr[i].speciesName
+ "\t" + mammals_arr[i].gender
+ "\t" + mammals_arr[i].sleep()
+ "\t" + mammals_arr[i].play() + "</p>";
// The trace statement calls the Mammal.toString() method.
trace(mammals_arr[i]);
}
info_txt.htmlText += "</textformat>";
}
The mammalTest.fla code is a bit more complex than the previous classes. First it imports
the three animal classes.
15. Save the Flash document, and then select Control > Test Movie to test the document.
You see the Mammal information displayed in a text field on the Stage, and the following
text in the Output panel:
[object Dog]
[object Cat]
[object Monkey]
[object Mammal]
274 Inheritance
CHAPTER 8
Interfaces 8
In object-oriented programming (OOP), an interface is a document that lets you declare (but
not define) the methods that must appear within a class. When you work in teams of
developers, or build larger applications in Flash, interfaces can be very beneficial during
development. Interfaces allow developers to easily identify the base methods in ActionScript
classes. These methods must be implemented when developers use each interface.
This chapter walks you through a few sample interfaces, and by the end of the chapter you are
able to build your own interface files. If you are not familiar with building classes, make sure
that you read Chapter 6, “Classes,” before you try the tutorials and examples in this chapter.
For more information on working with interfaces, see the following topics:
About interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
Creating interfaces as data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
Understanding inheritance and interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .282
Example: Using interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .283
Example: Creating a complex interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .285
About interfaces
In object-oriented programming, interfaces are like classes whose methods are not
implemented (defined)—that is, they otherwise don’t “do” anything. Therefore, an interface
consists of “empty” methods. Another class can then implement the methods declared by the
interface. In ActionScript, the distinction between interface and object is only for compile-
time error checking and language rule enforcement.
275
An interface is not a class; however, this is not altogether true in ActionScript at runtime
because an interface is abstract. ActionScript interfaces do exist at runtime to allow type
casting (changing an existing data type to a different type). The ActionScript 2.0 object model
does not support multiple inheritance. Therefore, a class can inherit from a single parent class.
This parent class can be either a core or Flash Player class or a user-defined (custom) class. You
can use interfaces to implement a limited form of multiple inheritance, by which a class
inherits from more than one class.
For example, in C++, the Cat class could extend the Mammal class as well as a Playful class,
which has methods chaseTail() and eatCatNip(). Like Java, ActionScript 2.0 does not
allow a class to extend multiple classes directly but does allow a class to extend a single class
and implement multiple interfaces. So you could create a Playful interface that declares the
chaseTail() and eatCatNip() methods. A Cat class, or any other class, could then
implement this interface and provide definitions for those methods.
You can also think of an interface as a “programming contract” that you can use to enforce
relationships between otherwise unrelated classes. For example, suppose you are working with
a team of programmers, each of whom is working on a different class within the same
application. While designing the application, you agree on a set of methods that the different
classes use to communicate. You create an interface that declares these methods, their
parameters, and their return types. Any class that implements this interface must provide
definitions for those methods; otherwise, a compiler error results. The interface is like a
communication protocol to which all the classes must adhere.
One way to do this would be to create a class that defines all these methods and then have
each class extend, or inherit from, this superclass. But because the application consists of
classes that are unrelated, it doesn’t make sense to put them all into a common class hierarchy.
A better solution is to create an interface that declares the methods these classes use to
communicate, and then have each class implement (provide its own definitions for) those
methods.
You can usually program successfully without using interfaces. When used appropriately,
however, interfaces can make the design of your applications more elegant, scalable, and
maintainable.
ActionScript interfaces exist at runtime to allow type casting; see Chapter 3, “About casting
objects,” on page 75. An interface is not an object or a class, but the workflow is similar to
working with classes. For more information on the class workflow, see “Writing custom class
files” on page 196. For a tutorial on creating an application with interfaces, see “Example:
Using interfaces” on page 283.
276 Interfaces
For more information on using interfaces, see the following sections:
■ “About the interface keyword” on page 277
■ “About naming interfaces” on page 277
■ “Defining and implementing interfaces” on page 278
Some developers start interface names with an uppercase “I” to distinguish them from
classes. This is a good practice to adopt because it lets you quickly distinguish between
interfaces and regular classes.
For more information on naming conventions, see Chapter 17, “Best Practices and Coding
Conventions for ActionScript 2.0,” on page 665.
278 Interfaces
4. Create a new ActionScript file and save it as MyClass.as in the same directory as the
IMyInterface.as.
5. In the MyClass class file, type the following ActionScript code into the Script window:
class MyClass {
}
In order to instruct the custom class (MyClass) to use your interface (IMyInterface), you
need to use the implements keyword, which specifies that a class must define all the
methods declared in the interface (or interfaces) that you implement.
6. Modify the ActionScript code in MyClass.as (add the boldface code) so it matches the
following snippet:
class MyClass implements IMyInterface {
}
For a tutorial demonstrating how to create a complex interface, see “Example: Using
interfaces” on page 283.
The rules for naming interfaces and storing them in packages are the same as those for classes;
see “About naming class files” on page 225.
280 Interfaces
5. In Box.as, type the following ActionScript code into the Script window:
class Box implements IMovable {
public var xPos:Number;
public var yPos:Number;
This ActionScript code creates an instance of the Box class, which you declare as a variable
of the Box type.
9. Save your changes to the Flash document, and then select Control > Test Movie to test the
SWF file.
In Flash Player 7 and later, you can cast an expression to an interface type or other data
type at runtime. Unlike Java interfaces, ActionScript interfaces exist at runtime, which
allows type casting. If the expression is an object that implements the interface or has a
superclass that implements the interface, the object is returned. Otherwise, null is
returned. This is useful if you want to ensure that a particular object implements a certain
interface. For more information on type casting, see Chapter 3, “About casting objects,”
on page 75.
10. Add the following code at the end of the ActionScript code in boxTest.fla:
if (IMovable(newBox) != null) {
newBox.moveUp();
} else {
trace("box instance is not movable");
}
To extend an interface:
1. Create a new ActionScript file, and then save it as Ia.as.
2. In Ia.as, type the following ActionScript code into the Script window:
interface Ia {
public function f1():Void;
public function f2():Void;
}
282 Interfaces
8. In ClassA.as, type the following ActionScript code into the Script window:
class ClassA implements Ib {
// f1() and f2() are defined in interface Ia.
public function f1():Void {
}
public function f2():Void {
}
// f8() and f9() are defined in interface Ib, which extends Ia.
public function f8():Void {
}
public function f9():Void {
}
}
9. Save your class file and click the Check Syntax button above the Script window.
Flash doesn’t generate any error messages as long as all four methods are defined and
match the definitions from their respective interface files.
N OTE
Classes are only able to extend one class in ActionScript 2.0, although you can use
classes to implement as many interfaces as you want.
If you want your ClassA class to implement multiple interfaces in the previous example, you
would simply separate the interfaces with commas. Or, if you had a class that extended a
superclass and implemented multiple interfaces, you would use code similar to the following:
class ClassA extends ClassB implements Ib, Ic, Id {...}.
To build an interface:
1. Create a new ActionScript file and save it as IDocumentation.as.
2. In IDocumentation.as, type the following ActionScript code into the Script window:
interface IDocumentation {
public function downloadUpdates():Void;
public function checkForUpdates():Boolean;
public function searchHelp(keyword:String):Array;
}
3. Save the changes that you made to the ActionScript interface file.
4. Create a new ActionScript file in the same directory as the IDocumentation.as file, and save
this new file as FlashPaper.as.
This error appears because the current FlashPaper class doesn’t define any of the public
methods that you defined in the IDocumentation interface.
8. Open the FlashPaper.as class file again and modify the existing ActionScript code so that
it matches the following code:
class FlashPaper implements IDocumentation {
private static var __version:String = "1,2,3,4";
public function downloadUpdates():Void {
};
public function checkForUpdates():Boolean {
return true;
};
public function searchHelp(keyword:String):Array {
return []
};
}
9. Save your changes to the ActionScript file, and then click Check Syntax again.
This time you don’t see any errors appear in the Output panel.
NOT E
You can add as many additional static, public, or private variables or methods as you
want to the FlashPaper class file. The interface file defines only a set of minimum
methods that must appear within any class that implements that interface.
10. Open the IDocumentation interface document again, and add the following boldface line
of code (below the searchHelp() method):
interface IDocumentation {
public function downloadUpdates():Void;
public function checkForUpdates():Boolean;
public function searchHelp(keyword:String):Array;
public function addComment(username:String, comment:String):Void;
}
284 Interfaces
11. Save your changes to the interface file, and then reopen the FlashPaper.as document.
12. Click the Check Syntax button, and you see a new error message in the Output panel:
**Error** path\FlashPaper.as: Line 1: The class must implement method
'addComment' from interface 'IDocumentation'.
class FlashPaper implements IDocumentation {
Total ActionScript Errors: 1 Reported Errors: 1
You see the previous error because the FlashPaper.as class file no longer defines all the
classes that you outlined in the interface file. To fix this error message, you must either add
the addComment() method to the FlashPaper class or remove the method definition from
the IDocumentation interface file.
13. Add the following method in the FlashPaper class:
public function addComment(username:String, comment:String):Void {
/* Send parameters to server-side page, which inserts comment into
database. */
}
14. Save the changes to FlashPaper.as and click the Check Syntax button and you should no
longer receive any errors.
In the previous section, you created a class-based on the IDocumentation interface file. In this
section you create a new class that also implements the IDocumentation interface, although it
adds some additional methods and properties.
This tutorial demonstrates the usefulness of using interfaces because if you want to create
another class that extends the IDocumentation interface, you can easily identify the methods
that are required within the new class.
4. Save the ActionScript document and then create a new ActionScript document named
ClassB.as and save it in the complexInterface directory.
ClassB.as implements the InterfaceA interface you created previously.
5. In ClassB.as, type the following ActionScript code into the Script window:
// filename: ClassB.as
class ClassB implements InterfaceA {
public function k():Number {
return 25;
}
public function n(z:Number):Number {
return (z + 5);
}
}
6. Save your changes to the ClassB.as document and then create a new Flash document and
save it as classbTest.fla in the complexInterface directory.
This class file tests the ClassB class you created previously.
7. In classbTest.fla, type the following ActionScript code on Frame 1 of the Timeline:
// filename: classbTest.fla
import ClassB;
var myB:ClassB = new ClassB();
trace(myB.k()); // 25
trace(myB.n(7)); // 12
8. Save your changes to the Flash document, and then select Control >Test Movie to test the
Flash document.
The Output panel displays two numbers, 25 and 12, which are the results of the k() and
n() methods in the ClassB class.
9. Create a new ActionScript file and save it as ClassC.as in the complexInterface directory.
This class file implements the InterfaceA interface that you created in step 1.
286 Interfaces
10. In ClassC.as, type the following ActionScript code into the Script window:
// filename: ClassC.as
class ClassC implements InterfaceA {
public function k():Number {
return 25;
}
// **Error** The class must also implement method 'n' from interface
'InterfaceA'.
}
If you click the Check Syntax button for the ClassC class file, Flash displays an error
message in the Output panel that says the current class must implement the n() method
defined in the InterfaceA interface. When you create classes that implement an interface,
it is important that you define methods for each entry in the interface.
11. Create a new ActionScript document and save it as InterfaceB.as in the complexInterface
directory.
12. In InterfaceB.as, type the following ActionScript code into the Script window:
// filename: InterfaceB.as
interface InterfaceB {
public function o():Void;
}
13. Save your changes to the InterfaceB.as document, and then create a new ActionScript
document and save it in the complexInterface directory as ClassD.as.
This class implements both the InterfaceA interface and the InterfaceB interface you
created in earlier steps. The ClassD class must include method implementations for each
of the methods listed in each of the interface files.
14. In ClassD.as, type the following ActionScript code into the Script window:
// filename: ClassD.as
class ClassD implements InterfaceA, InterfaceB {
public function k():Number {
return 15;
}
public function n(z:Number):Number {
return (z * z);
}
public function o():Void {
trace("o");
}
}
15. Save your changes to the ClassD.as file, and then create a new Flash document and save it
as classdTest.fla.
This Flash document tests the ClassD class that you created previously.
17. Save your changes to the classdTest.fla file and then select Control > Test Movie to test the
file.
The values 15 and 49 and the letter o should be displayed in the Output panel. These
values are the results of the ClassD.k() method, ClassD.n(), and ClassD.o() methods,
respectively.
18. Create a new ActionScript document and save it as InterfaceC.as.
This interface extends the InterfaceA interface you created earlier, and it adds a new
method definition.
19. In InterfaceC.as, type the following ActionScript code into the Script window:
// filename: InterfaceC.as
interface InterfaceC extends InterfaceA {
public function p():Void;
}
20.Save your changes to the ActionScript file and then create a new ActionScript file and save
it as ClassE.as in the complexInterface directory.
This class implements two interfaces, InterfaceB and InterfaceC.
21. In ClassE.as, type the following ActionScript code into the Script window:
// filename: ClassE.as
class ClassE implements InterfaceB, InterfaceC {
public function k():Number {
return 15;
}
public function n(z:Number):Number {
return (z + 5);
}
public function o():Void {
trace("o");
}
public function p():Void {
trace("p");
}
}
22.Save your changes to the ActionScript document, and then create a new Flash document
and save it as classeTest.fla in the complexInterface directory.
288 Interfaces
23.In classeTest.fla, type the following ActionScript code on Frame 1 of the Timeline:
// filename: classeTest.fla
import ClassE;
var myE:ClassE = new ClassE();
trace(myE.k()); // 15
trace(myE.n(7)); // 12
myE.o(); // o
myE.p(); // p
24.Save the Flash document, and then select Control > Test Movie to test the SWF file.
The values 15, 12, o, and p display in the Output panel. These values are the values that
return from the ClassE.k(), ClassE.n(), ClassE.o(), and ClassE.p() methods. Since
the ClassE class implemented both the InterfaceB and InterfaceC interfaces, each method
from the two interface files must be defined. Although the InterfaceB and InterfaceC
interfaces only define the o() and p() methods, InterfaceC extends InterfaceA. This
means that all of its defined methods, k() and n(), must also be implemented.
Handling Events 9
Events are actions that occur while a SWF file is playing. An event such as a mouse click or a
keypress is called a user event because it occurs as a result of direct user interaction. An event
that Flash Player generates automatically, such as the initial appearance of a movie clip on the
Stage, is called a system event because it isn’t generated directly by the user.
In order for your application to react to events, you must use event handlers—ActionScript
code associated with a particular object and event. For example, when a user clicks a button
on the Stage, you might advance the playhead to the next frame. Or when an XML file
finishes loading over the network, the contents of that file might appear in a text field.
You can handle events in ActionScript in several ways:
■ “About ActionScript and events” on page 292
■ “Using event listeners” on page 296
■ “Using button and movie clip event handlers” on page 300, specifically, on handler and
onClipEvent handler.
■ “Broadcasting events from component instances” on page 305
Using event handlers with loadMovie (MovieClip.loadMovie method) can be unpredictable.
If you attach an event handler to a button using on(), or if you create a dynamic handler
using an event handler method such as onPress (MovieClip.onPress handler), and then you
call loadMovie(), the event handler is not available after the new content is loaded. However,
if you use onClipEvent handler or on handler to attach an event handler to a movie clip, and
then call loadMovie() on that movie clip, the event handler is still available after the new
content is loaded.
291
For more information on handling events, see the following sections:
About ActionScript and events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .292
Using event listeners . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .296
Using event listeners with components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .298
Using button and movie clip event handlers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
Broadcasting events from component instances . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
Creating movie clips with button states . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
Event handler scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
Scope of the this keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
Using the Delegate class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
Frame events
On a main or movie clip timeline, a system event occurs when the playhead enters a
keyframe—this is known as a frame event. Frame events are useful for triggering actions based
on the passage of time (moving through the timeline) or for interacting with elements that are
currently visible on the Stage. When you add a script to a keyframe, it is executed when the
keyframe is reached during playback. A script attached to a frame is called a frame script.
One of the most common uses of frame scripts is to stop the playback when a certain
keyframe is reached. This is done with the stop() function. You select a keyframe and then
add the stop() function as a script element in the Actions panel.
When you’ve stopped the SWF file at a certain keyframe, you need to take some action. You
could, for example, use a frame script to dynamically update the value of a label, to manage
the interaction of elements on the Stage, and so on.
For example, suppose you have a button named next_btn on the Stage. The following code
assigns a function to the button’s onPress event handler; this function advances the playhead
to the next frame in the current timeline:
next_btn.onPress = function () {
nextFrame();
}
Notice in the following example that you assign the function reference, not the function’s
return value, to the onPress event handler:
// Incorrect!
next_btn.onPress = goNextFrame();
// Correct.
next_btn.onPress = goNextFrame;
Event handlers for runtime objects You can also assign functions to event handlers for
objects you create at runtime. For example, the following code creates a new movie clip
instance (newclip_mc) and then assigns a function to the clip’s onPress event handler:
this.attachMovie("symbolID", "newclip_mc", 10);
newclip_mc.onPress = function () {
trace("You pressed me");
}
For more information, see “Creating movie clips at runtime” on page 321.
Overriding event handler methods By creating a class that extends an ActionScript class,
you can override event handler methods with the functions that you write. You can define an
event handler in a new subclass that you can then reuse for various objects by linking any
symbol in the library of the extended class to the new subclass. The following code overrides
the MovieClip class’s onPress event handler with a function that decreases the transparency
of the movie clip:
// FadeAlpha class -- sets transparency when you click the movie clip.
class FadeAlpha extends MovieClip {
function onPress() {
this._alpha -= 10;
}
}
For specific instructions on extending an ActionScript class and linking to a symbol in the
library, see the examples in “Assigning a class to symbols in Flash” on page 239. For
information on writing and working with custom classes, see Chapter 6, “Classes.”
The code starts with an object, listenerObject, with a property eventName. Your listener
object can be any object, such as an existing object, movie clip, or button instance on the
Stage, or it can be an instance of any ActionScript class. For example, a custom movie clip
could implement the listener methods for Stage listeners. You could even have one object that
listens to several types of listeners.
The eventName property is an event that occurs on broadcasterObject, which then
broadcasts the event to listenerObject. You can register multiple listeners to one
event broadcaster.
You assign a function to the event listener that responds to the event in some way.
Last, you call the addListener() method on the broadcaster object, passing the listener
object to the addListener() method.
To unregister a listener object from receiving events, you call the removeListener() method
of the broadcaster object, passing it the name of the event to remove, and the listener object.
broadcasterObject.removeListener(listenerObject);
This code creates an object named focusListener that defines an onSetFocus property
and assigns a function to the property. The function takes two parameters: a reference to
the text field that does not have focus and one to the text field that has focus. The
function sets the border property of the text field that does not have focus to false, and
sets the border property of the text field that has focus to true.
6. To register the focusListener object to receive events from the Selection object, add the
following code to the Actions panel:
// Registers focusListener with broadcaster.
Selection.addListener(focusListener);
7. Test the application (Control > Test Movie), click in the first text field, and press the Tab
key to switch focus between fields.
my_ldr.addEventListener("progress", loaderListener);
my_ldr.addEventListener("complete", loaderListener);
my_ldr.load("http://www.helpexamples.com/flash/images/image1.jpg");
This ActionScript code defines a listener object named loaderListener, which listens for
two events: progress and complete. When each of these events are dispatched, their
code is executed, and debugging text is displayed in the Output panel if you test the SWF
file in the authoring tool.
Next you tell the my_ldr instance to listen for each of the two specified events (progress
and complete) and specify the listener object or function to execute when the event is
dispatched. Finally, the Loader.load() method is called, which triggers the image to
begin downloading.
4. Select Control > Test Movie to test the SWF file.
The image downloads into the Loader instance on the Stage, and then several messages are
displayed in the Output panel. Depending on the size of the image you download, and if
the image was cached on the user’s local system, the progress event might be dispatched
numerous times, whereas the complete event is only dispatched after the image is
completely downloaded.
When you work with components and dispatch events, the syntax is slightly different
from the event listeners in previous examples. Most notably, you must use the
addEventListener() method instead of calling addListener(). Secondly, you must
specify the specific event you want to listen for as well as the event listener object
or function.
my_ldr.addEventListener("progress", progressListener);
my_ldr.addEventListener("complete", completeListener);
my_ldr.load("http://www.helpexamples.com/flash/images/image1.png");
function progressListener(evt_obj:Object):Void {
trace(evt_obj.type); // progress
trace("\t" + evt_obj.target.bytesLoaded + " of " +
evt_obj.target.bytesTotal + " bytes loaded");
}
function completeListener(evt_obj:Object):Void {
trace(evt_obj.type); // complete
}
NOT E
In the previous examples, the event listeners are always added before the
Loader.load() method is called. If you call the Loader.load() method before you
specify the event listeners, the load might complete before the event listeners are
fully defined. This means that the content might display and the complete event might
not be caught.
Do not confuse button and movie clip event handlers with component events, such as
SimpleButton.click, UIObject.hide, and UIObject reveal, which must be
attached to component instances and are discussed in Using ActionScript 2.0
Components.
Attaching onClipEvent() and on() handlers is not a recommended practice. Instead, you
should put your code in frame scripts or in a class file, as demonstrated throughout this
manual. For more information, see “About ActionScript and events” on page 292 and
“Attaching code to objects” on page 680.
For more information on button and movie clip event handlers, see the following topics:
■ “Using on and onClipEvent with event handler methods” on page 301
■ “Specifying events for on or onClipEvent methods” on page 303
■ “Attaching or assigning multiple handlers to one object” on page 304
For example, the following on() event handler executes whenever the user clicks the button to
which the handler is attached:
on (press) {
trace("Thanks for pressing me.");
}
You can specify two or more events for each on() handler, separated by commas. The
ActionScript in a handler executes when either of the events specified by the handler occurs.
For example, the following on() handler attached to a button executes whenever the mouse
rolls over and then off the button:
on (rollOver, rollOut) {
trace("You rolled over, or rolled out");
}
You can also add key press events using on() handlers. For example, the following code traces
a string when you press the number 3 on the keyboard. Select a button or movie clip instance,
and add the following code to the Actions panel:
on (keyPress "3") {
trace("You pressed 3")
}
Or, if you want to trace when the Enter key is pressed by a user, you could use the following
code format. Select a button or movie clip instance, and add the following code to the Actions
panel:
on (keyPress "<Enter>") {
trace("Enter Pressed");
}
Select Control > Test Movie, and press the Enter key to see the string trace to the Output
panel. If nothing traces, select Control > Disable Keyboard Shortcuts and try again. For more
information on adding keypress interactivity to your applications, see Key.
N OTE
Attaching onClipEvent() and on() handlers is not a recommended practice. Instead, you
should put your code in frame scripts or in a class file, as demonstrated throughout this
manual. For more information, see “About ActionScript and events” on page 292 and
“Attaching code to objects” on page 680.
Attaching onClipEvent() and on() handlers is not a recommended practice. Instead, you
should put your code in frame scripts or in a class file, as demonstrated throughout this
manual. For more information, see “About ActionScript and events” on page 292 and
“Attaching code to objects” on page 680.
To attach multiple handlers to one object using code that’s placed on the timeline, see the
following example. The code attaches the onPress and onRelease handlers to a movie clip
instance.
10. Select Frame 10, all three layers, and select Insert > Timeline > Keyframe.
11. Add a stop() action on Frame 10 of the actions layer, and add a frame label of _over in
frame 10 of the labels layer.
12. Select the rectangle on Frame 10 and use the Property inspector to select a different
fill color.
13. Create new keyframes on frame 20 of each of the three layers, and add a frame label of
_down in the Property inspector.
14. Modify the color of the rectangle in Frame 20 so each of the three button states have a
different color.
15. Return to the main timeline.
16. To make the movie clip respond to mouse events, do one of the following:
■ Attach an on() event handler to the movie clip instance, as discussed in “Using button
and movie clip event handlers” on page 300).
■ Assign a function to one of the movie clip object’s mouse event handlers (onPress,
onRelease, and so forth), as discussed in “About ActionScript and events”
on page 292.
17. Select Control > Test Movie to test the Flash document.
Move your mouse pointer over the movie clip instance on the Stage and the movie clip
automatically goes to the movie clip’s _over state. Click the movie clip instance and the
playhead automatically goes to the movie clip’s _down state.
Although both event handlers contain the same code, they have different results. In the first
case, the color variable is local to the function defined for onPress. In the second case,
because the on() handler doesn’t define a local variable scope, the variable is defined in the
scope of the timeline of the clip_mc movie clip.
For on() event handlers attached to buttons, rather than to movie clips, variables (as well as
function and method calls) are invoked in the scope of the timeline that contains the
button instance.
For instance, the following on() event handler produces different results that depend on
whether it’s attached to a button or movie clip object. In the first case, the play() function
call starts the playhead of the timeline that contains the button; in the second case, the
play() function call starts the timeline of the movie clip to which the handler is attached.
// Attached to button.
on (press) {
play(); // Plays parent timeline.
}
// Attached to movie clip.
on (press) {
play(); // Plays movie clip's timeline.
}
When attached to a button object, the play() function applies to the timeline that contains
the button—that is, the button’s parent timeline. But when the on(press) handler is
attached to a movie clip object, the play() function call applies to the movie clip that bears
the handler. If you attach the following code to a movie clip, it plays the parent timeline:
// Attached to movie clip.
on (press) {
_parent.play(); // Plays parent timeline.
}
To play the movie clip that defines the onPress event handler, refer explicitly to that clip
using the this keyword, as follows:
// Function defined on root timeline
my_mc.onPress = function () {
this.play(); // plays timeline of my_mc clip.
};
However, the same code placed on the root timeline for a button instance would instead play
the root timeline:
my_btn.onPress = function () {
this.play(); // plays root timeline
};
For more information about the scope of the this keyword in event handlers, see “Scope of
the this keyword” on page 310.
ActionScript 2.0 example The following TextLoader class is used to load a text file and
display some text after it successfully loads the file.
// TextLoader.as
class TextLoader {
private var params_lv:LoadVars;
public function TextLoader() {
params_lv = new LoadVars();
params_lv.onLoad = onLoadVarsDone;
params_lv.load("http://www.helpexamples.com/flash/params.txt");
}
private function onLoadVarsDone(success:Boolean):Void {
_level0.createTextField("my_txt", 999, 0, 0, 100, 20);
_level0.my_txt.autoSize = "left";
_level0.my_txt.text = params_lv.monthNames; // undefined
}
}
Within an on() handler attached to a movie clip, this refers to the movie clip to which the
on() handler is attached, as shown in the following code:
// Attached to movie clip named my_mc on main timeline
on (press) {
trace(this); // _level0.my_mc
}
Within an on() handler attached to a button, this refers to the timeline that contains the
button, as shown in the following code:
// Attached to button on main timeline
on (press) {
trace(this); // _level0
}
The following example shows three methods of listening for events for a Button component
instance. Each way that you add event listeners to a Button component instance results in the
event being dispatched in a different scope.
function clickHandler(eventObj:Object):Void {
trace("[" + eventObj.type + "] event on " + eventObj.target + "
instance.");
trace("\t this -> " + this);
}
The preceding code is separated into six sections (each section is separated by a blank
line). The first section imports the Button class (for the Button component) as well as the
Delegate class. The second section of code defines a function that you call when the user
clicks some of the buttons. The third section of code creates an object that you use as an
event listener, and the object listens for a single event, click.
When you click one_button instance, the this scope refers to the button instance
itself.
b. Click the second button on the Stage to trace the following text in the Output panel:
[click] event on _level0.two_button instance.
this -> [object Object]
When you click the two_button instance, the this scope refers to the
buttonListener object.
c. Click the third button on the Stage to trace the following text in the Output panel:
[click] event on _level0.three_button instance.
this -> _level0
When you click the three_button instance, the this scope refers to the scope that
you specify in the Delegate.create() method call, or in this case, _level0.
313
For more information on movie clips, see the following topics:
About controlling movie clips with ActionScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
Calling multiple methods on a single movie clip . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
Loading and unloading SWF files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
Changing movie clip position and appearance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
Dragging movie clips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
Creating movie clips at runtime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321
Adding parameters to dynamically created movie clips. . . . . . . . . . . . . . . . . . . . . . .325
Managing movie clip depths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
About caching and scrolling movie clips with ActionScript . . . . . . . . . . . . . . . . . . 330
Using movie clips as masks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
Handling movie clip events. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .339
Assigning a class to a movie clip symbol. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .339
Initializing class properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
The following example shows the difference between using a method and using a function.
Each statement duplicates the instance my_mc, names the new clip new_mc, and places it at a
depth of 5.
my_mc.duplicateMovieClip("new_mc", 5);
duplicateMovieClip(my_mc, "new_mc", 5);
When a function and a method offer similar behaviors, you can select to control movie clips
by using either one. The choice depends on your preference and your familiarity with writing
scripts in ActionScript. Whether you use a function or a method, the target timeline must be
loaded in Flash Player when the function or method is called.
To use a method, activate it by using the target path of the instance name, a dot (.), and then
the method name and parameters, as shown in the following statements:
myMovieClip.play();
parentClip.childClip.gotoAndPlay(3);
The following MovieClip methods can control movie clips or loaded levels and do not have
equivalent functions: MovieClip.attachMovie(), MovieClip.createEmptyMovieClip(),
MovieClip.createTextField(), MovieClip.getBounds(),
MovieClip.getBytesLoaded(), MovieClip.getBytesTotal(), MovieClip.getDepth(),
MovieClip.getInstanceAtDepth(), MovieClip.getNextHighestDepth(),
MovieClip.globalToLocal(), MovieClip.localToGlobal(), MovieClip.hitTest(),
MovieClip.setMask(), MovieClip.swapDepths().
For more information about these functions and methods, see their entries in the ActionScript
2.0 Language Reference.
For a sample source file, animation.fla, that illustrates scripted animation in Flash, see the
Flash Samples page at www.adobe.com/go/learn_fl_samples. Download and decompress the
Samples zip file and navigate to the ActionScript2.0/Animation folder to access the sample.
For samples of photo gallery applications, see the Flash Samples page at www.adobe.com/go/
learn_fl_samples. Download and decompress the Samples zip file and navigate to the
ActionScript2.0/Galleries folder to access these samples:
■ gallery_tree.fla
■ gallery_tween.fla
These files provide examples of how to use ActionScript to control movie clips dynamically
while loading image files into a SWF file, which includes scripted animation.
The script behaves as if the statements inside the with statement were called from the timeline
of the hole instance. The preceding code is equivalent to the following example:
donut.hole._alpha = 20;
donut.hole._xscale = 150;
donut.hole._yscale = 150;
In the following example, the loaded SWF file, contents.swf, also declares a variable named
userName on its root timeline:
// In contents.swf:
_root.userName = "Mary";
After contents.swf loads into the movie clip in container.swf, the value of userName that’s
attached to the root timeline of the hosting SWF file (container.swf ) would be set to "Mary"
instead of "Tim". This could cause code in container.swf (as well as contents.swf ) to
malfunction.
To force _root to always evaluate to the timeline of the loaded SWF file, rather than the
actual root timeline, use the _lockroot property. You can set this property from within the
SWF file being loaded or in the SWF file that is initiating the loading. When _lockroot is set
to true on a movie clip instance, that movie clip acts as _root for any SWF file loaded into it.
When _lockroot is set to true within a SWF file, that SWF file acts as its own root, no
matter what other SWF file loads it. Any movie clip, and any number of movie clips, can set
_lockroot to true. By default, this property is false.
For example, the author of container.swf could put the following code on Frame 1 of the
main Timeline:
// Added to Frame 1 in container.swf:
target_mc._lockroot = true;
This step ensures that any references to _root in contents.swf—or any SWF file loaded into
target_mc—refers to its own timeline, not to the actual root timeline of container.swf. Now
when you click the button, "Tim" appears.
Alternatively, the author of contents.swf could add the following code to its main timeline:
// Added to Frame 1 in contents.swf:
this._lockroot = true;
This would ensure that no matter where contents.swf is loaded, any reference it makes to
_root refers to its own main timeline, not to that of the hosting SWF file.
This is equivalent to the following code, which uses the setProperty() function:
setProperty("my_mc", _rotation, 45);
Some properties, called read-only properties, have values that you can read but cannot set.
(These properties are specified as read-only in their ActionScript 2.0 Language Reference
entries.) The following are read-only properties: _currentframe, _droptarget,
_framesloaded, _parent, _target, _totalframes, _url, _xmouse, and _ymouse.
You can write statements to set any property that is not read-only. The following statement
sets the _alpha property of the wheel_mc movie clip instance, which is a child of the
car_mc instance:
car_mc.wheel_mc._alpha = 50;
In addition, you can write statements that get the value of a movie clip property. For example,
the following statement gets the value of the _xmouse property on the current level’s timeline
and sets the _x property of the my_mc instance to that value:
this.onEnterFrame = function() {
This is equivalent to the following code, which uses the getProperty() function:
this.onEnterFrame = function() {
my_mc._x = getProperty(_root, _xmouse);
};
The _x, _y, _rotation, _xscale, _yscale, _height, _width, _alpha, and _visible
properties are affected by transformations on the movie clip’s parent, and transform the movie
clip and any of the clip’s children. The _focusrect, _highquality, _quality, and
_soundbuftime properties are global; they belong only to the level 0 main timeline. All other
properties belong to each movie clip or loaded level.
For a list of movie clip properties, see the property summary for the MovieClip class in the
ActionScript 2.0 Language Reference.
For a sample source file, animation.fla, that illustrates scripted animation in Flash, see the
Flash Samples page at www.adobe.com/go/learn_fl_samples. Download and decompress the
Samples zip file and navigate to the ActionScript2.0/Animation folder to access the sample.
For samples of photo gallery applications, see the Flash Samples page at www.adobe.com/go/
learn_fl_samples. Download and decompress the Samples zip file and navigate to the
ActionScript2.0/Galleries folder to access these samples:
■ gallery_tree.fla
■ gallery_tween.fla
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);
For a sample source file, animation.fla, that creates and removes numerous movie clips at
runtime, see the Flash Samples page at www.adobe.com/go/learn_fl_samples. Download and
decompress the Samples zip file and navigate to the ActionScript2.0/Animation folder to
access the sample.
The initObject parameter specifies the name of the object whose parameters you want to
use to populate the dynamically created movie clip.
This example creates a new movie clip with a depth of 10 within the z-order space of
container_mc.
The following code attaches two new movie clips to container_mc. The first clip, named
clip1_mc, is rendered behind clip2_mc because it was assigned a lower depth value.
container_mc.attachMovie("symbolID", "clip1_mc", 10);
container_mc.attachMovie("symbolID", "clip2_mc", 15);
Depth values for movie clips can range from -16384 to 1048575. If you create or attach a new
movie clip on a depth that already has a movie clip, the new or attached clip overwrites the
existing content. To avoid this problem, use the MovieClip.getNextHighestDepth()
method; however, do not use this method with components that use a different depth-
management system. Instead, use DepthManager class with component instances. For more
information, see ActionScript 2.0 Components Language Reference.
The MovieClip class provides several methods for managing movie clip depths; for more
information, see getNextHighestDepth (MovieClip.getNextHighestDepth method),
getInstanceAtDepth (MovieClip.getInstanceAtDepth method), getDepth
(MovieClip.getDepth method), and swapDepths (MovieClip.swapDepths method) in
the ActionScript 2.0 Language Reference.
For more information on movie clip depths, see the following topics:
■ “Determining the next highest available depth” on page 328
■ “Determining the instance at a particular depth” on page 328
■ “Determining the depth of an instance” on page 329
■ “Swapping movie clip depths” on page 329
In this case, the variable named nextDepth contains the value 11 because that’s the next
highest available depth for the edit_mc movie clip.
Do not use MovieClip.getNextHighestDepth() with components; instead, use the depth
manager. For more information, see “DepthManager class” in Action Script 2.0 Components
Language Reference. For more information on MovieClip.getNextHighestDepth(), see
getNextHighestDepth (MovieClip.getNextHighestDepth method).
To obtain the current highest occupied depth, subtract 1 from the value that
getNextHighestDepth() returns, as shown in the next section.
You can update the vector data, at which time the surface is recreated. Therefore, the
vector data cached in the surface does not need to remain the same for the entire SWF
file.
You can use ActionScript to enable caching or scrolling and to control backgrounds. You can
use the Property inspector to enable caching for a movie clip instance. To cache movie clips or
buttons without using ActionScript, you can select the Use runtime bitmap caching option in
the Property inspector instead.
Property Description
cacheAsBitmap Makes the movie clip instance cache a bitmap representation of itself.
Flash creates a surface object for the instance, which is a cached
bitmap instead of vector data. If you change the bounds of the movie
clip, the surface is recreated instead of resized. For more information
and an example, see “Caching a movie clip” on page 334.
opaqueBackground Lets you specify a background color for the opaque movie clip
instance. If you set this property to a numeric value, the movie clip
instance has an opaque (nontransparent) surface. An opaque bitmap
does not have an alpha channel (transparency), and renders faster. For
more information and an example, see “Setting the background of a
movie clip” on page 336.
scrollRect Lets you quickly scroll movie clip content and have a window for
viewing larger content. The movie clip’s contents are cropped, and the
instance scrolls with a specified width, height, and scroll offsets. This
lets the user quickly scroll movie clip content and have a window that
displays larger content than the Stage area. Text fields and complex
content that you display in the instance can scroll faster because Flash
does not regenerate the entire movie clip vector data. For more
information and an example, see scrollRect (MovieClip.scrollRect
property).
These three properties are independent of each other, however, the opaqueBackground and
scrollRect properties work best when an object is cached as a bitmap. You only see
performance benefits for the opaqueBackground and scrollRect properties when you set
cacheAsBitmap to true.
To create a surface that’s also scrollable, you must set the cacheAsBitmap and scrollRect
properties for the movie clip instance. Surfaces can nest within other surfaces. The surface
copies the bitmap onto its parent surface.
For information on alpha channel masking, which requires you to set the cacheAsBitmap
property to true, see “About alpha channel masking” on page 338.
NO TE
You cannot apply caching directly to text fields. You need to place text within a movie
clip to take advantage of this feature. For a sample file, see the Flash Samples page at
www.adobe.com/go/learn_fl_samples. Download and decompress the Samples zip file
and navigate to the ActionScript2.0/CacheBitmap folder to access the sample.
To create a mask:
1. Create a square on the Stage with the Rectangle tool.
2. Select the square and press F8 to convert it into a movie clip.
This instance is your mask.
3. In the Property inspector, type mask_mc in the Instance Name text box.
The masked movie clip is revealed under all opaque (nontransparent) areas of the movie
clip acting as the mask.
4. Select Frame 1 in the Timeline.
5. Open the Actions panel (Window > Actions) if it isn’t already open.
6. In the Actions panel, enter the following code:
System.security.allowDomain("http://www.helpexamples.com");
this.createEmptyMovieClip("img_mc", 10);
var mclListener:Object = new Object();
mclListener.onLoadInit = function(target_mc:MovieClip):Void {
target_mc.setMask(mask_mc);
}
var my_mcl:MovieClipLoader = new MovieClipLoader();
my_mcl.addListener(mclListener);
my_mcl.loadClip("http://www.helpexamples.com/flash/images/image1.jpg",
img_mc);
When you test the document (Control > Test Movie), the maskee is alpha blended by using
the mask.
NOT E
Mask layers do not support alpha channel masking. You must use ActionScript code to
apply a mask, and use runtime bitmap caching.
This code creates two new instances of the symbol on the root timeline of the SWF file.
The first instance, named ball50_mc, moves 50 pixels each time it is clicked; the second,
named ball125_mc, moves 125 pixels each time it is clicked.
10. Select Control > Test Movie to test the SWF file.
343
Fonts Sets of characters with a similar font face, style, and size.
String A sequence of characters.
Text A series of one or more strings that can be displayed in a text field, or within a user
interface component.
Text fields A visual element on the Stage that lets you display text to a user. Similar to an
input text field or text area form control in HTML, Flash lets you set text fields as editable
(read-only), allow HTML formatting, enable multiline support, password masking, or apply a
CSS stylesheet to your HTML formatted text.
Text formatting You can apply formatting to a text field, or certain characters within a text
field. Some examples of text formatting options that can be applied to text are: alignment,
indenting, bold, color, font size, margin widths, italics, and letter spacing.
For more information on text, see the following topics:
About text fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344
Using the TextField class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .346
About loading text and variables into text fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . .353
Using fonts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
About font rendering and anti-alias text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
About text layout and formatting. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375
Formatting text with Cascading Style Sheet styles . . . . . . . . . . . . . . . . . . . . . . . . . .382
Creating a style sheet object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .385
Using HTML-formatted text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .397
Example: Creating scrolling text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410
All text fields support Unicode. For information on Unicode, see “About strings and the
String class” on page 411
The methods of the TextField class let you set, select, and manipulate text in a dynamic or
input text field that you create during authoring or at runtime. For more information, see
“Using the TextField class” on page 346. For information on debugging text fields at runtime,
see Using Flash.
ActionScript also provides several ways to format your text at runtime. The TextFormat class
lets you set character and paragraph formatting for TextField objects (see “Using the
TextFormat class” on page 380). Flash Player also supports a subset of HTML tags that you
can use to format text (see “Using HTML-formatted text” on page 397). Flash Player 7 and
later supports the img HTML tag, which lets you embed not just external images but also
external SWF files as well as movie clips that reside in the library (see “Image tag”
on page 400).
In Flash Player 7 and later, you can apply Cascading Style Sheet (CSS) styles to text fields
using the TextField.StyleSheet class. You can use CSS styles to style built-in HTML tags,
define new formatting tags, or apply styles. For more information on using CSS, see
“Formatting text with Cascading Style Sheet styles” on page 382.
You can also assign HTML formatted text, which might optionally use CSS styles, directly to
a text field. In Flash Player 7 and later, HTML text that you assign to a text field can contain
embedded media (movie clips, SWF files, and JPEG files). In Flash Player 8 and later, you can
also dynamically load PNG, GIF, and progressive JPEG images (Flash Player 7 does not
support progressive JPEG images). The text wraps around the embedded media similar to
how a web browser wraps text around media embedded in an HTML document. For more
information, see “Image tag” on page 400.
For information on the terminology that compares text, strings, and more, see the
introduction for this chapter, “Working with Text and Strings” on page 343.
This code creates a new text field with the instance name headline_txt. The text field is
created at the next highest depth, at the x and y coordinates of 100, 100, with a text field
width of 200 pixels and a height of 20 pixels. When you test the SWF file (Control > Test
Movie), the text “New articles available on Developer Center” appears on the Stage.
When you use HTML formatted text with a text field (not components) on the Stage, you
must assign the text to the text field’s htmlText property instead of the text property.
For samples that demonstrate how to work with text fields using ActionScript, see the Flash
Samples page at www.adobe.com/go/learn_fl_samples. Download the Samples zip file and
navigate to the ActionScript 2.0/TextFields folder to access these samples:
■ textfieldsA.fla
■ textfieldsB.fla
However, you can’t use the variable name myTextVar to set the text field’s text property. You
have to use the instance name, as shown in the following code:
// This won't work.
myTextVar.text = "A text field variable is not an object reference";
// For input text field with instance name "myField", this will work.
myField.text = "This sets the text property of the myField object";
This code creates a 300 x 100-pixel text field named test_txt with a location of (0, 0)
and a depth (z-order) of 10.
3. To access the methods and properties of the newly created text field, use the instance name
specified in the first parameter of the createTextField() method.
For example, the following code creates a new text field named test_txt, and modifies its
properties to make it a multiline, word-wrapping text field that expands to fit inserted
text. Then it assigns some text using the text field’s text property:
test_txt.multiline = true;
test_txt.wordWrap = true;
test_txt.autoSize = "left";
test_txt.text = "Create new text fields with the
MovieClip.createTextField() method.";
Some TextField properties, such as _rotation, are not available when you create text
fields at runtime. You can rotate a text field only if it uses embedded fonts. See “To
embed a font symbol:” on page 361.
For samples that demonstrate how to work with text fields using ActionScript, see the Flash
Samples page at www.adobe.com/go/learn_fl_samples. Download the Samples zip file and
navigate to the ActionScript 2.0/TextFields folder to access these samples:
■ textfieldsA.fla
■ textfieldsB.fla
For a complete list of properties in the TextField class, see the ActionScript 2.0 Language
Reference.
For examples of how to manipulate text fields, see the following sections:
■ “Changing a text field’s position” on page 351
■ “Changing a text field’s dimensions at runtime” on page 351
For samples that demonstrate how to work with text fields using ActionScript, see the Flash
Samples page at www.adobe.com/go/learn_fl_samples. Download the Samples zip file and
navigate to the ActionScript 2.0/TextFields folder to access these samples:
■ textfieldsA.fla
■ textfieldsB.fla
3. Save the Flash document and select Control > Test Movie to see the text field centered on
the Stage.
For samples that demonstrate how to work with text fields using ActionScript, see the Flash
Samples page at www.adobe.com/go/learn_fl_samples. Download the Samples zip file and
navigate to the ActionScript 2.0/TextFields folder to access these samples:
■ textfieldsA.fla
■ textfieldsB.fla
If you paste this code directly into the Actions panel from some versions of Flash
Help, you may encounter line breaks in the long text string. In this case, the code
won’t compile. If you encounter this situation, enable Hidden Characters on the pop-
up menu of the Actions panel, and then remove the line break characters in the long
text string.
3. Save the Flash document and select Control > Test Movie to view the Flash document in
the authoring environment.
Flash resizes the text field vertically so that all the content can be displayed without being
cropped by the text field boundaries. If you set the my_txt.wordWrap property to false,
the text field resizes horizontally to accommodate the text.
To enforce a maximum height on the auto-sized text field (so that the text field height
doesn’t exceed the boundaries of the Stage), use the following code.
if (my_txt._height > 160) {
my_txt.autoSize = "none";
my_txt._height = 160;
}
3. Save the Flash document and select File > Publish to generate the HTML and SWF files.
NOT E
An HTML document publishes, by default, to the same directory as your FLA file. If
an HTML document does not publish, select File > Publish Settings and then select
the Formats tab. Make sure that you select HTML.
The first block of code in the previous snippet creates a new text field on the Stage and
enables multiline and word wrapping. The second block of code defines a new LoadVars
object that is used to load a text file (lorem.txt) from a remote web server and display its
contents into the my_txt text field created earlier.
3. Save the Flash document and select Control > Test Movie to test the SWF file.
After a slight delay, Flash displays the contents of the remote file in the text field on
the Stage.
For information on security, see Chapter 16, “Understanding Security.”
3. Save the Flash document and select Control > Test Movie from the main menu.
Because you are using the LoadVars.onLoad() method instead of LoadVars.onData(),
Flash parses out the variables and creates variables within the LoadVars object instance.
The external text file contains two variables, monthNames and dayNames, which both
contain strings.
For information on security, see Chapter 16, “Understanding Security.”
The first block of code in the preceding snippet creates a new text field on the Stage. This
text field is used to display various parts of the XML document that is loaded later. The
second block of code handles creating an XML object that will be used to load the XML
content. Once the date is completely loaded and parsed by Flash, the XML.onLoad() event
handler is invoked and displays the contents of the XML packet in the text field.
3. Save the Flash document and select Control > Test Movie to test the SWF file.
Flash displays the following output in the text field on the Stage:
Item 1
Item 2
...
Item 8
Clicking Don’t Embed in the Character Embedding dialog box removes any specified
embedded characters and character sets that were previously chosen without asking
you to confirm.
Embedding characters
If you’re working with embedded fonts and know exactly what characters you need, you can
reduce file size by embedding only the characters that you need instead of including
additional, unused font outlines. To embed certain characters within a text field and not
embed a whole character set, use the Character Embedding dialog box to specify which
specific characters you want to embed.
Flash can determine characters to embed automatically only if the text field contains
text on the Stage. If the text field is populated by using ActionScript, you must
specify which characters you want to embed for the text field.
Embedding fonts
When you embed fonts, Flash stores all of the font information in the SWF file so the font is
displayed properly even if it’s not installed on the user’s computer. If you use a font in your
FLA file that isn’t installed on a user’s system, and you don’t embed the font in the SWF file,
Flash Player automatically selects a substitute font to use instead.
NO TE
You need to embed a font only if you’re using dynamic or input text fields. If you use a
static text field, you don’t need to embed the font.
Each character set you select increases the final size of the SWF file because Flash
has to store all of the font information for each character set that you use.
6. Select the individual characters or character sets you want to embed, and then click OK to
apply the changes and return to your document.
7. Select Control > Test Movie to test the Flash document in the authoring environment.
The embedded font is displayed in the text field on the Stage. To properly test that the
font is embedded, you might need to test on a separate computer without the embedded
font installed.
Or you can set the TextField._alpha or TextField._rotation properties for the text
field with embedded fonts, because these properties work only on embedded fonts (see the
following steps).
8. Close the SWF file and return to the authoring tool.
9. Select the text field on the Stage, and open the Property inspector.
a. Set the text field’s Text type to Dynamic Text.
b. Type font_txt into the Instance Name text box.
10. Add the following code to Frame 1 of the Timeline:
font_txt._rotation = 45;
11. Select Control > Test Movie again to view the changes in the authoring environment.
If you don’t embed a font within your Flash document and Flash Player automatically
chooses a font substitute on the user’s computer, the TextField.font property returns
the original font used within the FLA, not the name of the substituted font.
N OTE
If you use embedded fonts with a variety of styles in your text fields, you must embed
the style that you want to use. For example, if you’re using an embedded font called
Times, and then want a word to be italic, you must make sure to embed both the
normal and italic character outlines. Otherwise, the text won’t appear in the text field.
Notice that the glyphRange node includes name, Uppercase [A..Z], and id. A glyphRange
node can have as many range child nodes as you need. A range can be a single character, such
as 0x0020 (the space character), seen in the previous snippet, or a range of characters, such as
the second range child node. To embed only a single character, set the min value and the max
value to the same unicode character value.
This range of characters includes the Unicode values 0x0030 (zero) through 0x0039 (9), as
well as 0x002E (.).
Before you create a custom character set, you need to know the characters and their
corresponding Unicode values. The best place to find Unicode values is the Unicode
Standards web site, www.unicode.org, which contains the Unicode Character Code chart for
dozens of languages.
C A U T IO N
To add custom character sets, you need to edit an XML file in the Flash installation
folder. Before you edit this file, you should make a backup copy in case you want to
revert to the original Unicode table.
C A UTI ON
Adobe recommends that you do not modify the existing character sets that are installed
with Flash, and that you instead make your own custom character sets that include the
characters and punctuation that you require.
Remember to save a backup of this document, in case you want to revert to the
original file that is installed with Flash.
2. Scroll to the bottom of the XML document and add the following XML code directly
before the closing </fontEmbeddingTable> node:
<glyphRange name="Uppercase and Numerals [A..Z,0..9] " id="100" >
<range min="0x0020" max ="0x0020" />
<range min="0x002E" max ="0x002E" />
<range min="0x0030" max ="0x0039" />
<range min="0x0041" max ="0x005A" />
</glyphRange>
The position of a character set in the Character Embedding dialog box is determined
by its location in the XML document. You can reorder the character sets, including
your custom character sets, by moving <glyphRange> packets in the XML file.
// 2
var style_fmt:TextFormat = new TextFormat();
style_fmt.font = "Times (embedded)";
style_fmt.size = 30;
lorem_txt.setTextFormat(style_fmt);
// 3
var mouseListener:Object = new Object();
mouseListener.onMouseMove = function():Void {
// Values for TextField.thickness can range from -200 to +200.
lorem_txt.thickness = Math.round(_xmouse * (400 / Stage.width) - 200);
thickness_txt.text = "TextField.thickness = " + lorem_txt.thickness;
};
Mouse.addListener(mouseListener);
The first block of code creates two text fields, thickness_txt and lorem_txt, and
positions them on the Stage. The lorem_txt text field sets its embedFonts property to
true and populates the text field with a block of text.
The second block of code defines a text format with the font face Times New Roman, sets
the font size to 30 pixels, and applies the text format to the lorem_txt text field.
When you open existing FLA files in Flash 8 and later, your text is not automatically
updated to the Anti-Alias for Readability option; you must select individual text fields and
manually change the anti-aliasing settings to take advantage of the advanced anti-
aliasing technology.
When text is animated, the player turns off advanced anti-alias to improve the
appearance of your text while it’s moving. After the animation is complete, anti-alias
is turned back on.
Adobe does not recommend advanced anti-aliasing for fonts larger than 48 points.
normal_mc.onRelease = function() {
my_txt.antiAliasType = "normal";
};
advanced_mc.onRelease = function() {
my_txt.antiAliasType = "advanced";
};
Advanced anti-aliasing allows font faces to be rendered at high quality at small sizes.
It is best used with applications that have a lot of small text. Adobe does not
recommend advanced anti-aliasing for fonts larger than 48 points.
For information on formatting anti-alias text, see “Using a grid fit type” on page 378 and
“About formatting anti-alias text” on page 376.
For a sample source file, aliasing.fla, that shows how to apply and manipulate anti-aliasing text
in an application, see the Flash Sample page at www.adobe.com/go/learn_fl_samples.
Download and decompress the Samples zip file and navigate to the ActionScript2.0/Advanced
Anti-Aliasing folder to access this sample. You use the advanced anti-aliasing technology to
create small text that’s highly legible. This sample also demonstrates how text fields can scroll
quickly and smoothly when you use the cacheAsBitmap property.
The outside cutoff should always be less than or equal to the inside cutoff.
Flash Player includes advanced anti-aliasing settings for ten basic fonts; and for these fonts,
advanced anti-aliasing settings are provided only for the font sizes from 6 to 20. For these
fonts, all sizes below 6 use the settings for 6, and all sizes above 20 use the settings for 20.
Other fonts map to the supplied font data. The setAdvancedAntialiasingTable() method
lets you set custom anti-aliasing data for other fonts and font sizes, or to override the default
settings for the provided fonts. For more information on creating an anti-aliasing table, see
the following example:
This ActionScript code can be separated into five key sections. The first section of code
defines a new TextFormat instance that will be applied to a dynamically created text field.
The next two sections create two new text fields on the Stage. The first text field,
lorem_txt, applies the custom text formatting object created earlier, enables embedded
fonts, and sets the antiAliasType property to true. The second text field,
debug_txt,displays the current sharpness and thickness values for the lorem_txt text
field. The fourth section of code creates a LoadVars object, which is responsible for
loading the external text file and populating the lorem_txt text field. The fifth, and final,
section of code defines a mouse listener that is called whenever the mouse pointer moves
on the Stage. The current values for sharpness and thickness are calculated based on
the current position of the mouse pointer on the Stage. The sharpness and thickness
properties are set for the lorem_txt text field, and the current values are displayed in the
debug_txt text field.
8. Select Control > Test Movie to test the document.
Move the mouse pointer along the x axis to change the text field’s sharpness. Move the
mouse pointer from left to right to cause the sharpness to increase and appear more
jagged. Move the mouse pointer along the y axis to cause the text field’s thickness to
change.
For more information on using anti-alias text in a SWF file, see “Setting anti-alias with
ActionScript” on page 370, “Font rendering options in Flash” on page 369, and “Using a grid
fit type” on page 378.
For a sample source file, aliasing.fla, that shows how to apply and manipulate anti-aliasing text
in an application, see the Flash Sample page at www.adobe.com/go/learn_fl_samples.
Download and decompress the Samples zip file and navigate to the ActionScript 2.0/
Advanced Anti-Aliasing folder to access the sample. You use the advanced anti-aliasing
technology to create small text that’s highly legible. This sample also demonstrates how text
fields can scroll quickly and smoothly when you use the cacheAsBitmap property.
The setTextFormat() method changes the text format that is applied to individual
characters, to groups of characters, or to the entire body of text in a text field. Newly inserted
text, however—such as text entered by a user or inserted with ActionScript—does not assume
the formatting specified by a setTextFormat() call. To specify the default formatting for
newly inserted text, use TextField.setNewTextFormat(). For more information, see
setTextFormat (TextField.setTextFormat method) and setNewTextFormat
(TextField.setNewTextFormat method) in the ActionScript 2.0 Language Reference.
5. Apply the TextFormat object to the text field you created in step 1 by using
TextField.setTextFormat():
myText_txt.setTextFormat(txt_fmt);
This version of setTextFormat() applies the specified formatting to the entire text field.
Two other versions of this method let you apply formatting to individual characters or
groups of characters. For example, the following code applies bold, italic, 24-point
formatting to the first three characters you entered in the text field:
myText_txt.setTextFormat(0, 3, txt_fmt);
For a complete list of TextFormat methods and their descriptions, see TextFormat in the
ActionScript 2.0 Language Reference.
font-size fontSize Only the numeric part of the value is used. Units
(px, pt) are not parsed; pixels and points are
equivalent.
margin-left marginLeft Only the numeric part of the value is used. Units
(px, pt) are not parsed; pixels and points are
equivalent.
margin-right marginRight Only the numeric part of the value is used. Units
(px, pt) are not parsed; pixels and points are
equivalent.
letter-spacing letterSpacing Only the numeric part of the value is used. Units
(px, pt) are not parsed; pixels and points are
equivalent.
text-indent textIndent Only the numeric part of the value is used. Units
(px, pt) are not parsed; pixels and points are
equivalent.
For an example of using styles on XML elements, see “An example of using styles with XML”
on page 394.
To add styles to a style sheet object, you can either load an external CSS file into the object or
define the styles in ActionScript. See “Loading external CSS files” on page 385 and “Creating
new styles with ActionScript” on page 387.
For a sample source file, formattedText.fla, which shows you how to apply CSS formatting to
text that you load into a SWF file at runtime, see the Flash Sample page at www.adobe.com/
go/learn_fl_samples. Download and decompress the Samples zip file and navigate to the
ActionScript2.0/LoadText folder to access the sample.
.headline {
font-family: Arial,Helvetica,sans-serif;
font-size: 24px;
}
In the previous code snippet, this.getStyleNames() refers to the styles object you
constructed in the first line of ActionScript.
8. Save the FLA file to the same directory that contains styles.css.
9. Test the Flash document (Control > Test Movie).
You should see the names of the two styles in the Output panel:
.bodyText,.headline
If you see “Error loading CSS file.” in the Output panel, make sure the FLA file and the
CSS file are in the same directory and that you typed the name of the CSS file correctly.
As with all other ActionScript methods that load data over the network, the CSS file must
reside in the same domain as the SWF file that is loading the file. (See “Restricting
networking APIs” on page 648.) For more information on using CSS with Flash, see
StyleSheet (TextField.StyleSheet) in the ActionScript 2.0 Language Reference.
When you assign a style sheet object to a TextField object, the following changes occur to the
text field’s normal behavior:
■ The text field’s text and htmlText properties, and any variable associated with the text
field, always contain the same value and behave identically.
■ The text field becomes read-only and cannot be edited by the user.
The preceding block of code creates a new TextField.StyleSheet instance that defines three
styles: for the html, body, and h1 HTML tags. Next, the style sheet object is applied to
the TextArea component and HTML formatting is enabled. The remaining ActionScript
defines a LoadVars object that loads an external HTML file and populates the text area
with the loaded text.
4. Select Control > Test Movie to test the Flash document.
Combining styles
CSS styles in Flash Player are additive; that is, when styles are nested, each level of nesting can
contribute style information, which is added together to result in the final formatting.
The following example shows some XML data assigned to a text field:
<sectionHeading>This is a section</sectionHeading>
<mainBody>This is some main body text, with one
<emphasized>emphatic</emphasized> word.</mainBody>
For the word emphatic in the above text, the emphasized style is nested within the mainBody
style. The mainBody style contributes color, font-size, and decoration rules. The emphasized
style adds a font-weight rule to these rules. The word emphatic will be formatted using a
combination of the rules specified by mainBody and emphasized.
The following table shows which built-in HTML tags can be styled and how each style
is applied:
a:link {
color: #FF0000;
}
a:hover{
text-decoration: underline;
}
.headline {
color: #000000;
font-family: Arial,Helvetica,sans-serif;
font-size: 18px;
font-weight: bold;
display: block;
}
.byline {
color: #666600;
font-style: italic;
font-weight: bold;
display: inline;
}
This style sheet defines styles for two built-in HTML tags (<p> and <a>) that will be
applied to all instances of those tags. It also defines two style classes (.headline and
.byline) that will be applied to specific paragraphs and text spans.
3. Save the file as html_styles.css.
If you copy and paste this text string, make sure that you remove any line breaks that
might have been added to the text string.
In this ActionScript, you are loading the text from an external file. For information on
loading external data, see Chapter 14, “Working with Images, Sound, and Video.”
8. Save the file as news_html.fla in the same directory that contains the CSS file you
created in step 3.
9. Select Control > Test Movie to see the styles applied to the HTML text automatically.
The following XML style sheet also creates the new styles sectionHeading, mainBody,
and emphasized:
sectionHeading {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 18px;
display: block
}
mainBody {
color: #000099;
text-decoration: underline;
font-size: 12px;
display: block
}
emphasized {
font-weight: bold;
display: inline
}
You could then populate a text field associated with that XML style sheet with the following
formatted text:
<sectionHeading>This is a section</sectionHeading>
<mainBody>This is some main body text,
with one <emphasized>emphatic</emphasized> word.
</mainBody>
This code creates a new style sheet object named styles that defines styles by using the
setStyle() method. The styles exactly match the ones you created in an external CSS file
earlier in this chapter.
If you copy and paste this text string, make sure that you remove any line breaks that
might have been added to the text string. Select Hidden Characters from the pop-up
menu in the Actions panel to see and remove any extra line breaks.
You are loading XML data from an external file in this ActionScript. For
information on loading external data, see Chapter 14, “Working with Images,
Sound, and Video.”
If you enclose attribute values in double quotation marks, you must escape the quotation
marks (\"). Either of the following ways of doing this is acceptable:
myField_txt.htmlText = "<p align='left'>This uses single quotes</p>";
myField_txt.htmlText = "<p align=\"left\">This uses escaped double quotes</
p>";
myField_txt.htmlText = '<p align="left">This uses outer single quotes</p>';
myField_txt.htmlText = '<p align=\'left\'>This uses escaped single quotes</
p>';
It’s not necessary to escape double quotation marks if you’re loading text from an external file;
it’s necessary only if you’re assigning a string of text in ActionScript.
You can use the special asfunction protocol to cause the link to execute an ActionScript
function in a SWF file instead of opening a URL. For more information on the asfunction
protocol, see asfunction protocol in the ActionScript 2.0 Language Reference.
You can also define a:link, a:hover, and a:active styles for anchor tags by using style
sheets. See “Styling built-in HTML tags” on page 390.
NOT E
Absolute URLs must be prefixed with http://; otherwise, Flash treats them as relative
URLs.
Bold tag
The <b> tag renders text as bold, as shown in the following example:
text3_txt.htmlText = "He was <b>ready</b> to leave!";
A bold typeface must be available for the font used to display the text.
Break tag
The <br> tag creates a line break in the text field. You must set the text field to be a multiline
text field to use this tag.
In the following example, the line breaks between sentences:
this.createTextField("text1_txt", 1, 10, 10, 200, 100);
text1_txt.html = true;
text1_txt.multiline = true;
text1_txt.htmlText = "The boy put on his coat.<br />His coat was <font
color='#FF0033'>red</font> plaid.";
■ face Specifies the name of the font to use. As shown in the following example, you can
specify a list of comma-delimited font names, in which case Flash Player selects the first
available font:
myText_txt.htmlText = "<font face='Times, Times New Roman'>Displays as
either Times or Times New Roman...</font>";
If the specified font is not installed on the user’s computer system or isn’t embedded in the
SWF file, Flash Player selects a substitute font.
For more information on embedding fonts in Flash applications, see embedFonts
(TextField.embedFonts property) in the ActionScript 2.0 Language Reference and “Setting
dynamic and input text options” in Using Flash.
■ size Specifies the size of the font, in pixels, as shown in the following example:
myText_txt.htmlText = "<font size='24' color='#0000FF'>This is blue, 24-
point text</font>";
You can also use relative point sizes instead of a pixel size, such as +2 or -4.
Image tag
The <img> tag lets you embed external image files (JPEG, GIF, PNG), SWF files, and movie
clips inside text fields and TextArea component instances. Text automatically flows around
images you embed in text fields or components. To use this tag, you must set your dynamic or
input text field to be multiline and to wrap text.
To create a multiline text field with word wrapping, do one of the following:
■ In the Flash authoring environment, select a text field on the Stage and then, in the
Property inspector, select Multiline from the Text Type menu.
■ For a text field created at runtime with createTextField (MovieClip.createTextField
method), set the new text field instance’s multiline (TextField.multiline property) and
multiline (TextField.multiline property) properties to true.
The <img> tag has one required attribute, src, which specifies the path to an image file, a
SWF file, or the linkage identifier of a movie clip symbol in the library. All other attributes
are optional.
Italic tag
The <i> tag displays the tagged text in italics, as shown in the following code:
That is very <i>interesting</i>.
Ordered and unordered lists (<ol> and <ul> tags) are not recognized by Flash Player,
so they do not modify how your list is rendered. All list items use bullets.
Paragraph tag
The <p> tag creates a new paragraph. You must set the text field to be a multiline text field to
use this tag.
The <p> tag supports the following attributes:
■ align Specifies alignment of text within the paragraph; valid values are left, right,
justify, and center.
■ class Specifies a CSS style class defined by a TextField.StyleSheet object. (For more
information, see “Using style classes” on page 389.)
The following example uses the align attribute to align text on the right side of a
text field.
this.createTextField("myText_txt", 1, 10, 10, 400, 100);
myText_txt.html = true;
myText_txt.multiline = true;
myText_txt.htmlText = "<p align='right'>This text is aligned on the
right side of the text field</p>";
The following example uses the class attribute to assign a text style class to a <p> tag:
var myStyleSheet:TextField.StyleSheet = new TextField.StyleSheet();
myStyleSheet.setStyle(".blue", {color:'#99CCFF', fontSize:18});
this.createTextField("test_txt", 10, 0, 0, 300, 100);
test_txt.html = true;
test_txt.styleSheet = myStyleSheet;
test_txt.htmlText = "<p class='blue'>This is some body-styled text.</
p>.";
AJ 34 Detective
The use of the tab character escape sequence (\t) adds tabs between each column in the
table. You append text using the += operator.
4. Select Control > Test Movie to view the formatted table.
Underline tag
The <u> tag underlines the tagged text, as shown in the following code:
This is <u>underlined</u> text.
At runtime, the previous code example in Flash displays the following text on the Stage:
The <b> tag makes text appear bold.
In addition to the greater-than and less-than symbols, Flash also recognizes other HTML
entities that are listed in the following table.
Entity Description
< < (less than)
> > (greater than)
& & (ampersand)
" " (double quotes)
' ' (apostrophe, single quote)
Flash also supports explicit character codes, such as ' (ampersand - ASCII) and
& (ampersand - Unicode).
The following ActionScript demonstrates how you can use ASCII or Unicode character codes
to embed a tilde (~) character:
this.createTextField("my_txt", 10, 100, 100, 100, 19);
my_txt.autoSize = "left";
my_txt.html = true;
my_txt.htmlText = "~"; // tilde (ASCII)
my_txt.htmlText += "\t"
my_txt.htmlText += "~"; // tilde (Unicode)
The preceding code creates a new dynamic text field on the Stage, enables HTML
formatting, and adds some text and a local image to the text field.
3. Add the following ActionScript below the code added in the previous step:
this.createTextField("image2_txt", 20, 50, 200, 400, 150);
image2_txt.html = true;
image2_txt.htmlText = "<p>Here's a picture from my garden:<img
src='http://www.helpexamples.com/flash/images/image2.jpg'>";
You can also insert an image by using an absolute address. The preceding code inserts a
JPEG file that’s located in a directory that’s on a server. The SWF file that contains this
code might be on your hard disk or on a server.
When using absolute URLs, you must make sure that your URL is prefixed with
http://.
For an embedded movie clip to be displayed properly and completely, the registration
point for its symbol should be at point (0,0).
8. Save your changes to the Flash document.
If you don’t specify values for height and width, no space is reserved for the embedded
media. After an image or SWF file has downloaded completely, Flash inserts it into the text
field at full size and rebreaks text around it.
NO TE
If you are dynamically loading your images into a text field containing text, it is good
practice to specify the width and height of the original image so the text properly wraps
around the space you reserve for your image.
In this case, the fully qualified path to the newly created movie clip is
textField_txt.animation_mc.
13. Save your changes to the Flash document and then select Control > Test Movie to preview
the animation within the text field.
To control the SWF file as it plays in a text field, complete the next exercise.
When the mouse pointer is over an image, SWF file, or movie clip that is enclosed by <a>
tags, the mouse pointer turns into a “pointing hand” icon, the same as it does with standard
hypertext links. Interactivity, such as mouse clicks and keypresses, does not register in SWF
files and movie clips that are enclosed by <a> tags.
For information on embedding media, see “About making hypertext links out of embedded
media” on page 410.
If you are not dynamically loading text into the SWF file, select Text > Scrollable
from the main menu.
2. Create an Up button and a Down button, or select Window > Common Libraries >
Buttons, and drag buttons to the Stage.
You will use these buttons to scroll the text up and down.
3. Select the Down button on the Stage and type down_btn into the Instance Name text box.
4. Select the Up button on the Stage and type up_btn into the Instance Name text box.
5. Select Frame 1 on the Timeline, and, in the Actions panel (Window > Actions), enter the
following code to scroll the text down in the text field:
down_btn.onPress = function() {
textField_txt.scroll += 1;
};
6. Following the ActionScript in step 5, enter the following code to scroll the text up:
up_btn.onPress = function() {
textField_txt.scroll -= 1;
};
Any text that loads into the textField_txt text field can be scrolled using the up and
down buttons.
panel
The Strings panel lets you create and update multilingual content. You can specify content for
text fields that span multiple languages, and have Flash automatically determine the content
that should appear in a certain language based on the language of the computer that is
running Flash Player.
For general information on the Strings panel, and how to use it in your applications, see the
following topics in Using Flash:
■ “Authoring multilanguage text”
■ “About the Strings panel”
■ “Translating text in the Strings panel or an XML file”
■ “Importing an XML file into the Strings panel”
You can use the Locale class to control how multilanguage text is displayed. For more
information, see “Using the Locale class” on page 414 and Locale (mx.lang.Locale) in
the ActionScript 2.0 Language Reference.
Manually using stage language String IDs are replaced by strings when the SWF file
compiles, and cannot be changed by Flash Player.
Using ActionScript at runtime You can control string ID replacement by using
ActionScript, which is controlled at runtime. This option gives you control over both the
timing and the language of string ID replacement.
You can use the properties and methods of the Locale class when you want to replace the
string IDs by using ActionScript to control the application when it plays in Flash Player. For a
demonstration of how to use the Locale class, see the following procedure.
function langListener(eventObj:Object):Void {
Locale.loadLanguageXML(eventObj.target.value);
}
function localeListener(success:Boolean):Void {
if (success) {
greeting_txt.text = Locale.loadString("IDS_GREETING");
} else {
greeting_txt.text = "unable to load language XML file.";
}
}
The preceding ActionScript is split into two sections. The first section of code imports the
Locale class and specifies a callback listener that is called whenever a language XML file is
finished loading. Next, the lang_cb combo box is populated with a sorted array of
available languages. Whenever the lang_cb value changes, Flash’s event dispatcher triggers
the langListener() function, which loads the specified-language XML file. The second
section of code defines two functions, langListener(), and localeListener(). The
first function, langListener(), is called whenever the lang_cb combo box’s value is
changed by the user. The second function, localeListener(), is called whenever a
language XML file is finished loading. The function checks if the load was successful, and
if so, sets the text property of the greeting_txt instance to the greeting for the
selected language.
11. Select Control > Test Movie to test the Flash document.
TIP
The XML file that you use must use the XML Localization Interchange File Format
(XLIFF).
C A UTI ON
The Locale class is different from the other classes in the ActionScript 2.0 Language
Reference, since it is not part of the Flash Player. Because this class installed in the
Flash Authoring classpath, it is automatically compiled into your SWF files. Using the
Locale class increases the SWF file size slightly, because the class must be
compiled into the SWF file.
Curently, you cannot tell which IME is active (if any), or change from one IME to another
(for instance, English to Japanese or Korean to Chinese)
You can also disable or enable the IME by using your application at runtime, and perform
other functions, depending on the user’s operating system. You can check whether a system
has an IME by using the System.capabilities.hasIME property. The next example shows
how to determine whether the user has an IME installed and active.
The preceding code first checks whether the current system has an IME installed. If an
IME is installed, Flash checks whether it is currently enabled.
enable_btn.onRelease = function() {
System.IME.setEnabled(true);
};
disable_btn.onRelease = function() {
System.IME.setEnabled(false);
};
function checkIME():Boolean {
if (System.capabilities.hasIME) {
if (System.IME.getEnabled()) {
trace("You have an IME installed and enabled.");
return true;
} else {
trace("You have an IME installed but not enabled.");
The preceding code is separated into five sections. The first section calls the checkIME()
method, which displays a message in the Output panel if the system has an IME installed
or active. The second section defines a custom text-format object, which sets the font to
_sans. The third section creates an input text field and applies the custom text format.
The fourth section creates some event handlers for the enable_btn and disable_btn
instances created in an earlier step. The fifth, and final, section of code defines the custom
checkIME() function, which checks whether the current system has an IME installed and
if so, whether or not the IME is active.
4. Save the FLA file and select Control > Test Movie to test the document.
NO TE
This example requires that you have an IME installed on your system. For information
on installing an IME, see the links that precede this example.
Type some text into the input text field on the Stage. Switch your IME to a different
language and type in the input text field again. Flash Player inputs characters by using the
new IME. If you click the disable_btn button on the Stage, Flash reverts to using the
previous language and ignores the current IME settings.
For information on System.capabilities.hasIME, see hasIME (capabilities.hasIME
property) in the ActionScript 2.0 Language Reference.
For a sample source file, strings.fla, that shows you how to build a simple word processor that
compares and retrieves string and substring selections, see the Flash Sample page at
www.adobe.com/go/learn_fl_samples. Download and decompress the Samples zip file and
navigate to the ActionScript2.0/Strings folder to access the sample.
Creating strings
You can call any of the methods of the String class by using the new String() constructor
method or by using a string literal value. If you specify a string literal, the ActionScript
interpreter automatically converts it to a temporary String object, calls the method, and
discards the temporary String object. You can also use the String.length property with a
string literal.
Do not confuse a string literal with a String object. For more information on string literals and
the String object, see Chapter 4, “About literals,” on page 94.
In the following example, the line of code creates the firstStr string literal. To declare a
string literal, use single straight quotation mark (') or double straight quotation mark (")
delimiters.
This code defines three String objects, one that uses a string literal, one that uses the new
operator, and the other without an initial value. Strings can be compared by using the
equality (==) operator, as shown in the third line of code. When referring to variables, you
specify the data type only when the variable is being defined.
For more information on using the backslash character in strings, see “About the escape
character” on page 420.
Remember that you cannot use “curly quotation mark” or “special quotation mark” characters
within your ActionScript code; they are different from the straight quotation marks (') and
(") that you can use in your code. When you paste text from another source into
ActionScript, such as the web or a Word document, be sure to use straight quote delimiters.
For a sample source file, strings.fla, that shows you how to build a simple word processor that
compares and retrieves string and substring selections, see the Flash Samples page at
www.adobe.com/go/learn_fl_samples. Download and decompress the Samples zip file and
navigate to the ActionScript2.0/Strings folder to access the sample.
For more information on string literals, see Chapter 4, “About literals,” on page 94 and
“Creating strings” on page 419.
If your string contains a null byte character (\0), the string value will be truncated.
You can also use character codes to define a string. For more information on character codes
and character encoding, see “About strings and the String class” on page 411.
The following example creates a variable named myStr and sets the string’s value based on
ASCII values passed to the String.fromCharCode() method:
var myStr:String =
String.fromCharCode(104,101,108,108,111,32,119,111,114,108,100,33);
trace(myStr); // hello world!
Each number listed in the fromCharCode() method in the previous code represents a single
character. For example, the ASCII value 104 represents a lowercase h, and the ASCII value 32
represents the space character.
You can examine the characters in various positions in a string, as in the following example.
3. Select Control > Test Movie to preview your Flash document. You should see each
character traced to the Output panel on a separate line.
4. Modify the existing ActionScript code so that it traces the ASCII value for each character:
var myStr:String = "hello world!";
for (var i:Number = 0; i < myStr.length; i++) {
trace(myStr.charAt(i) + " - ASCII=" + myStr.charCodeAt(i));
}
5. Save the current Flash document and select Control > Test Movie to preview the SWF file.
When you run this code, the following is displayed in the Output panel:
h - ASCII=104
e - ASCII=101
l - ASCII=108
l - ASCII=108
o - ASCII=111
- ASCII=32
w - ASCII=119
o - ASCII=111
r - ASCII=114
l - ASCII=108
d - ASCII=100
! - ASCII=33
TIP
You can also split a string into an array of characters by using the String.split()
method and entering an empty string ("") as a delimiter; for example, var
charArray:Array = myStr.split("");
3. Save the Flash document and select Control > Test Movie to test the SWF file.
When comparing two different data types (such as strings and numbers), Flash tries to
convert the data types so that a comparison can be made.
Use the strict equality (===) and strict inequality (!==) operators to verify that both
comparison objects are of the same type. The following example uses strict comparison
operators to ensure that Flash doesn’t try to convert data types while trying to compare values.
3. Save the Flash document and select Control > Test Movie.
For more information on using operators with strings, see “About using operators with
strings” on page 143.
For a sample source file, strings.fla, that shows you how to build a simple word processor that
compares and retrieves string and substring selections, see the Flash Samples page at
www.adobe.com/go/learn_fl_samples. Download and decompress the Samples zip file and
navigate to the ActionScript2.0/Strings folder to access the sample.
When you use the addition (+) operator with a combination of string and nonstring instances,
you don’t need to use the toString() method. For details on concatenation, see the second
procedure in this section.
The toLowerCase() method and the toUpperCase() method convert alphabetical characters
in the string to lowercase and uppercase, respectively. The following example demonstrates
how to convert a string from lowercase to uppercase characters.
3. Save the Flash document and select Control > Test Movie.
NOT E
After these methods are executed, the source string remains unchanged. To
transform the source string, use the following:
myStr = myStr.toUpperCase();
The preceding code shows two methods of concatenating strings. The first method uses
the addition (+) operator to join the str1 string with the string "ish". The second
method uses the addition and assignment (+=) operator to concatenate the string "ish"
with the current value of str3.
3. Save the Flash document and select Control > Test Movie.
You can also use the concat() method of the String class to concatenate strings. This method
is demonstrated in the following example.
You can use the split() method to create an array of substrings of a string, which is divided
based on a delimiter character. For example, you could segment a comma- or tab-delimited
string into multiple strings.
For example, the following code shows how you can split an array into substrings by using the
ampersand (&) character as a delimiter.
The second parameter of the split() method defines the maximum size of the array.
If you don’t want to limit the size of the array created by the split() method, you can
omit the second parameter.
TIP
The easiest way to parse a query string (a string delimited with & and = characters) is
to use the LoadVars.decode() method, as shown in the following ActionScript:
For more information on using operators with strings, see “About using operators with
strings” on page 143.
For a sample source file, strings.fla, that shows you how to build a simple word processor that
compares and retrieves string and substring selections, see the Flash Samples page at
www.adobe.com/go/learn_fl_samples. Download and decompress the Samples zip file and
navigate to the ActionScript2.0/Strings folder to access the sample.
The first method, substr(), returns a string 15 characters long starting from the eleventh
character. The second method, substring(), returns a string four characters long by
grabbing all characters between the eleventh and fifteenth index.
3. Add the following ActionScript below the code added in the preceding step:
trace(myStr.slice(11, 15)); // Pari
trace(myStr.slice(-3, -1)); // !!
trace(myStr.slice(-3, 26)); // !!!
trace(myStr.slice(-3, myStr.length)); // !!!
trace(myStr.slice(-8, -3)); // Texas
The slice() method functions similarly to the substring() method. When given two
non-negative integers as parameters, it works exactly the same. However, the slice()
method can take negative integers as parameters.
4. Select Control > Test Movie to test the Flash document.
NOT E
You can combine non-negative and negative integers as the parameters of the
slice() method.
You can use the indexOf() and lastIndexOf() methods to locate matching substrings
within a string, as shown in the following example.
The first index of the word the begins at the 10th character because the indexOf()
method is case sensitive; therefore the first instance of The isn’t considered. You can also
specify a second parameter to the indexOf() method to indicate the index position in the
string from which to start the search. In the preceding code, Flash searches for the first
index of the word the that occurs after the 11th character.
3. Add the following ActionScript below the code that you added in the previous step:
trace(myStr.lastIndexOf("the")); // 30
trace(myStr.lastIndexOf("the", 29)); // 21
The lastIndexOf() method finds the last occurrence of a substring in the string. For
example, instead searching for a character or substring from the beginning of a string,
lastIndexOf() starts from the end of a string and works backward. Similarly to the
indexOf() method, if you include a second parameter with the lastIndexOf() method,
the search is conducted from that index position, although with lastIndexOf() the
string is searched backward (from right to left).
4. Select Control > Test Movie to test your Flash document.
TI P
For a sample source file, strings.fla, that shows you how to build a simple word processor that
compares and retrieves string and substring selections, see the Flash Samples page at
www.adobe.com/go/learn_fl_samples. Download and decompress the Sample zip file and
navigate to the ActionScript2.0/Strings folder to access the sample.
Animation, Filters,
and Drawings
12
This chapter describes how to add animation to your Flash CS3 Professional applications
using ActionScript instead of (or in addition to) timeline-based animations that use motion or
shape tweens. Using code to create animation and effects often reduces the file size of your
finished application, and can also improve the performance and consistency of the animation
itself. At times, ActionScript-based animations might even reduce your workload: code can be
faster to write, and it’s easy to apply to many instances at once or reuse in other applications.
This chapter also shows you how to animate by using fundamental ActionScript basics, the
Tween and TransitionManager classes, the Drawing API, filter classes, and blend modes.
You can use the Drawing API, which consists of the drawing methods in the MovieClip class,
to add animation and draw. These methods let you use code to create lines, fills, and shapes,
instead of using the drawing tools in the authoring tool.
Filters and other expressive effects are also important in many Flash applications, to quickly
apply an effect and animate it. You can use code to add and animate filter effects, blend
modes, and bitmap images.
This chapter contains the following sections, which describe using ActionScript to create
animation and add effects, as well as using the Drawing API to draw in ActionScript:
Scripting animation with ActionScript 2.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 430
About bitmap caching, scrolling, and performance . . . . . . . . . . . . . . . . . . . . . . . . . 440
About the Tween and TransitionManager classes . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
Using filter effects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .456
Working with filters using ActionScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .463
Manipulating filter effects with code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489
Creating bitmaps with the BitmapData class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
About blending modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496
About operation order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498
Drawing with ActionScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499
Understanding scaling and slice guides . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514
429
Scripting animation with ActionScript 2.0
You can use ActionScript 2.0 to add animation to your Flash applications, instead of using
motion or shape tweens on a timeline.The following sections show you how to use code to
animate instances, such as changing the transparency and appearance of the instance, and
moving the instance around the Stage.
For information on using the Tween and TransitionManager classes to further automate code-
based animations, see ActionScript 2.0 Components Language Reference. These classes help you
add advanced easing equations and transition animations to movie clip instances in your
application. Many of these effects are difficult to recreate using ActionScript without these
prebuilt classes, because the code you need to use involves writing complex mathematical
equations to achieve the effect.
For more information about how to animate drawings that you create with code, see
“Drawing with ActionScript” on page 499.
The following sections describe how to script animations:
■ “About animation and frame rate” on page 431
■ “Fading objects with code” on page 432
■ “Adding color and brightness effects with code” on page 434
■ “Moving objects with code” on page 437
■ “Panning an image with code” on page 438
For a source sample of scripted animation in Flash, animation.fla, see the Flash Samples page
at www.adobe.com/go/learn_fl_samples. Download and decompress the Samples zip file and
navigate to the ActionScript2.0/Animation folder to access the sample.
For samples of photo gallery applications, see the Flash Samples page at www.adobe.com/go/
learn_fl_samples. Download the Samples zip file and navigate to the ActionScript2.0/
Galleries folder to access these samples:
■ gallery_tree.fla
■ gallery_tween.fla
These files provide examples of how to use ActionScript to control movie clips dynamically
while loading image files into a SWF file, which includes scripted animation.
When you use an onEnterFrame event handler to create scripted animations, the
animation runs at the document’s frame rate, similar to if you created a motion tween on
a timeline. An alternative to the onEnterFrame event handler is setInterval (see
setInterval function in the ActionScript 2.0 Language Reference). Instead of depending
on frame rate, you call functions at a specified interval. Like onEnterFrame, the more
frequently you use setInterval to call a function, the more resource intensive the
animation is on your processor.
Use the lowest possible frame rate that makes your animation appear to play smoothly at
runtime, which helps reduce the strain on the end-user’s processor. Try not to use a frame rate
that’s more than 30 to 40 fps; high frame rates put a lot of stress on processors, and do not
change the appearance of the animation much or at all at runtime.
Also, especially if you’re working with timeline-based animation, select a frame rate for your
animation as early as possible in the development process. When you test the SWF file, check
the duration, and the SWF file size, of your animation. The frame rate greatly affects the
speed of the animation.
This code uses an onEnterFrame event handler, which is invoked repeatedly at the frame
rate of the SWF file. The number of times per second that the event handler is called
depends on the frame rate at which the Flash document is set. If the frame rate is
12 frames per second (fps), the onEnterFrame event handler is invoked 12 times per
second. Likewise, if the Flash document’s frame rate is 30 fps, the event handler is invoked
30 times per second.
7. Select Control > Test Movie to test the document.
The movie clip you added to the Stage slowly fades out.
You can modify the _alpha property by using the setInterval() function instead of an
onEnterFrame event handler, as the next procedure shows.
The setInterval() function behaves slightly differently than the onEnterFrame event
handler, because the setInterval() function tells Flash precisely how frequently the
code should call a particular function. In this code example, the user-defined
fadeImage() function is called every 50 milliseconds (20 times per second). The
fadeImage() function decrements the value of the current movie clip’s _alpha property.
When the _alpha value is equal to or less than 0, the interval is cleared, which causes the
fadeImage() function to stop executing.
7. Select Control > Test Movie to test the document.
The movie clip you added to the Stage slowly fades out.
For more information on user-defined functions, see “Defining global and timeline functions”
on page 173. For more information on the onEnterFrame event handler, see onEnterFrame
(MovieClip.onEnterFrame handler) in the ActionScript 2.0 Language Reference. For more
information on the setInterval() function, see setInterval global function in the
ActionScript 2.0 Language Reference.
For a source sample of scripted animation in Flash, animation.fla, see the Flash Samples page
at www.adobe.com/go/learn_fl_samples. Download and decompress the Samples zip file and
navigate to the ActionScript2.0/Animation folder to access the sample.
3. Select Control > Test Movie to test the document, and then move the mouse pointer
around the Stage.
The image file that loads transforms colors as you move the mouse.
You can also use the ColorMatrixFilter class to convert a color image to a black and white
image, as the following procedure shows.
The preceding code begins by importing the ColorMatrixFilter class, and creates a listener
object that will be used with a new MovieClipLoader instance created in some later code.
Next, a new movie clip instance is created with the instance name img_mc, as well as a new
movie clip loader instance with the instance name img_mcl. Finally, the source movie clip
is loaded into the img_mc movie clip on the Stage. When the image is successfully loaded,
the onLoadInit event handler is called and attaches a ColorMatrixFilter to the loaded
image.
3. Select Control > Test Movie to test the document.
The image that you load onto the Stage changes to a grayscale image. View the image
online (http://www.helpexamples.com/flash/images/image1.jpg) to see the
original color of the image.
You can also set an image’s brightness by using the ActionScript code in the following
procedure.
This block of code uses the MovieClipLoader class to load an external JPEG. When the
image successfully loads, the MovieClipLoader class onLoadInit event handler is called
and modifies the image brightness to 100 using the ColorMatrixFilter filter.
3. Select Control > Test Movie to test the document.
The image that you load into the SWF file changes its brightness when you test the SWF
file. View the image online (http://www.helpexamples.com/flash/images/
image2.jpg) to see the original appearance of the image.
For a source sample of scripted animation in Flash, animation.fla, see the Flash Samples page
at www.adobe.com/go/learn_fl_samples. Download the Samples zip file and navigate to the
ActionScript2.0/Animation folder to access the sample.
For samples of photo gallery applications, see the Flash Samples page at www.adobe.com/go/
learn_fl_samples. Download the Samples zip file and navigate to the ActionScript2.0/
Galleries folder to access these samples:
■ gallery_tree.fla
■ gallery_tween.fla
These files provide examples of how to use ActionScript to control movie clips dynamically
while loading image files into a SWF file, which includes scripted animation.
This code example loads an external image from a remote web server and, when the image
is fully loaded, animates it horizontally across the Stage. Instead of using an
onEnterFrame event handler, you could use the setInterval() function to animate the
image.
4. Select Control > Test Movie to test the document.
The image loads and then animates from the right side of the Stage to the upper-left
corner of the Stage.
For information on using an onEnterFrame event handler or setInterval() function to
animate the image, see “Fading objects with code” on page 432.
The first section of code in this code example defines two variables: direction and
speed. The direction variable controls whether the masked image scrolls from left to
right (1) or right to left (-1). The speed variable controls how many pixels are moved each
time the onEnterFrame event handler is called. Larger numbers cause the animation to
move more quickly, although the animation appears a bit less smooth.
The next section of code creates two empty movie clips: img_mc and mask_mc. A 300 pixel
by 100 pixel rectangle is drawn inside the mark_mc movie clip using the Drawing API.
Next, a new object (mcl_obj) is created, which you use as a listener for a
MovieClipLoader instance created in the final block of code. This object defines an event
listener for the onLoadInit event, masks the dynamically loaded image, and sets up the
scrolling animation. After the image reaches the left or right edge of the mask, the
animation reverses.
The final block of code defines a MovieClipLoader instance, specifies the listener object
you created earlier, and begins loading the JPEG image into the img_mc movie clip.
4. Select Control > Test Movie to test the document.
The bitmap is copied to the main Stage as unstretched, unrotated pixels snapped to the
nearest pixel boundaries. Pixels are mapped one-to-one with the parent object. If the
bounds of the bitmap change, the bitmap is re-created instead of being stretched.
For detailed information on caching button or movie clip instances see the following sections
in Chapter 10, “Working with Movie Clips”:
■ “About caching and scrolling movie clips with ActionScript” on page 330
■ “Caching a movie clip” on page 334
■ “Setting the background of a movie clip” on page 336
It’s ideal to use the cacheAsBitmap property with movie clips that have mostly static content
and that do not scale and rotate frequently. With such movie clips, using the cacheAsBitmap
property can lead to performance improvements when the movie clip is translated (when its x
and y position is changed). For detailed information about when to use this feature, see
“When to enable caching” on page 332.
For samples of how bitmap caching can be applied to an instance and how to apply bitmap
caching to scrolling text, see the Flash Samples page at www.adobe.com/go/learn_fl_samples.
The following samples are available:
■ cacheBitmap.fla; Download the Samples zip file and navigate to the ActionScript2.0/
CacheBitmap folder.
■ aliasing.fla; Download the Samples zip file and navigate to the ActionScript2.0/Advanced
Anti-Aliasing folder.
The Tween and TransitionManager classes are available only in ActionScript 2.0, but
these classes are available in Flash.
For information on each method and property of the Tween class, see ActionScript 2.0
Components Language Reference. For information on each method and property of the
TransitionManager class, see ActionScript 2.0 Components Language Reference. For information
on working with packages, see “Working with filter packages” on page 458.
For a sample source file that uses the Tween and TransitionManager classes, tweenProgress.fla,
see the Flash Samples page at www.adobe.com/go/learn_fl_samples. Download and
decompress the Samples zip file and navigate to the ActionScript2.0/Tween ProgressBar folder
to access the sample.
For more information on the Tween and TransitionManager classes, see the following topics:
■ “Adding tweens and transitions to a file in Flash” on page 442
■ “Animating with the TransitionManager and Tween classes” on page 444
■ “About easing classes and methods” on page 447
■ “About the Tween class” on page 448
This section describes adding tweens and transitions to a Flash slide presentation to
demonstrate what they look like for Flash users. However, you can add transitions and
tweens to your Flash applications if you use code. The following sections include
examples that show you how.
The Tween and TransitionManager classes are designed to let you use simple ActionScript to
add animations to parts of your SWF file. The Flash authoring environment contains
behaviors that let you use these prebuilt classes for transitions in a screen-based application.
To create a slide presentation or form application, you can select behaviors that add different
kinds of transitions between slides.
Before you start to use these transitions with movie clips in Flash, you should see what they do
when you use a screen-based application.
Transition Description
Iris Reveals the screen or movie clip by using an animated mask of a shape
that zooms in.
Wipe Reveals the screen or movie clip by using an animated mask of a shape
that moves horizontally.
Pixel Dissolve Masks the screen or movie clip by using disappearing or appearing
rectangles.
Photo Has the screen or movie clip appear like a photographic flash.
Each transition has slightly different customizations that you can apply to the animation. The
Transitions dialog box lets you preview a sample animation before you apply the effect to the
slide or form.
TI P
To preview how each transition works with the different methods in the easing classes,
you can double-click Transition.swf in boot drive\Program Files\Adobe\Adobe Flash
CS3\language\First Run\Behaviors\ folder or Macintosh HD:Applications:Adobe Flash
CS3:First Run:Behaviors: to open the SWF file in the stand-alone player.
For information on working with packages, see “Working with filter packages”
on page 458.
6. Select the new movie clip on the Stage and use the Property inspector to give it an instance
name of img2_mc.
7. Select Frame 1 of the main Timeline and add the following ActionScript to the
existing code:
mx.transitions.TransitionManager.start(img2_mc,
{type:mx.transitions.Zoom, direction:mx.transitions.Transition.IN,
duration:1, easing:mx.transitions.easing.Bounce.easeOut});
Some transitions are sensitive to where you locate the registration point. Changing
the registration point can have a dramatic effect on how the animation looks in a
SWF file. For example, if the registration point is in the upper-left corner (default)
when you use the Zoom transition, the transition begins from that location.
For information on each method and property of the Tween class and TransitionManager
class, see ActionScript 2.0 Components Language Reference.
For a sample source file that adds scripted animation using the Tween and TransitionManager
classes, tweenProgress.fla, see the Flash Samples page at www.adobe.com/go/learn_fl_samples.
Download the Samples zip file and navigate to the ActionScript2.0/Tween ProgressBar folder
to access this sample.
Transition Description
Back Extends the animation beyond the transition range at one or both ends
once to resemble an overflow effect.
Bounce Adds a bouncing effect within the transition range at one or both ends.
The number of bounces relates to the duration—longer durations
produce more bounces.
Elastic Adds an elastic effect that falls outside the transition range at one or
both ends. The amount of elasticity is unaffected by the duration.
Regular Adds slower movement at one or both ends. This feature lets you add a
speeding up effect, a slowing down effect, or both.
Strong Adds slower movement at one or both ends. This effect is similar to
Regular easing, but it’s more pronounced.
None Adds an equal movement from start to end without effects, slowing
down, or speeding up. This transition is also called a linear transition.
These six easing classes each have three easing methods, which are described in the following
table:
Method Description
easeIn Provides the easing effect at the beginning of the transition.
easeOut Provides the easing effect at the end of the transition.
easeInOut Provides the easing effect at the beginning and end of the transition.
To open these classes in Flash or your ActionScript editor, browse to Hard Disk\Program
Files\Adobe\Adobe Flash CS3\language\First Run\Classes\mx\transitions\easing\ folder on
Windows (assumes a default installation), or Macintosh HD:Applications:Adobe Flash
CS3:First Run:Classes:mx:transitions:easing.
The procedure on zooming images under “Animating with the TransitionManager and
Tween classes” on page 444 used the mx.transitions.easing.Bounce.easeOut easing class and
method. In the folder on your hard disk, the ActionScript refers to the easeOut() method
within the Bounce.as class. This ActionScript file is in the easing folder.
To preview how each transition works with the different methods in the easing classes,
you can double-click Transition.swf in boot drive\Program Files\Adobe\Adobe Flash
CS3\language\First Run\Behaviors\ or Macintosh HD:Applications:Adobe Flash
CS3:First Run:Behaviors: to open the SWF file in the stand-alone player.
For a sample source file that adds scripted animation using the Tween and TransitionManager
classes, tweenProgress.fla, see the Flash Samples page at www.adobe.com/go/learn_fl_samples.
Download the Samples zip file and navigate to the ActionScript2.0/Tween ProgressBar folder
to access this sample.
obj The movie clip object that the Tween instance targets.
prop A string name of a property in obj to which the values are to be tweened.
func The easing method that calculates an easing effect for the tweened object’s
property values.
begin A number that indicates the starting value of prop (the target object property to
be tweened).
finish A number that indicates the ending value of prop (the target object property to
be tweened).
duration A number that indicates the length of time of the tween motion. If omitted, the
duration is set to infinity by default.
useSeconds A Boolean value related to the value you specify in the duration parameter,
which indicates to use seconds if true, or frames if false.
This ActionScript snippet creates a new instance of the Tween class, which animates the
ball_mc movie clip on the Stage along the x-axis (left to right). The movie clip animates from
0 pixels to 300 pixels in three seconds, and the ActionScript applies an elastic easing method.
This means that the ball extends past 300 pixels on the x-axis before using a fluid motion
effect to animating back.
For a sample source file that adds scripted animation using the Tween and TransitionManager
classes, tweenProgress.fla, see the Flash Samples page at www.adobe.com/go/learn_fl_samples.
Download the Samples zip file and navigate to the ActionScript2.0/Tween ProgressBar folder
to access this sample.
For information on working with packages, see “Working with filter packages”
on page 458.
Instead of moving around the Stage, now ball_mc fades from 100% visible to completely
transparent in three seconds. To make the symbol fade out more quickly, change the
duration parameter from 3 to 1 or 2.
5. Select Control > Test Movie to see the animation.
If you change the document’s frame rate, the animation appears to play more smoothly.
For information on animation and frame rate, see “About animation and frame rate”
on page 431.
This code fades out the ball_mc instance using the Strong.easeIn easing method.
Instead of fading the instance for three seconds, it fades the instance across 24 frames.
5. Select Control > Test Movie to see the animation.
Wait a moment, then the instance fades out across 24 frames.
6. Return to the authoring environment and open the Property inspector.
7. Change the document’s frame rate to 24 fps.
If you increase the frame rate of your FLA file, you see the instance fade out sooner. For
information on animation and frame rate, see “About animation and frame rate”
on page 431.
Using frames instead of seconds offers more flexibility, but remember that the duration relates
to the frame rate of the current Flash document. If your Flash document uses a frame rate of
12 frames per second (fps), the previous code snippet fades the instance over two seconds
(24 frames/12 fps = 2 seconds). However, if your frame rate is 24 fps, the same code fades the
instance over one second (24 frames/24 fps = 1 second). If you use frames to measure
duration, you can significantly change the speed of your animation when you change the
document’s frame rate, without modifying your ActionScript.
The Tween class has several more useful features. For example, you can write an event handler
that triggers when the animation completes, as the next procedure shows.
If you test this ActionScript in your FLA file, you see the message “onMotionFinished
triggered” appear in the Output panel after ball_mc finishes fading on the Stage.
5. Select Control > Test Movie to see the animation.
Wait for a moment, and then the instance fades out. When it finishes tweening, you see
the message appear in the Output panel.
For more information on functions, see Chapter 6, “Classes.”
Only two arguments pass to the continueTo() method, instead of the seven arguments for
the Tween constructor method, as the following snippet shows:
function Tween (obj, prop, func, begin, finish, duration, useSeconds) {
/* omitted to save space. */
}
The five parameters that aren’t required by the continueTo() method (obj, prop, func,
begin, and useSeconds) use the arguments that you defined earlier in the call to the Tween
class. When you call the continueTo() method, you assume that the obj, prop, func (easing
type), and useSeconds arguments are the same as in the earlier call to the Tween class. The
continueTo() method uses the finish value from the call to the Tween class, instead of
specifying a value for the begin argument, as the following ActionScript shows:
import mx.transitions.Tween;
import mx.transitions.easing.*;
var ball_tween:Tween = new Tween(ball_mc, "_x", Regular.easeIn, 0, 300, 3,
true);
ball_tween.onMotionFinished = function() {
ball_tween.continueTo(0, 3);
};
This code moves the ball_mc instance along the x-axis from 0 pixels to 300 pixels in three
seconds. After the animation finishes, the onMotionFinished event handler is triggered and
calls the continueTo() method. The continueTo() method tells the target object
(ball_mc) to proceed from its current position and animate for three seconds along the x-axis
to 0 pixels and to use the same easing method. You use the values specified in the call to the
Tween constructor method for any parameters that you don’t define in the continueTo()
method. If you don’t specify a duration for the continueTo() method, it uses the duration
you specify in the call to the Tween constructor.
this.createEmptyMovieClip("box_mc", this.getNextHighestDepth());
with (box_mc) {
beginFill(0xFF0000, 60);
moveTo(0, 0);
lineTo(20, 0);
lineTo(20, Stage.height);
lineTo(0, Stage.height);
lineTo(0, 0);
endFill();
}
The first section code begins by importing the Tween class, as well as each class in the
easing package. The next section of code creates a new movie clip with an instance name
of box_mc and draws a rectangle 20 pixels wide and the same height as the Stage.
3. Add the following ActionScript after the code created in the previous step:
var box_tween:Tween = new Tween(box_mc, "_x", Regular.easeInOut, 0,
Stage.width, 3, true);
box_tween.onMotionFinished = function() {
box_tween.yoyo();
};
This code creates a new tween to animate the box_mc movie clip across the Stage along the
x-axis over 3 seconds.
4. Select Control > Test Movie to test the animation.
The box animates from left to right and back. If the animation isn’t smooth, you might
want to increase the document’s frame rate from 12 fps to 24 fps.
As the box approaches the right edge of the Stage, it animates outside the boundaries of
the Stage. While this might not seem significant, you might not want the rectangle to
disappear from view off the side of the Stage and then reappear a second later and animate
in the other direction.
To make adjustments, animate the rectangle from 0 pixels to the width of the Stage minus
the width of the box_mc movie clip.
5. To stop the rectangle from disappearing, revise the corresponding lines of code from step 3
to match the following code:
var box_tween:Tween = new Tween(box_mc, "_x", Regular.easeInOut, 0,
(Stage.width - box_mc._width), 3, true);
This code completes two different functionalities. The first section creates and positions a
movie clip instance, and draws a black rounded rectangle on the Stage. The second block
of code applies a glow filter to the rectangle on the Stage and defines an onEnterFrame
event handler, which is responsible for animating the filter effect. The onEnterFrame
event handler animates the glow filter between a blur of 10 and 30 pixels, and after the
animation is greater than or equal to 30, or less than or equal to 10, the direction of the
animation reverses.
3. Save your changes to the Flash document and select Control > Test Movie to test the
SWF file.
For more information on working with filters in an application, see the following topics:
■ “Working with filter packages” on page 458
■ “Working with filters, caching, and the MovieClip class” on page 460
To use the import statement, you must specify ActionScript 2.0 and Flash Player 6 or
later in the Flash tab of your FLA file’s Publish Settings dialog box.
The import statement lets you access classes without specifying their fully qualified names.
For example, to use a BlurFilter in a script, you must refer to it by its fully qualified name
(flash.filters.BlurFilter) or import it; if you import it, you can refer to it by its class name
(BlurFilter) in your code instead. The following ActionScript code demonstrates the
differences between using the import statement and using fully qualified class names.
If you don’t import the BlurFilter class, your code needs to use the fully qualified class name
(package name followed by class name) in order to use the filter:
// without importing
var myBlur:flash.filters.BlurFilter = new flash.filters.BlurFilter(10, 10,
3);
The same code, written with an import statement, lets you access the BlurFilter using the
class name instead of continually referencing it using the fully qualified name. This can save
typing and reduces the chance of making typing mistakes:
// with importing
import flash.filters.BlurFilter;
var myBlur:BlurFilter = new BlurFilter(10, 10, 3);
If you use individual import statements for each class within a package, it becomes time
consuming to write and prone to typing mistakes. You can avoid importing individual class
files by using a wildcard import, which imports all classes within a certain level of a package.
The following ActionScript shows an example of using a wildcard import:
import flash.filters.*; // imports each class within flash.filters package
The import statement applies only to the current script (frame or object) in which it's called.
For example, suppose on Frame 1 of a Flash document you import all the classes in the
macr.util package. On that frame, you can reference classes in the package by using their
class names instead of their fully qualified name. To use the class name on another frame
script, reference classes in that package by their fully qualified names or add an import
statement to the other frame that imports the classes in that package.
When you use import statements, remember that classes are only imported for the level that
you specify. For example, if you import all classes in the mx.transitions package, only the
classes within the /transitions/ directory are imported, not all classes within subdirectories
(such as the classes in the mx.transitions.easing package).
TI P
If you import a class but don't use it in your script, the class isn't exported as part of the
SWF file. This means that you can import large packages without being concerned
about the size of the SWF file; the bytecode associated with a class is included in a SWF
file only if that class is actually used.
For a sample of using ActionScript to apply filters, Filters.fla, see the Flash Samples page at
www.adobe.com/go/learn_fl_samples. Download the Samples zip file and navigate to the
ActionScript2.0/Filters folder to access this sample.
You can access and modify filters as you would a regular array object. Setting and getting the
filters by using the property returns a duplicate of the filters object, not a reference.
To modify an existing filter, you can use code similar to the code in the following procedure.
Currently, no support is available for having any filters perform rotation based upon
their parent’s rotation or some sort of other rotation. The blur filter always blurs
perfectly horizontally or vertically, independently of the rotation or skew of any item
in the parent object tree.
TIP
Filtered content has the same restrictions on size as content with its cacheAsBitmap
property set to true. If the author zooms in too far on the SWF file, the filters are no
longer visible when the bitmap representation is greater than 2880 pixels in either
direction. When you publish SWF files with filters, it is a good idea to disable the
zoom menu options.
For a source sample of using ActionScript to apply filters, Filters.fla, see the Flash Samples
page at www.adobe.com/go/learn_fl_samples. Download the Samples zip file and navigate to
the ActionScript2.0/Filters folder to access this sample.
You can also apply filter effects to images and video during authoring using the
Filters tab in the Property inspector.
If a 100 pixel by 100 pixel object is zoomed in once, it uses four times the memory since
the content’s dimensions are now 200 pixels by 200 pixels. If you zoom another two
times, the shape is drawn as an 800 pixel by 800 pixel object which uses 64 times the
memory as the original 100 pixel by 100 pixel object. Whenever you use filters in a SWF
file, it is always a good idea to disable the zoom menu options from the SWF file’s
context menu.
You can also encounter errors if you use invalid parameter types. Some filter parameters also
have a particular valid range. If you set a value that’s outside of the valid range, the value
changes to a valid value that’s within the range. For example, quality should be a value from
1 to 3 for a standard operation, and can only be set to 0 to 15. Anything higher than 15 is set
to 15.
Also, some constructors have restrictions on the length of arrays required as input parameters.
If a convolution filter or color matrix filter is created with an invalid array (not the right size),
the constructor fails and the filter is not created successfully. If the filter object is then used as
an entry on a movie clip’s filters array, it is ignored.
TI P
When using a blur filter, using values for blurX and blurY that are powers of 2 (such as 2,
4, 8, 16, and 32) can be computed faster and give a 20% to 30% performance
improvement.
This code uses a movie clip loader instance to load a semi-transparent PNG image. After
the image finishes loading, the image moves to the center of the Stage and a glow filter
is applied.
3. Select Control > Test Movie to test the document.
The glow filter effect is only applied to the opaque (nontransparent) area of the
PNG image.
The following sections describe how to use the filters:
■ “Using the blur filter” on page 465
■ “Using the drop shadow filter” on page 467
■ “Using the glow filter” on page 472
■ “Creating gradient glows” on page 473
■ “Using the bevel filter” on page 475
■ “Applying a gradient bevel filter” on page 482
■ “Using the color matrix filter” on page 483
■ “Using the convolution filter” on page 486
■ “Using the displacement map filter” on page 487
For a source sample of using ActionScript to apply filters, Filters.fla, see the Flash Samples
page at www.adobe.com/go/learn_fl_samples. Download the Samples zip file and navigate to
the ActionScript2.0/Filters folder to access this sample.
The blur filter scales only when you zoom into the Stage.
For more information on this filter, see BlurFilter (flash.filters.BlurFilter) in the ActionScript
2.0 Language Reference.
The following procedure blurs a dynamically loaded image based on the mouse pointer’s
current position on the Stage. The further the pointer is from the center of the Stage, the
more the image is blurred.
The first section of this code loads and positions a dynamically loaded image on the Stage.
The second section defines a listener that is called whenever the mouse moves. You
calculate the amount of horizontal and vertical blurring based on the mouse pointer’s
current position on the Stage. The further you move the pointer away from the center of
the Stage, the more blurring is applied to the instance.
When you use a blur filter, using values for blurX and blurY that are powers of two
(such as 2, 4, 8, 16, and 32) can be computed faster and give a 20% to 30%
performance improvement.
C AU TI ON
Setting a blur value lower than 1.03125 disables the blur effect.
The first section of code creates a new movie clip and uses the Drawing API to draw a red
square. The second section of code defines a mouse listener, which is called whenever the
mouse moves. The mouse listener calculates the drop shadow’s distance and level of
blurring based on the current x and y positions of the mouse pointer, and reapplies the
drop shadow filter. If you click the red square, the drop shadow’s strength increases.
You can also create drop shadows and apply them to dynamically loaded images. The
following procedure demonstrates how you can load an external image and apply a drop
shadow that follows the mouse pointer. The further the pointer moves away from the image’s
upper-left corner, the more horizontal and vertical blurring is applied to the image.
The first section of this code defines a drop shadow instance, loads an external image, and
repositions the image at the center of the Stage. The second section of code defines a
mouse listener, which you call whenever the user moves the mouse pointer around the
Stage. Whenever the mouse moves, the event handler recalculates the distance and angle
between the mouse pointer and the upper-left corner of the image. Based on this
calculation, the drop shadow filter is reapplied to the movie clip.
3. Select Control > Test Movie to test the Flash document.
When you run the SWF file, the drop shadow follows the mouse pointer. The closer you
move the mouse pointer to the upper-left corner of the image on the Stage, the less of a
blur effect is applied to the image. As the mouse pointer moves further from the upper-left
corner of the image, the drop shadow effect becomes more apparent.
This ActionScript code uses the MovieClipLoader class to load an image and apply a drop
shadow filter when the image is completely loaded from the remote server.
3. Select Control > Test Movie to test the Flash document.
Flash loads a PNG image with a transparent background. When you apply the drop
shadow filter, only the opaque (nontransparent) portion of the image has the filter
applied.
this.createEmptyMovieClip("shapeClip", 10);
with (shapeClip) {
beginFill(0xFF0000, 100);
moveTo(0, 0);
lineTo(100, 0);
lineTo(100, 100);
lineTo(0, 100);
lineTo(0, 0);
endFill();
}
shapeClip._x = 100;
shapeClip._y = 100;
shapeClip.onPress = function():Void {
glow.strength++;
shapeClip.filters = [glow];
};
var glow:GlowFilter = new GlowFilter(0xCC0000, 0.5, 10, 10, 2, 3);
var mouseListener:Object = new Object();
mouseListener.onMouseMove = function():Void {
glow.blurX = (_xmouse / Stage.width) * 255;
glow.blurY = (_ymouse / Stage.width) * 255;
shapeClip.filters = [glow];
};
Mouse.addListener(mouseListener);
The previous code is split into three sections. The first section of code uses the Drawing
API to create a square and positions the shape on the Stage. The second section of code
defines a new gradient glow filter instance, which creates a glow from red to black. The
third section of code defines a mouse listener, which listens for two mouse event handlers.
The first event handler is onMouseDown, which causes the strength of the gradient glow to
increase. The second event handler is onMouseMove, which is called whenever the mouse
pointer moves within the SWF file. The further the mouse pointer moves from the upper-
left corner of the Flash document, the stronger the glow effect that is applied.
For more information on this filter, see BevelFilter (flash.filters.BevelFilter) in the ActionScript
2.0 Language Reference.
The following procedure uses the Drawing API to create a square, and adds a bevel to
the shape.
The first section of code defines a BevelFilter instance, and uses the Drawing API to draw
a square on the Stage. When you click the square on the Stage, the current strength value
of the bevel increments and gives the bevel a taller, sharper appearance. The second
section of code defines a mouse listener, which modifies the bevel’s distance and blurring
based on the current position of the mouse pointer.
The angle value determines which edge is the highlight and which edge is the
shadow.
The angle value determines the angle at which the gradient colors are applied to the object;
meaning, where the highlight and shadow appear on the object. The colors are applied in the
same order as the array.
The following code takes a pink square (drawn with the Drawing API) and applies a rainbow
gradient filter. The colors, in the order in which they are present in the array, are: blue, green,
purple, and yellow (highlight); red (base fill); yellow, purple, green, black (shadow). To
determine the ratios values, we assign four highlight colors values from 0 to 127, making
them roughly equal, and shadow colors from 129 to 255. The colors on the outer edges, blue
(16) and black (235).
var colors:Array = [0x0000FF, 0x00FF00, 0x9900FF, 0xFFFF00, 0xFF0000,
0xFFFF00, 0x9900FF, 0x00FF00,0x000000];
var alphas:Array = [1, 1, 1, 1, 1, 1, 1, 1, 1];
var ratios:Array = [16, 32, 64, 96, 128, 160, 192, 224, 235];
var gradientBevel:GradientBevelFilter = new GradientBevelFilter(8, 225,
colors, alphas, ratios, 16, 16, 1.3, 2, "inner", false);
The dashed line shows how angles are determined. The figure shows how the angle of 225° is
realized on the filter, and also shows each ratio value for each color. Setting the angle at 225°
indicates that the first color in the array begins at 225°, which is in the top left corner (the
highlight). The dotted line shows where the highlight gradient is applied and where the
shadow gradient is applied.
The original movie clip color is pink, but setting the 128 value to red means the 128-pixel
value is the base fill and covers the original movie clip fill. However, when you set the filters
property, the original object is not altered; by simply clearing the filters property, you can
restore the original movie clip fill.
The properties of all filters affect each other, so if you adjust one property to change the effect
that you’re applying, you might need to adjust another property as well.
This code uses the Drawing API to draw a square on the Stage, which is placed at the
center of the Stage. When you move the mouse pointer around the Stage, the amount of
blurring along the x-axis and y-axis increases or decreases. When you move your pointer
towards the left of the Stage, the amount of horizontal blurring decreases. When you
move the pointer towards the right of the Stage, the blurring increases. Similarly, the
higher the pointer is on the Stage, the smaller the amount of blurring that occurs along
the y-axis.
3. Select Control > Test Movie to test the document and view the results.
You can apply the color matrix filter to bitmaps and movie clip instances.
This code dynamically loads a JPEG image by using a MovieClipLoader instance. After
the image is completely loaded and is placed on the Stage, the instance’s brightness is set to
100% by using a color matrix filter.
3. Select Control > Test Movie to test the document.
You could also create an animated brightness effect by combining the Tween class with the
ColorMatrixFilter class, as the next procedure shows.
The first section of code uses the MovieClipLoader class to load a JPEG image onto the
Stage. After the image completely loads, you reposition the image to the center of the
Stage. Then you use the Tween class to animate the image brightness level. To animate the
brightness, you use the Object.watch() method, which registers an event handler that
you start when a specified property of an ActionScript object changes. Whenever some
ActionScript tries to set the custom brightness property of the target_mc instance, you
call the brightnessWatcher function. The custom brightnessWatcher function creates
a new array, which uses the color matrix filter to set the target image’s brightness to a
specified amount.
3. Select Control > Test Movie to test the document.
After the image loads and is placed on the Stage, the image’s brightness animates between
-100 and 100. After the brightness tween is complete, the animation is reversed using the
Tween.yoyo() method, which causes the tween to constantly animate.
You can apply this filter on bitmaps and movie clip instances.
A matrix convolution is based on an n x m matrix, which describes how a given pixel value in
the input image is combined with its neighboring pixel values to produce a resulting pixel
value. Each resulting pixel is determined by applying the matrix to the corresponding source
pixel and its neighboring pixels.
This filter is only available by using ActionScript. For more information on this filter, see
ConvolutionFilter (flash.filters.ConvolutionFilter) in the ActionScript 2.0 Language Reference.
The following procedure applies the convolution filter to a dynamically loaded JPEG image.
this.createEmptyMovieClip("shape_mc", 1);
shape_mc.createEmptyMovieClip("holder_mc", 1);
var imageLoader:MovieClipLoader = new MovieClipLoader();
imageLoader.loadClip("http://www.helpexamples.com/flash/images/
image1.jpg", shape_mc.holder_mc);
var matrixArr:Array = [1, 4, 6, 4, 1, 4, 16, 24, 16, 4, 16, 6, 24, 36,
24, 6, 4, 16, 24, 16, 4, 1, 4, 6, 4, 1];
var convolution:ConvolutionFilter = new ConvolutionFilter(5, 5,
matrixArr);
shape_mc.filters = [convolution];
This code loads a JPEG image and places it on the Stage. After the image is completely
loaded, this code creates a BitmapData instance and uses the perlinNoise() method to
fill it with randomly placed pixels. The BitmapData instance passes to the displacement
map filter, which is applied to the image and causes the image to look distorted.
Move your mouse pointer around the Stage to re-create a displacement map by calling the
perlinNoise() method, which changes the appearance of the JPEG image.
Because the previous code snippet returns a copy of the filters array, the code modifies the
copy instead of the original array. In order to modify the blurX property, you would need to
use the following ActionScript code instead:
// works
var filterArray:Array = my_mc.filters;
filterArray[0].blurX = 20;
my_mc.filters = filterArray;
The following procedure blurs an image based on the current position of the mouse pointer
on the Stage. Whenever the mouse pointer moves horizontally or vertically, the blurX and
blurY properties of the blur filter are modified accordingly.
this.createEmptyMovieClip("holder_mc", 10);
holder_mc.createEmptyMovieClip("img_mc", 20);
holder_mc.img_mc.loadMovie("http://www.helpexamples.com/flash/images/
image2.jpg");
holder_mc.filters = [new BlurFilter(10, 10, 2)];
holder_mc._x = 75;
holder_mc._y = 75;
holder_mc.onMouseMove = function() {
var tempFilter:BlurFilter = holder_mc.filters[0];
tempFilter.blurX = Math.floor((_xmouse / Stage.width) * 255);
tempFilter.blurY = Math.floor((_ymouse / Stage.height) * 255);
holder_mc.filters = [tempFilter];
};
The previous code is split into three sections. The first section imports the
flash.filters.BlurFilter class so that you don’t have to use the fully qualified class name
when you refer to the BlurFilter class. The second section of code creates a couple of
movie clips and loads an image into one of the nested clips. The third section of code
responds to the mouse movement on the Stage and adjusts the blur accordingly.
3. Select Control > Test Movie to test the Flash document.
this.createEmptyMovieClip("holder_mc", 10);
holder_mc.createEmptyMovieClip("img_mc", 20);
This code creates a text field with the instance name status_txt, which follows the
mouse pointer and displays the current values for the high and low parameters for the
noise() method. The setInterval() function changes the noise effect, which is
updated every 100 milliseconds (1/10 of a second), by continuously calling the
updateNoise() function. The high and low parameters for the noise() method are
determined by calculating the pointer’s current position on the Stage.
3. Select Control > Test Movie to test the document.
Moving the mouse pointer along the x-axis affects the low parameter; moving the mouse
pointer along the y-axis affects the high parameter.
This code example consists of five logical sections. The first section imports the necessary
classes for the example. The second block of code creates a nested movie clip and loads a
JPEG image from a remote server. The third block of code creates a new BitmapData
instance named perlinBmp, which is the same size as the dimensions of the Stage. The
perlinBmp instance contains the results of a Perlin noise effect, and is used later as a
parameter for the displacement map filter. The fourth block of code creates and applies
the displacement map filter effect to the dynamically loaded image created earlier. The
fifth, and final, block of code creates a listener for the mouse that regenerates the Perlin
noise that the displacement map filter uses whenever the user moves the mouse pointer.
function cbListener(eventObj:Object):Void {
img_mc.blendModeType_mc.blendMode = eventObj.target.value;
}
blendMode_cb.addEventListener("change", cbListener);
This ActionScript code populates the combo box with each type of blending mode, so the
user can view each effect on the dynamically loaded image. A listener object is created,
which is used with a MovieClipLoader instance. The listener object defines a single event
listener, onLoadInit, which is invoked when the image is completely downloaded and is
initialized by Flash. The event listener creates a new movie clip named
blendModeType_mc, and uses the Drawing API to draw a rectangular shape over the left
half of the image. The currently selected blending mode for the ComboBox instance is
then applied to the blendModeType_mc movie clip.
The rest of the code sets up the MovieClipLoader instance, which is responsible for
loading the specified image into a movie clip on the Stage. Finally, a listener is defined for
the blendMode_cb ComboBox instance, which applies the selected blending mode
whenever a new item is selected from the ComboBox instance.
4. Select Control > Test Movie to test the document.
You can use the drawing methods with any movie clip. However, if you use the drawing
methods with a movie clip that was created in authoring mode, the drawing methods execute
before the clip is drawn. In other words, content that is created in authoring mode is drawn
on top of content drawn with the drawing methods.
You can use movie clips with drawing methods as masks; however, as with all movie clip
masks, strokes are ignored.
For more information on drawing with ActionScript, see the following topics:
■ “Using drawing methods to draw lines, curves, and shapes” on page 500
■ “Drawing specific shapes” on page 501
■ “Using complex gradient fills” on page 505
■ “Using line styles” on page 506
■ “Using Drawing API methods and scripting animation” on page 512
For a sample source file which shows you how to use the Drawing API in a Flash application,
drawingapi.fla, see the Flash Samples page at www.adobe.com/go/learn_fl_samples.
Download the Samples zip file and navigate to the ActionScript2.0/DrawingAPI folder to
access this sample.
To draw a line:
1. Create a new Flash document and save it as line.fla.
2. Add the following ActionScript to Frame 1 of the Timeline:
this.createEmptyMovieClip("line_mc", 10);
line_mc.lineStyle(1, 0x000000, 100);
line_mc.moveTo(0, 0);
line_mc.lineTo(200, 100);
line_mc._x = 100;
line_mc._y = 100;
This code draws a line from 0,0 on the Stage to 200,100. The line’s _x and _y coordinates
are then modified to reposition the line to 100,100 on the Stage.
3. Save your Flash document and select Control > Test Movie to test the SWF file.
To draw a more complex shape, continue calling the MovieClip.lineTo() method and draw
a rectangle, square, or oval, as the following procedures show.
To draw a curve:
1. Create a new Flash document and save it as curve.fla.
2. Add the following ActionScript to Frame 1 of the Timeline:
this.createEmptyMovieClip("circle_mc", 1);
with (circle_mc) {
lineStyle(4, 0x000000, 100);
beginFill(0xFF0000);
moveTo(200, 300);
curveTo(300, 300, 300, 200);
curveTo(300, 100, 200, 100);
curveTo(100, 100, 100, 200);
curveTo(100, 300, 200, 300);
endFill();
}
3. Save your Flash document and select Control > Test Movie to test the Flash document.
To draw a triangle:
1. Create a new Flash document and save it as triangle.fla.
2. Add the following ActionScript to Frame 1 of the Timeline:
this.createEmptyMovieClip("triangle_mc", 1);
In this code, the empty movie clip (triangle_mc) calls drawing methods. This code
draws a triangle with 5-pixel purple lines and no fill.
4. Save your Flash document and select Control > Test Movie to test the Flash document.
For detailed information on these methods, see their entries in MovieClip in the ActionScript
2.0 Language Reference.
For a sample source file which shows you how to use the Drawing API in a Flash application,
drawingapi.fla, see the Flash Samples page at www.adobe.com/go/learn_fl_samples.
Download the Samples zip file and navigate to the ActionScript2.0/DrawingAPI folder to
access this sample.
To create a rectangle:
1. Create a new Flash document and save it as rect.fla.
3. Save your Flash document and select Control > Test Movie to test the Flash document.
Flash draws a simple green rectangle on the Stage and positions it at 100,100. To change
the dimensions of the rectangle, or its fill color or transparency, you can change those
values within the call to the drawRectangle() method instead of having to modify the
contents of the MovieClip.beginFill() method.
You can also create a rectangle with rounded corners using the Drawing API, as the following
procedure shows.
3. Save the Flash document and select Control > Test Movie to test the document.
A green rectangle appears on the Stage that is 240 pixels wide and 180 pixels high with
20-pixel rounded corners. You can create multiple instances of rounded rectangles by
creating new movie clips using MovieClip.createEmptyMovieClip() and calling your
custom drawRoundedRectangle() function.
You can create a perfect circle using the Drawing API, as the following procedure shows.
To create a circle:
1. Create a new Flash document and save as circle2.fla.
2. Add the following ActionScript code to Frame 1 of the Timeline:
this.createEmptyMovieClip("circle_mc", 10);
circle_mc._x = 100;
circle_mc._y = 100;
drawCircle(circle_mc, 100, 0x99FF00, 100);
3. Save your Flash document and select Control > Test Movie to test the SWF file.
This code creates a more complex, and realistic, circle than the previous circle example.
Instead of only using four calls to the curveTo() method, this example uses eight calls to the
curveTo() method, which gives the shape a much rounder appearance.
You can use the Drawing API to create a triangle, as the following procedure shows.
The Drawing API draws an equilateral triangle on the Stage and fills it with the specified
fill color and amount of alpha (transparency).
3. Save the Flash document and select Control > Test Movie to test the Flash document.
For a sample source file which shows you how to use the Drawing API in a Flash application,
drawingapi.fla, see the Flash Samples page at www.adobe.com/go/learn_fl_samples.
Download the Samples zip file and navigate to the ActionScript2.0/DrawingAPI folder to
access this sample.
The preceding ActionScript code uses the Drawing API to create a square on the Stage
and calls the beginGradientFill() method to fill the square with a red and blue
circular gradient.
3. Save the Flash document and select Control > Test Movie to view the Flash file.
You can call MovieClip.lineStyle() in the middle of drawing a path to specify different
styles for different line segments within a path.
For more information on using ActionScript to set line styles, see the following sections:
■ “Setting stroke and caps styles” on page 506
■ “Setting parameters of line styles” on page 507
The preceding code dynamically creates four movie clips and uses the Drawing API to
create a series of lines on the Stage. The first movie clip contains two vertical lines, one at
50 pixels and the other at 250 pixels on the x-axis. The next three movie clips each draw a
green line on the Stage and sets their capsStyle to round, square, or none.
3. Select Control > Test Movie to test the document.
The different caps styles appear on the Stage at runtime.
The preceding code uses the Drawing API to draw two lines on the Stage. The first line is
red and has a thickness of 0, indicating a hairline thickness, the second line is blue and has
a thickness of 1 pixel.
3. Save the Flash document and select Control > Test Movie to test the SWF file.
Initially, both the red and blue lines look exactly the same. If you right-click in the SWF
file and select Zoom In from the context menu, the red line always appears as a 1-pixel
line; however, the blue line grows larger each time you zoom in to the SWF file.
It is useful to enable scaling for user interface elements when users zoom in, but not if a
movie clip is only scaled vertically or horizontally.
You can use one of four different modes to specify when scaling should occur and when it
shouldn’t. The following are the possible values for the noScale property:
normal Always scale the thickness (default).
vertical Do not scale the thickness if the object is scaled vertically.
horizontal Do not scale the thickness if the object is scaled horizontally.
none Never scale the thickness.
The following procedure demonstrates the differences between each of the three caps styles. A
visual representation of each cap style appears on the Stage when you test the SWF file.
The preceding code uses the Drawing API to draw three lines, each with a different value
for capsStyle.
The following example demonstrates the differences between each of the three joint styles.
Flash uses the Drawing API to draw three triangles on the Stage. Each triangle has a
different value for its joint style.
3. Save the Flash document and select Control > Test Movie to test the document.
This code example imports the Tween class and each of the classes in the easing package.
Next, it creates an object that acts as the listener object for a MovieClipLoader instance
that’s created in a later section of the code. The listener object defines a single event
listener, onLoadInit, which centers the dynamically loaded JPEG image on the Stage.
After the code repositions the image, a new movie clip instance is created within the
target_mc movie clip (which contains the dynamically loaded JPEG image). The
Drawing API code draws a rectangle with the same dimensions as the JPEG image within
this new movie clip. The new movie clip masks the JPEG image by calling the
MovieClip.setMask() method. After the mask is drawn and set up, the mask uses the
Tween class to animate, which causes the image to slowly reveal itself.
3. Save the Flash document and select Control > Test Movie to test the SWF file.
NOT E
To animate _alpha in the previous example instead of _yscale, tween the target_mc
directly instead of the mask movie clip.
For a sample source file which shows you how to use the Drawing API in a Flash application,
drawingapi.fla, see the Flash Samples page at www.adobe.com/go/learn_fl_samples.
Download the Samples zip file and navigate to the ActionScript2.0/DrawingAPI folder to
access this sample.
By default, the Button component instance is 100 pixels wide by 22 pixels high.
4. Resize the Button component instance to 200 pixels width by 44 pixels high by using the
Property inspector.
Strokes are created from the edges after the 9-slice scaling transformation, and
therefore don't deform or lose detail.
You can enable slice guides for 9-slice scaling in the Flash environment within the Convert to
Symbol dialog box or the Symbol Properties dialog box. The Enable guides for 9-slice scaling
check box is available only if you are publishing for Flash Player 8 and later and the behavior
is set to movie clip. The 9-slice scaling guides are not available for earlier versions of Flash or if
you are creating a button or graphic symbol. 9-slice scaling can be enabled in ActionScript by
setting the scale9Grid property on a movie clip instance.
Whether you created your slice guides by using the user interface or by using ActionScript,
you can trace the x coordinate, y coordinate, width, and height by tracing the movie clip’s
scale9Grid property.
trace(my_mc.scale9Grid); // (x=20, y=20, w=120, h=120)
This snippet of code traces the value of the Rectangle object being used by the scale9Grid
property. The rectangle has a x and y coordinates of 20 pixels, a width of 120 pixels and a
height of 120 pixels.
The preceding code is separated into five sections. The first section of code imports two
classes: mx.controls.Button (the Button component class) and flash.geom.Rectangle. The
second section of code creates a new Rectangle class instance and specifies x and y
coordinates of 100 pixels as well as a width and height of 100 pixels. This rectangle
instance is used to set up the 9-slice scaling grid for a movie clip shape created later on.
519
About events and interaction
Whenever a user clicks the mouse or presses a key, that action generates an event. These types
of events are generally called user events because they are generated in response to some action
by the user. You can write ActionScript to respond to, or handle, these events. For example,
when a user clicks a button, you might want to send the playhead to another frame in the
SWF file or load a new web page into the browser.
In a SWF file, buttons, movie clips, and text fields all generate events to which you can
respond. ActionScript provides three ways to handle events: event handler methods, event
listeners, and on() and onClipEvent() handlers. For more information about events and
handling events, see Chapter 9, “Handling Events.”
In the next example, the MovieClip.gotoAndStop() method sends the timeline of a movie
clip instance named categories_mc to Frame 10 and stops. When you use the MovieClip
methods gotoAndPlay() and gotoAndStop(), you must specify an instance to which the
method applies.
jump_btn.onPress = function () {
categories_mc.gotoAndStop(10);
};
In the final example, the global gotoAndStop() function is used to move the playhead to
Frame 1 of Scene 2. If no scene is specified, the playhead goes to the specified frame in the
current scene. You can use the scene parameter only on the root timeline, not within timelines
for movie clips or other objects in the document.
nextScene_mc.onRelease = function() {
gotoAndStop("Scene 2", 1);
}
The same conditions apply to onClipEvent() handlers attached to movie clip objects. For
example, the following code stops the timeline of the movie clip that bears the
onClipEvent() handler when the clip first loads or appears on the Stage:
onClipEvent(load) {
stop();
}
The following code then loads addUser.cfm into a blank browser window and passes
variables_mc.name and variables_mc.age in the POST header to the CFM page:
variables_mc.getURL("addUser.cfm", "_blank", "POST");
The functionality of getURL() is dependent on what browser you use. The most reliable way
to get all browsers to work the same is to call a JavaScript function in the HTML code that
uses the JavaScript window.open() method to open a window. Add the following HTML and
JavaScript within your HTML template:
<script language="JavaScript">
<--
function openNewWindow(myURL) {
window.open(myURL, "targetWindow");
}
// -->
</script>
You can use the following ActionScript to call openNewWindow from your SWF file:
var myURL:String = "http://foo.com";
getURL("javascript:openNewWindow('" + String(myURL) + "');");
For more information, see getURL function in the ActionScript 2.0 Language Reference.
The Mouse.hide() method hides the pointer when the movie clip first appears on the
Stage; the onMouseMove function positions the custom pointer at the same place as the
pointer and calls updateAfterEvent() whenever the user moves the mouse.
The updateAfterEvent() function immediately refreshes the screen after the specified
event occurs, rather than when the next frame is drawn, which is the default behavior. (See
updateAfterEvent function in the ActionScript 2.0 Language Reference.)
5. Select Control > Test Movie to test your custom pointer.
Buttons still function when you use a custom mouse pointer. It’s a good idea to put the
custom pointer on the top layer of the timeline so that, as you move the mouse in the SWF
file, the custom pointer appears in front of buttons and other objects in other layers. Also, the
tip of a custom pointer is the registration point of the movie clip you’re using as the custom
pointer. Therefore, if you want a certain part of the movie clip to act as the tip of the pointer,
set the registration point coordinates of the clip to be that point.
For more information about the methods of the Mouse class, see Mouse in the ActionScript
2.0 Language Reference.
The _xmouse and _ymouse properties within the main timeline and a movie clip timeline
The following procedure shows several ways to get the pointer position within the main
timeline or within a movie clip.
5. Select Control > Test Movie to test the Flash movie. The box1_txt and box2_txt fields
show the position of the pointer while you move it over the Stage.
For more information about the _xmouse and _ymouse properties, see _xmouse
(MovieClip._xmouse property) and _ymouse (MovieClip._ymouse property) in the
ActionScript 2.0 Language Reference.
Make sure that you select Control > Disable Keyboard Shortcuts, or certain keys with built-in
behavior won’t be overridden when you use Control > Test Movie to test the application. See
the keyPress parameter of on handler in the ActionScript 2.0 Language Reference.
You can use the methods of the built-in Key class to detect the last key that the user pressed.
The Key class does not require a constructor function; to use its methods, you call the
methods on the class, as shown in the following example:
Key.getCode();
You can obtain either virtual key codes or American Standard Code for Information
Interchange (ASCII) values of keypresses:
■ To obtain the virtual key code of the last key pressed, use the getCode() method.
■ To obtain the ASCII value of the last key pressed, use the getAscii() method.
A virtual key code is assigned to every physical key on a keyboard. For example, the left arrow
key has the virtual key code 37. By using a virtual key code, you ensure that your SWF file’s
controls are the same on every keyboard, regardless of language or platform.
ASCII values are assigned to the first 127 characters in every character set. ASCII values
provide information about a character on the screen. For example, the letter “A” and the letter
“a” have different ASCII values.
The key code of the desired key appears in the Output panel.
A common place to use Key class methods is within an event handler. In the following
example, the user moves the car using the arrow keys. The Key.isDown() method indicates
whether the key being pressed is the right, left, up, or down arrow. The event listener,
Key.onKeyDown, determines the Key.isDown(keyCode) value from the if statements.
Depending on the value, the handler instructs Flash Player to update the position of the car
and to show the direction.
The following example shows how to capture keypresses to move a movie clip up, down, left,
or right on the Stage, depending on which corresponding arrow key (up, down, left, or right)
is pressed. Also, a text field shows the name of the pressed key.
4. Add the following ActionScript code to the Actions panel below the existing code:
this.createTextField("display_txt", 999, 0, 0, 100, 20);
5. To create the event handler for the car movie clip that checks which arrow key (left, right,
up, or down) is currently pressed, add the following code to the Actions panel:
var keyListener:Object = new Object();
keyListener.onKeyDown = function() {
};
Key.addListener(keyListener);
If the Left Arrow key is pressed, the car’s _x property is set to the current _x value minus
distance or the value 0, whichever is greater. Therefore, the value of the _x property can
never be less than 0. Also, the word Left should appear in the SWF file.
7. Use similar code to check if the Right, Up, or Down Arrow key is being pressed.
Your complete code should look like the following example (new code is in boldface):
var distance:Number = 10;
this.createTextField("display_txt", 999, 0, 0, 100, 20);
var keyListener:Object = new Object();
keyListener.onKeyDown = function() {
if (Key.isDown(Key.LEFT)) {
car_mc._x = Math.max(car_mc._x - distance, 0);
display_txt.text = "Left";
} else if (Key.isDown(Key.RIGHT)) {
car_mc._x = Math.min(car_mc._x + distance, Stage.width -
car_mc._width);
display_txt.text = "Right";
} else if (Key.isDown(Key.UP)) {
car_mc._y = Math.max(car_mc._y - distance, 0);
display_txt.text = "Up";
} else if (Key.isDown(Key.DOWN)) {
car_mc._y = Math.min(car_mc._y + distance, Stage.height -
car_mc._height);
display_txt.text = "Down";
}
};
Key.addListener(keyListener);
7. To make the blue button change the color of the car_mc movie clip to blue, add the
following code to the Actions panel:
blue_btn.onRelease = function() {
colorTrans.rgb = 0x333399; // blue
trans.colorTransform = colorTrans;
};
The preceding snippet of code changes the rgb property of the color transform object and
reapplies the color tranform effect to the car_mc movie clip whenever the button
is pressed.
blue_btn.onRelease = function() {
colorTrans.rgb = 0x333399; // blue
trans.colorTransform = colorTrans;
};
red_btn.onRelease = function() {
colorTrans.rgb = 0xFF0000; // red
trans.colorTransform = colorTrans;
};
green_btn.onRelease = function() {
colorTrans.rgb = 0x006600; // green
trans.colorTransform = colorTrans;
};
black_btn.onRelease = function() {
colorTrans.rgb = 0x000000; // black
trans.colorTransform = colorTrans;
};
9. Select Control > Test Movie to change the color of the movie clip.
For more information about the methods of the ColorTransform class, see ColorTransform
(flash.geom.ColorTransform) in the ActionScript 2.0 Language Reference.
This code first stops the speaker movie clip. It then creates a new Sound object
(song_sound) and attaches the sound whose linkage identifier is a_thousand_ways. The
onRelease event handlers associated with the play_btn and stop_btn objects start and
stop the sound by using the Sound.start() and Sound.stop() methods, and also play
and stop the attached sound.
7. Select Control > Test Movie to hear the sound.
volume_mc.handle_btn.onPress = function() {
startDrag(this._parent, false, this._parent.left, this._parent.top,
this._parent.right, this._parent.bottom);
};
volume_mc.handle_btn.onRelease = function() {
stopDrag();
var level:Number = Math.ceil(this._parent._x - this._parent.left);
this._parent._parent.song_sound.setVolume(level);
this._parent._parent.volume_txt.text = level;
};
volume_mc.handle_btn.onReleaseOutside = slider_mc.handle_btn.onRelease;
The startDrag() parameters left, top, right, and bottom are variables set in a
movie clip action.
10. Select Control > Test Movie to use the volume slider.
The startDrag() parameters left, top, right, and bottom are variables set in a
movie clip action.
9. Select Control > Test Movie to use the balance slider.
For more information about the methods of the Sound class, see Sound in the ActionScript 2.0
Language Reference.
Detecting collisions
The hitTest() method of the MovieClip class detects collisions in a SWF file. It checks to
see if an object has collided with a movie clip and returns a Boolean value (true or false).
You would want to know whether a collision has occurred either to test if the user has arrived
at a certain static area on the Stage, or to determine when one movie clip has reached another.
With hitTest(), you can determine these results.
You can use the parameters of hitTest() to specify the x and y coordinates of a hit area on
the Stage or use the target path of another movie clip as a hit area. When you specify x and y,
hitTest() returns true if the point identified by (x, y) is a non-transparent point. When a
target is passed to hitTest(), the bounding boxes of the two movie clips are compared. If
they intersect, hitTest() returns true. If the two boxes do not intersect, hitTest()
returns false.
You can also use hitTest() to test a collision between two movie clips.
The following example shows how to detect a collision between a mouse and movie clips on
the Stage.
4. Select Control > Test Movie, and move the pointer over the movie clip to test the collision.
The value true appears whenever the pointer is over a non-transparent pixel.
car_mc.onPress = function() {
this.startDrag(false);
updateAfterEvent();
};
car_mc.onRelease = function() {
this.stopDrag();
};
You can apply these methods to any movie clip instance (for example, myClip.lineTo()), or
to a level (_level0.curveTo()).
The lineTo() and curveTo() methods let you draw lines and curves, respectively. You
specify a line color, thickness, and alpha setting for a line or curve with the lineStyle()
method. The moveTo() drawing method sets the current drawing position to the x and y
Stage coordinates that you specify.
The beginFill() and beginGradientFill() methods fill a closed path with a solid or
gradient fill, respectively, and endFill() applies the fill specified in the last call to
beginFill() or beginGradientFill(). The clear() method erases what’s been drawn in
the specified movie clip object.
If you forget to delete the DataBindingClasses component from the Stage, the
component’s icon is visible at runtime.
NOT E
When you created a binding using the Component inspector in the previous
example, Flash added the DataBindingClasses component automatically to the FLA
file. When you use ActionScript to create data bindings, you must copy that class
into your library yourself, as shown in the following step.
If you prefer the somewhat shortened version, you could import the binding classes and
use the following code instead:
import mx.data.binding.*;
var src:EndPoint = new EndPoint();
src.component = in_ti;
src.property = "text";
src.event = "focusOut";
var dest:EndPoint = new EndPoint();
dest.component = out_ti;
dest.property = "text";
new Binding(src, dest);
This ActionScript creates two data binding end points, one for each component that
you’re binding. The first endpoint you create defines which component it is binding from
(in_ti), which property to watch for (text), and which event will trigger the binding
(focusOut). The second endpoint you create lists only the component and property
(out_ti and text, respectively). Finally, you create the binding between the two
endpoints when you call the constructor for the Binding class (new Binding(src,
dest)).
You don’t need to use fully qualified class names (such as mx.data.binding.EndPoint)
in your ActionScript, as you saw in the first code snippet. If you use the import statement
at the beginning of your code, you can avoid using fully qualified names. When you
import all the classes in the mx.data.binding package using the wildcard (*) (the
package includes both the EndPoint and Binding classes), you can shorten your code and
directly reference the EndPoint and Binding classes. For more information on import
statements, see the import entry in the ActionScript 2.0 Language Reference.
8. Select Control > Test Movie to test the code in the test environment. Enter some text into
the in_ti text input field.
After the in_ti instance loses focus (click the Stage, press Tab, or click the second field),
Flash copies any text that you input into in_ti to the out_ti text field.
9. Select File > Save to save your changes.
You can use the Binding classes with most user interface components of version 2 of the
Adobe Component Architecture, not just the TextInput component. The following example
demonstrates how to use ActionScript to bind CheckBox instances and Label components
during runtime.
You use objects to define the endpoints instead of creating new instances of the EndPoint
class, as demonstrated in the previous exercises in this section. The code snippet in this
step creates two objects, which act as endpoints for the binding. You create the binding
when you call the constructor for the Binding class. To reduce the amount of code (and
readability) even more, define the objects inline as shown in the following snippet:
new mx.data.binding.Binding({component:my_ch, property:"selected",
event:"click"}, {component:my_lbl, property:"text"});
This ActionScript reduces the readability of your code, but it also reduces the amount of
typing you have to do. If you share your FLA (or ActionScript) files, you might want to
use the first snippet of ActionScript, because it is more reader friendly.
This code creates a binding between the DateChooser's selectedDate property and the
text property of the Label component on the Stage. Each time you click a new date in the
calendar, the selected date appears in the Label component.
6. Save the Flash document as customformat.fla in a convenient location on your hard disk.
(You will recycle it in the next exercise.)
7. Select Control > Test Movie to test the document.
Try to change the dates in the Calendar component and you’ll see the currently selected
date appear in the Label component. The Label component isn’t wide enough to display
the entire date, so Flash crops off the text.
8. Close the test SWF file and return to the authoring environment.
Either resize the Label component on the Stage or select the Label component and set the
autoSize property to left in the Parameters tab of the Property inspector.
You need to complete the exercise from “Using components, bindings, and custom
formatters” on page 542 before you begin this one.
Your code is probably fine. This problem occurs when Flash cannot locate the class, and
because of this, syntax checking fails.
4. Save the DateFormat.as file.
5. Open customformat.fla from the exercise in “Using components, bindings, and custom
formatters”. Make sure you save or copy DateFormat.as in the same directory as this file.
6. In customformat.fla, modify the ActionScript code in Frame 1 of the actions layer to match
the following code:
import mx.data.binding.*;
var src:EndPoint = new EndPoint();
src.component = my_dc;
src.property = "selectedDate";
src.event = "change";
var dest:EndPoint = new EndPoint();
dest.component = my_lbl;
dest.property = "text";
new Binding(src, dest, {cls:mx.data.formatters.Custom,
settings:{classname:"DateFormat", classname_class:DateFormat}});
This time you define a customFormatter object, which tells Flash that you’re using the
newly created DateFormat class to format the endpoint on the binding.
7. Save the changes in your document and select Control > Test Movie to test your code.
The first line of ActionScript imports the classes from the mx.data.binding package so
that you don’t need to use fully qualified paths in your code. The next two lines of
ActionScript attach the components from the document’s library to the Stage. Next you
position the components on the Stage.
Finally you add data to the ComboBox instance and create the binding between the my_cb
ComboBox and my_lbl Label component on the Stage.
reset_btn.onRelease = function() {
zapped = false;
bug_mc._x = initx;
bug_mc._y = inity;
bug_mc._alpha = 100;
bug_mc._rotation = 0;
};
bug_mc.onPress = function() {
this.startDrag();
};
bug_mc.onRelease = function() {
this.stopDrag();
};
bug_mc.onEnterFrame = function() {
if (this.hitTest(this._parent.zapper_mc)) {
this.stopDrag();
zapped = true;
bug_mc._alpha = 75;
bug_mc._rotation = 20;
this._parent.zapper_mc.play();
}
if (zapped) {
bug_mc._y += 25;
}
};
549
About loading and working with
external media
You can load several types of media files into a Flash application at runtime: SWF, MP3,
JPEG, GIF, PNG, and FLV files. However, not all versions of Flash Player support each kind
of media. For more information on the image file types that are supported in Flash Player 8
and later, see “Loading external SWF and image files” on page 551. For information on FLV
video support in Flash Player, see “About using FLV video” on page 560
Flash Player can load external media from any HTTP or FTP address, from a local disk using
a relative path, or by using the file:// protocol.
To load external SWF and image files, you can use the loadMovie() or loadMovieNum()
function, the MovieClip.loadMovie() method, or the MovieClipLoader.loadClip()
method. The class methods generally provide more function and flexibility than global
functions and are appropriate for more complex applications. When you load a SWF or image
file, you specify a movie clip or SWF file level as the target for that media. For more
information on loading SWF and image files, see “Loading external SWF and image files”
on page 551.
To play back an external MP3 file, use the loadSound() method of the Sound class. This
method lets you specify whether the MP3 file should progressively download or complete
downloading before it starts to play. You can also read the ID3 information embedded in
MP3 files, if they’re available. For more information, see “Reading ID3 tags in MP3 files”
on page 558.
Flash Video is the native video format used by Flash Player. You can play FLV files over
HTTP or from a local file system. Playing external FLV files provides several advantages over
embedding video in a Flash document, such as better performance and memory management
as well as independent video and Flash frame rates. For more information, see “Playing back
external FLV files dynamically” on page 563.
You can also preload or track the downloading progress of external media with the
MovieClipLoader class, which you can use to track the downloading progress of SWF or
image files. To preload MP3 and FLV files, you can use the getBytesLoaded() method of
the Sound class and the bytesLoaded property of the NetStream class. For more information,
see “Preloading FLV files” on page 566.
For samples of photo gallery applications, see the Flash Samples page at www.adobe.com/go/
learn_fl_samples. Download the Samples zip file and navigate to the ActionScript2.0/
Galleries to access these samples:
■ gallery_tree.fla
For image files, Flash Player 8 and later support the JPEG (progressive and non-progressive)
image file type, GIF images (transparent and non-transparent, although only the first frame of
an animated GIF will be loaded), and PNG files (transparent and non-transparent).
To load a SWF or image file into a level in Flash Player, use the loadMovieNum() function.
To load a SWF or image file into a movie clip target, use the loadMovie() function or
method. In either case, the loaded content replaces the content of the specified level or target
movie clip.
When you load a SWF or image file into a movie clip target, the upper-left corner of the SWF
file or image is placed on the registration point of the movie clip. Because this registration
point is often the center of the movie clip, the loaded content might not appear centered.
Also, when you load a SWF file or image to a root timeline, the upper-left corner of the image
is placed on the upper-left corner of the Stage. The loaded content inherits rotation and
scaling from the movie clip, but the original content of the movie clip is removed.
You can optionally send ActionScript variables with a loadMovie() or loadMovieNum() call.
This is useful, for example, if the URL you’re specifying in the method call is a server-side
script that returns a SWF or image file according to data passed from the Flash application.
When you use the global loadMovie() or loadMovieNum() function, specify the target level
or clip as a parameter. The following example loads the Flash application contents.swf into the
movie clip instance named image_mc:
loadMovie("contents.swf", image_mc);
The following example loads the image1.jpg JPEG image into the image_mc movie clip
instance:
image_mc.loadMovie("http://www.helpexamples.com/flash/images/image1.jpg");
Create a listener object and create event handlers The listener object can be any
ActionScript object, such as a generic Object object, a movie clip, or a custom component.
The following example creates a generic listener object named loadListener and defines for
itself onLoadError, onLoadStart, onLoadProgress, and onLoadComplete functions:
// Create listener object:
var mclListener:Object = new Object();
mclListener.onLoadError = function(target_mc:MovieClip, errorCode:String,
status:Number) {
trace("Error loading image: " + errorCode + " [" + status + "]");
};
mclListener.onLoadStart = function(target_mc:MovieClip):Void {
trace("onLoadStart: " + target_mc);
};
mclListener.onLoadProgress = function(target_mc:MovieClip,
numBytesLoaded:Number, numBytesTotal:Number):Void {
var numPercentLoaded:Number = numBytesLoaded / numBytesTotal * 100;
trace("onLoadProgress: " + target_mc + " is " + numPercentLoaded + "%
loaded");
};
mclListener.onLoadComplete = function(target_mc:MovieClip,
status:Number):Void {
trace("onLoadComplete: " + target_mc);
};
N OTE
Flash Player 8 and later allow you to check the HTTP status of a MovieClipLoader
download within the onLoadComplete and onLoadError event listeners. This ability
allows you to check why the file was unable to download—whether it was a server error,
or the file was unable to be found, and so on.
You can use MovieClipLoader methods only to track the downloading progress of files
loaded with the MovieClipLoader.loadClip() method. You cannot use the loadMovie()
function or MovieClip.loadMovie() method.
The following example uses the setProgress() method of the ProgressBar component to
display the downloading progress of a SWF file. For more information, see ActionScript 2.0
Components Language Reference.
this.createEmptyMovieClip("img_mc", 999);
When you load files in the test environment, make sure you load an uncached file
from the Internet and not a local file if you want to see the progress bar work. A local
file loads too quickly to see the progress. Alternatively, upload your SWF file and test
your document on a server.
For related information, see “About loading SWF files and the root timeline” on page 555.
For more information on the MovieClipLoader class, see MovieClipLoader in the
ActionScript 2.0 Language Reference. For information on creating a progress bar animation, see
“Creating a progress animation for loading SWF and image files” on page 581.
For samples of photo gallery applications, see the Flash Samples page at www.adobe.com/go/
learn_fl_samples. Download the Samples zip file and navigate to the ActionScript2.0/
Galleries to access these samples:
■ gallery_tree.fla
■ gallery_tween.fla
Use the new object to call loadSound() to load an event or a streaming sound. Event sounds
are loaded completely before being played; streaming sounds play as they download. You can
set the isStreaming parameter of loadSound() to specify a sound as a streaming or event
sound. After you load an event sound, you must call the start() method of the Sound class
to make the sound play. Streaming sounds begin playing when sufficient data is loaded into
the SWF file; you don’t need to use start().
In most cases, set the isStreaming parameter to true, especially if you’re loading large sound
files that should start playing as soon as possible—for example, when creating an MP3
“jukebox” application. However, if you download shorter sound clips and need to play them
at a specified time (for example, when a user clicks a button), set isStreaming to false.
To determine when a sound IS completely downloaded, use the Sound.onLoad event handler.
This event handler automatically receives a Boolean value (true or false) that indicates
whether the file downloaded successfully.
For more information, see the following topics:
■ “Loading an MP3 file” on page 556
■ “Preloading MP3 files” on page 557
■ “Reading ID3 tags in MP3 files” on page 558
For a sample source file that loads MP3 files, jukebox.fla, see the Flash Samples page at
www.adobe.com/go/learn_fl_samples. Download the Samples zip file and navigate to the
ComponentsAS2/Jukebox folder to access this sample. This sample demonstrates how to
create a jukebox by using data types, general coding principles, and several components.
7 7 and later
You can create FLV files by importing video into the Flash authoring tool and exporting it as
an FLV file. If you have Flash, you can use the FLV Export plug-in to export FLV files from
supported video-editing applications.
Using external FLV files provides certain capabilities that are not available when you use
imported video:
■ Longer video clips can be used in your Flash documents without slowing down playback.
External FLV files play using cached memory, which means that large files are stored in
small pieces and accessed dynamically, requiring less memory than embedded video files.
■ An external FLV file can have a different frame rate than the Flash document in which it
plays. For example, you can set the Flash document frame rate to 30 frames per second
(fps) and the video frame rate to 21 fps. This setting gives you better control of the video
than embedded video, to ensure smooth video playback. It also allows you to play FLV
files at different frame rates without the need to alter existing Flash content.
To load FLV files from a web server, you might need to register the file extension and
MIME type with your web server; check your web server documentation. The MIME
type for FLV files is video/x-flv. For more information, see “Configuring your server
for FLV files” on page 579.
13. Select Insert > Timeline > Layer to create a new layer, and name it button.
14. Select the Rectangle tool in the Tools panel.
15. In the Colors section of the Tools panel, click the pencil icon to select the Stroke
color control.
16. Select No Color, which disables the rectangle’s outline.
17. Drag the pointer diagonally across the Stage to create a rectangle.
The size of the rectangle does not matter because you’ll resize it by using the
Property inspector.
18. Click the Selection tool in the Tools panel then click the rectangle on the Stage to select it.
19. With the rectangle still selected, type 468 in the width text box and 60 in the height text
box in the Property inspector. Then change the X and Y coordinates (X and Y text boxes)
to 0.
20.With the rectangle selected on the Stage, press F8 to change the rectangle into a symbol.
21. In the Convert to Symbol dialog box, type invisible btn in the Name text box, select
Button, and then click OK.
22.Double-click the new button on the Stage to enter symbol-editing mode.
The rectangle is currently on the first Up frame of the button you created. This is the Up
state of the button—what users see when the button is on the Stage. However, you want
the button to not be visible on the Stage, so you need to move the rectangle to the Hit
frame, which is the hit area of the button (the active region that a user can click to activate
the button’s actions).
23.Click the keyframe at the Up frame, and hold down the mouse button while you drag the
keyframe to the Hit frame.
You can now click in the entire banner area, but there is no visual appearance of the
button on your banner.
24.Click Scene 1 to return to the main Timeline.
A teal rectangle appears over the banner area, representing the invisible button’s hit area.
25.Select the button you created, open the Property inspector, and type inv_btn in the
Instance Name text box.
27. Make other modifications to the banner, such as adding graphics or text.
28.Select Control > Test Movie to test the banner in Flash Player.
In this example, you created a banner and resized its dimensions to the established,
standardized dimensions that the Interactive Advertising Bureau specifies. For information on
standard advertising dimensions (and many other useful guidelines), see the Interactive
Advertising Bureau’s Standards and Guidelines page at www.iab.net/standards/adunits.asp.
Despite standardized guidelines, ensure that you confirm the advertising guidelines for the
advertising service, client, or website that you’re advertising with first. If you submit your
banner to an advertising company, make sure the file meets a specified file size, dimension,
target Flash Player version, and frame-rate guideline. Also, you might have to consider rules
about the kinds of media you can use, button code you use in the FLA file, and so on.
If your progress bar loads instantly, the video has cached on your hard disk (either
from testing this example or loading it in a different procedure). If this occurs, upload
a FLV file to your server and load it instead.
Another way to preload FLV files is to use the NetStream.setBufferTime() method. This
method takes a single parameter that indicates the number of seconds of the FLV stream to
buffer before playback begins. For more information, see setBufferTime
(NetStream.setBufferTime method), getBytesLoaded (MovieClip.getBytesLoaded
method), getBytesTotal (MovieClip.getBytesTotal method), bytesLoaded
(NetStream.bytesLoaded property), bytesTotal (NetStream.bytesTotal
property), and setInterval function in the ActionScript 2.0 Language Reference.
function traceMeta(metaProp:Object):Void {
var p:String;
for (p in metaProp) {
switch (p) {
case "cuePoints" :
trace("cuePoints: ");
//cycles through the cue points
var cuePointArr:Array = metaProp[p];
for (var j:Number = 0; j < cuePointArr.length; j++) {
//cycle through the current cue point parameters
trace("\t cuePoints[" + j + "]:");
var currentCuePoint:Object = metaProp[p][j];
var metaPropPJParams:Object = currentCuePoint.parameters;
trace("\t\t name: " + currentCuePoint.name);
trace("\t\t time: " + currentCuePoint.time);
trace("\t\t type: " + currentCuePoint.type);
if (metaPropPJParams != undefined) {
trace("\t\t parameters:");
traceObject(metaPropPJParams, 4);
}
}
break;
default :
trace(p + ": " + metaProp[p]);
break;
}
}
}
function traceObject(obj:Object, indent:Number):Void {
var indentString:String = "";
for (var j:Number = 0; j < indent; j++) {
indentString += "\t";
}
for (var i:String in obj) {
if (typeof(obj[i]) == "object") {
trace(indentString + " " + i + ": [Object]");
traceObject(obj[i], indent + 1);
} else {
trace(indentString + " " + i + ": " + obj[i]);
}
}
}
For information on using cue points with the FLVPlayback component, see “Using embedded
cue points with the FLVPlayback component”.
To see the cue points on the Parameters tab, you must type the name of your FLV file in
the contentPath text box instead of using code to assign the contentPath.
Embed navigation cue points in a document if you intend to add navigation functionality
to an application. For more information, see “Working with cue points” on page 568. For
an example of working with embedded cue points, see “Using embedded cue points with
the FLVPlayback component” on page 570.
For information on working with cue points and the FLVPlayback component, see
ActionScript 2.0 Components Language Reference.
The following example shows how to add cue points at runtime and then trace the cue points
when a FLV file plays in the MediaPlayback component.
For more information on working with the MediaPlayback component and the FLVPlayback
component, see ActionScript 2.0 Components Language Reference.
function clickMe(){
my_flvPb.seekToNextNavCuePoint();
}
my_button.addEventListener("click", clickMe);
8. Select Control > Test Movie to test your code.
The cuepoints.flv file contains three navigation cue points: one each near the beginning,
middle, and end of the video file. When you click the button, the FLVPlayback instance
seeks to the next cue point until it reaches the last cue point in the video file.
function clickMe(){
my_flvPb.seekToNavCuePoint("point2");
}
my_button.addEventListener("click", clickMe);
If your video file does not have metadata information, you can use tools to add metadata
information to the file.
To work with NetStream.onMetaData, you must have Flash Video that contains metadata. If
you encode FLV files using Flash 8 Video Encoder, your FLV file will have metadata
information in it (see the following example for a list of metadata in a FLV file encoded with
Flash 8 Video Encoder).
N OTE
Flash Video Exporter 1.2 and later (including Flash 8 Video Exporter), add the metadata
to your FLV files. Sorenson Squeeze 4.1 and later also adds metadata to your video files.
If your video does not have audio, the audio-related metadata information (such as
audiodatarate) returns undefined because no audio information is added to the
metadata during encoding.
You can also use the following format to display most metadata information. For example, the
following code shows the duration of an FLV file:
nStream.onMetaData = function(myMeta) {
trace("FLV duration: " + myMeta.duration + " sec.");
};
This format cannot trace cuePoint metadata information. For information on tracing cue
points, see “Tracing cue points from an FLV file” on page 568.
The reason for this failure is a limitation of the operating system, not a limitation in Flash
or Flash Player.
For an FLV file to play from a non-system drive on a Macintosh, refer to it with an absolute
path using a colon-based notation (:) rather than slash-based notation (/). The following list
shows the difference in the two kinds of notation:
Slash-based notation myDrive/myFolder/myFLV.flv
Colon-based notation (Macintosh) myDrive:myFolder:myFLV.flv
You can also create a projector file for a CD-ROM you intend to use for Macintosh playback.
For the latest information on Macintosh CD-ROMs and FLV files, see http://
www.adobe.com/cfusion/knowledgebase/index.cfm?id=3121b301.
4. Select Control > Test Movie to see the image load and watch the progress bar.
NOT E
If you test this code a second time, the image will be cached and the progress bar will
complete right away. To test multiple times, use different images and load them from
an external source. A local source might cause problems with testing your
application because the content loads too quickly.
For a sample source file that uses scripted animation to create a progress bar animation,
tweenProgress.fla, see the Flash Samples page at www.adobe.com/go/learn_fl_samples.
Download the Samples zip file and navigate to the ActionScript2.0/Tween Progressbar folder
to access this sample.
pb._x = 100;
pb._y = 100;
with (pb.bar_mc) {
beginFill(0x00FF00);
moveTo(0, 0);
lineTo(pb_width, 0);
lineTo(pb_width, pb_height);
lineTo(0, pb_height);
lineTo(0, 0);
endFill();
_xscale = 0;
}
var my_interval:Number;
var my_sound:Sound = new Sound();
my_sound.onLoad = function(success:Boolean) {
if (success) {
trace("sound loaded");
}
};
my_sound.onSoundComplete = function() {
clearInterval(my_interval);
trace("Cleared interval");
}
my_sound.loadSound("http://www.helpexamples.com/flash/sound/song2.mp3",
true);
my_interval = setInterval(updateProgressBar, 100, my_sound);
function updateProgressBar(the_sound:Sound):Void {
var pos:Number = Math.round(the_sound.position / the_sound.duration *
100);
pb.bar_mc._xscale = pos;
pb.vBar_mc._x = pb.bar_mc._width;
pb.pos_txt.text = pos + "%";
}
3. Select Control > Test Movie to load the MP3 file and watch the progress bar.
N OTE
If you test this code a second time, the image will be cached and the progress bar will
complete right away. To test multiple times, use different images and load them from
an external source. A local source might cause problems with testing your
application because the content loads too quickly.
For more information on using sound, see the Sound class entry, Sound, in the ActionScript
2.0 Language Reference.
If your progress bar loads instantly, the video is cached on your hard disk (either from
testing this example already, or loading it in a different procedure). If this occurs,
upload a FLV file to your server and load it instead.
For a sample source file that uses scripted animation to create a progress bar animation,
tweenProgress.fla, see the Flash Samples page at www.adobe.com/go/learn_fl_samples.
Download the Samples zip file and navigate to the ActionScript2.0/Tween Progressbar folder
to access this sample.
589
Sending and loading variables
A SWF file is a window for capturing and displaying information, much like an HTML page.
However, SWF files can stay loaded in the browser and continuously update with new
information without having to reload the entire page. Using ActionScript functions and
methods, you can send information to and receive information from server-side scripts and
receive information from text files and XML files.
In addition, server-side scripts can request specific information from a database and relay it to
a SWF file. Server-side scripts can be written in different languages: some of the most
common are CFML, Perl, ASP (Microsoft Active Server Pages), and PHP. By storing
information in a database and retrieving it, you can create dynamic and personalized content
for your SWF file. For example, you could create a message board, personal profiles for users,
or a shopping cart that keeps track of a user’s purchases.
Several ActionScript functions and methods let you pass information into and out of a SWF
file. Each function or method uses a protocol to transfer information and requires
information to be formatted in a certain way.
■ The functions and MovieClip methods that use the HTTP or HTTPS protocol to send
information in URL-encoded format are getURL(), loadVariables(),
loadVariablesNum(), loadMovie(), and loadMovieNum().
■ The LoadVars methods that use the HTTP or HTTPS protocol to send and load
information in URL-encoded format are load(), send(), and sendAndLoad().
■ The methods that use HTTP or HTTPS protocol to send and load information as XML
are XML.send(), XML.load(), and XML.sendAndLoad().
■ The methods that create and use a TCP/IP socket connection to send and load
information as XML are XMLSocket.connect() and XMLSocket.send().
For more information, see the following topics:
■ “Checking for loaded data” on page 591
■ “Creating a progress bar to display data loading progress” on page 592
If you used the following code, you could not trace the data that is loading:
loadVariables("myData.txt", 0);
trace(lastSiteVisited); // undefined
Each function or method has a specific technique you can use to check data it has loaded. If
you use loadVariables function or loadMovie function, you can load information into a movie
clip target and use the onData handler to execute a script. If you use loadVariables function to
load the data, the onData handler executes when the last variable is loaded. If you use
loadMovie function to load the data, the onData handler executes each time a fragment of the
SWF file is streamed into Flash Player.
For example, the following ActionScript loads the variables from the file myData.txt into the
movie clip loadTarget_mc. An onData() handler assigned to the loadTarget_mc instance
uses the variable lastSiteVisited, which is loaded from the file myData.txt. The following
trace actions appear only after all the variables, including lastSiteVisited, are loaded:
this.createEmptyMovieClip("loadTarget_mc", this.getNextHighestDepth());
this.loadTarget_mc.onData = function() {
trace("Data Loaded");
trace(this.lastSiteVisited);
};
loadVariables("myData.txt", this.loadTarget_mc);
If the remote XML file loads too quickly to see the preloading effect, try uploading a
larger XML file to the internet and loading that file.
this.createEmptyMovieClip("pBar_mc", 9999);
var bar:MovieClip = pBar_mc.createEmptyMovieClip("bar_mc", 10);
bar.beginFill(0xFF0000, 100);
bar.moveTo(0, 0);
bar.lineTo(barWidth, 0);
bar.lineTo(barWidth, barHeight);
bar.lineTo(0, barHeight);
bar.lineTo(0, 0);
bar.endFill();
bar._xscale = 0;
pBar_mc.onEnterFrame = function() {
var pctLoaded:Number = Math.floor(my_xml.getBytesLoaded() /
my_xml.getBytesTotal() * 100);
if (!isNaN(pctLoaded)) {
pBar_mc.bar_mc._xscale = pctLoaded;
pBar_mc.label_txt.text = pctLoaded + "% loaded";
if (pctLoaded >= 100) {
pBar_mc.onEnterFrame = undefined;
}
}
};
The previous code is broken down into seven sections. The first section defines the width
and height of the progress bar when it is drawn on the Stage. The progress bar will be
centered on the Stage in an upcoming section. The next section of code creates two movie
clips, pBar_mc and bar_mc. The bar_mc movie clip is nested inside pBar_mc, and draws a
red rectangle on the Stage. The bar_mc instance modifies its _xscale property as the
external XML file loads from the remote website.
Next, a second movie clip is nested inside of the pBar_mc movie clip, stroke_mc. The
stroke_mc movie clip draws an outline on the Stage that matches the dimensions
specified by the barHeight and barWidth variables defined in the first section. The
fourth section of code creates within the pBar_mc movie clip a text field that is used to
display what percentage of the XML file has already loaded, similar to the label on the
ProgressBar component. Next, the pBar_mc movie clip (which includes the nested
bar_mc, stroke_mc, and label_txt instances) is centered on the Stage.
This example loads variables from the ColdFusion script called high_score.cfm into the movie
clip instance scoreClip using the GET HTTP method.
Any variables loaded with the loadVariables() function must be in the standard MIME
format application/x-www-form-urlencoded (a standard format used by CFM and CGI scripts).
The file you specify in the URL parameter of loadVariables() must write out the variable
and value pairs in this format so that Flash can read them. This file can specify any number of
variables; variable and value pairs must be separated with an ampersand (&), and words within
a value must be separated with a plus (+) sign. For example, the following phrase defines
several variables:
highScore1=54000&playerName1=RGoulet&highScore2=53455&playerName2=
WNewton&highScore3=42885&playerName3=TJones
N OTE
You might need to URL-encode certain characters, such as the plus (+) sign or
ampersand (&) characters. For more information, see www.adobe.com/go/tn_14143.
For more information, see the following topic: “Using the LoadVars class” on page 596. Also,
see loadVariables function, getURL function, loadMovie function, and the LoadVars entry in
the ActionScript 2.0 Language Reference.
You must have ColdFusion installed on your web server for this example.
9. Save the document as sendEmail.fla, and then publish it by selecting File > Publish.
10. Upload sendEmail.swf to the same directory that contains email.cfm (the ColdFusion file
you saved and uploaded in step 2).
11. View and test the SWF file in a browser.
For more information, see the LoadVars entry in the ActionScript 2.0 Language Reference.
Flash Player 8 and later supports the onHTTPStatus event handler for the LoadVars class,
XML class, and MovieClipLoader class to allow users to access the status code from an HTTP
request. This allows developers to determine why a particular load operation may have failed
instead of only being able to determine that a load operation already has failed.
The following example shows how you can use the LoadVars class’s onHTTPStatus event
handler to check whether a text file successfully downloaded from the server and what the
status code returned from the HTTP request was.
The previous code creates a new text field on the Stage and enables text field autosizing.
Next, a LoadVars object is created and two event handlers: onHTTPStatus and onLoad.
The onHTTPStatus event handler (supported in Flash Player 8 and later) is invoked when
a LoadVars.load() or LoadVars.sendAndLoad() operation has completed. The value
passed to the onHTTPStatus event handler function (httpStatus in the previous code)
contains the HTTP status code definition for the current load operation. If the SWF file
was able to successfully load the text file, the value of httpStatus is set to 200 (HTTP
status code for “OK”). If the file didn’t exist on the server, the value of httpStatus is set
to 404 (HTTP status code for “Not Found”). The second event handler,
LoadVars.onLoad(), gets called after the file has finished loading. If the file successfully
loaded, the value of the success parameter is set to true, otherwise the success
parameter is set to false. Finally, the external file is loaded using the LoadVars.load()
method.
3. Select Control > Test Movie to test the Flash document.
Flash displays an error message to the Output panel stating that it was unable to load the
image because it doesn’t exist on the server. The onHTTPStatus event handler traces the
status code of 404 since the file could not be found on the server, and the onLoad event
handler sets the params_txt text field’s text property to “unable to load text file.”
C A U TI O N
If a web server does not return a status code to the Flash Player, the number 0 is
returned to the onHTTPStatus event handler.
Or, you can call the FileReferenceList.browse() method, which opens a dialog box on
the user’s system to prompt the user to select a file to upload and then creates an array of
FileReference objects if the user selects one or more files successfully. Each FileReference
object represents a file selected by the user from the dialog box. A FileReference object does
not contain any data in the FileReference properties (such as name, size, or
modificationDate) until the FileReference.browse() method or
FileReferenceList.browse() method has been called and the user has selected a file from
the file picker or until the FileReference.download() method has been used to select a file
from the file picker.
N OTE
After a successful call to the browse() method, you call FileReference.upload() to upload
one file at a time.
When a dialog box appears on the end-user’s computer, the default location that
appears in the dialog box is the most recently browsed folder (if that location can be
determined) or the desktop (if the recent folder cannot be determined). The
FileReference and FileReferenceList APIs do not let you set the default file location
For information on the functionality and security of the FileReference API, see “About
FileReference API functionality and security” on page 601. For an example of an application
that uses the FileReference API, see “Adding file upload functionality to an application”
on page 602. For a sample source file for this example, FileUpload.fla, see the Flash Samples
page at www.adobe.com/go/learn_fl_samples. Download the Samples zip file and navigate to
the ActionScript2.0/FileUpload folder to access this sample.
For information on each method, property, and event of the FileReference API, see
FileReference (flash.net.FileReference) and FileReferenceList
(flash.net.FileReferenceList) in the ActionScript 2.0 Language Reference.
When allowing users to upload files to a server, you should always be careful to check
the file type before saving the file to the hard disk. For example, you wouldn’t want to
allow a user to upload a server-side script that could be used to delete folders or files on
the server. If you only want to allow users to upload an image file, make sure the server-
side script that uploads the files checks that the file being uploaded is a valid image.
For an example of an application that uses the FileReference API, see “Adding file upload
functionality to an application” on page 602.
The width of the text field should be less than the width of the ScrollPane
instance (400 pixels); otherwise users have to scroll horizontally to view the
error message
9. Right-click the symbol in the Library and select Linkage from the context menu.
10. Select the Export for ActionScript and Export in First Frame check boxes, and type
Message into the Identifier text box. Click OK.
11. Add the following ActionScript to Frame 1 of the Timeline:
N OTE
The code comments include details about the functionality. A code overview follows
this example.
import flash.net.FileReference;
imagePane.setSize(400, 350);
imagePane.move(75, 25);
uploadBtn.move(75, 390);
uploadBtn.label = "Upload Image";
imageLbl.move(75, 430);
imageLbl.text = "Select Image";
statusLbl.move(210, 390);
statusLbl.text = "Status";
/* When the user selects a file, the onSelect() method is called, and
passed a reference to the FileReference object. */
listener.onSelect = function(selectedFile:FileReference):Void {
/* Update the TextArea to notify the user that Flash is attempting to
upload the image. */
statusArea.text += "Attempting to upload " + selectedFile.name + "\n";
/* Upload the file to the PHP script on the server. */
selectedFile.upload("http://www.helpexamples.com/flash/file_io/
uploadFile.php");
};
imagePane.addEventListener("complete", imageDownloaded);
imagesCb.addEventListener("change", downloadImage);
uploadBtn.addEventListener("click", uploadImage);
/* If the image does not download, the event object's total property will
equal -1. In that case, display a message to the user. */
function imageDownloaded(event:Object):Void {
if (event.total == -1) {
imagePane.contentPath = "Message";
}
/* When the user selects an image from the ComboBox, or when the
downloadImage() function is called directly from the
listener.onComplete() method, the downloadImage() function sets the
contentPath of the ScrollPane in order to start downloading the image
to the player. */
function downloadImage(event:Object):Void {
imagePane.contentPath = "http://www.helpexamples.com/flash/file_io/
images/" + imagesCb.value;
}
/* When the user clicks the button, Flash calls the uploadImage()
function, and it opens a file browser dialog box. */
function uploadImage(event:Object):Void {
imageFile.browse([{description: "Image Files", extension:
"*.jpg;*.gif;*.png"}]);
}
This ActionScript code first imports the FileReference class and initializes, positions, and
resizes each of the components on the Stage. Next, a listener object is defined, and three
event handlers are defined: onSelect, onOpen, and onComplete. The listener object is
then added to a new FileReference object named imageFile. Next, event listeners are
added to the imagePane ScrollPane instance, imagesCb ComboBox instance, and
uploadBtn Button instance. Each of the event listener functions is defined in the code
that follows this section of code.
The first function, imageDownloaded(), checks to see if the amount of total bytes for the
downloaded images is -1, and if so, it sets the contentPath for the ScrollPane instance to
the movie clip with the linkage identifier of Message, which you created in a previous step.
The second function, downloadImage(), attempts to download the recently uploaded
image into the ScrollPane instance. When the image has downloaded, the
imageDownloaded() function defined earlier is triggered and checks to see whether the
image successfully downloaded. The final function, uploadImage(), opens a file browser
dialog box, which filters all JPEG, GIF, and PNG images.
12. Save your changes to the document.
13. Select File > Publish settings and then select the Formats tab, and make sure that Flash and
HTML are both selected.
14. (Optional) In the Publish Settings dialog box, select the Flash tab, and then select Access
Network Only from the Local Playback Security pop-up menu.
If you complete this step, you won’t run into security restrictions if you test your
document in a local browser.
15. In the Publish Settings dialog box, click Publish to create the HTML and SWF files.
This PHP code first defines two constant variables: $MAXIMUM_FILESIZE and
$MAXIMUM_FILE_COUNT. These variables dictate the maximum size (in kilobytes) of an
image being uploaded to the server (200KB), as well as how many recently uploaded files
can be kept in the images folder (10). If the file size of the image currently being uploaded
is less than or equal to the value of $MAXIMUM_FILESIZE, the image is moved to the
temporary folder.
Next, the file type of the uploaded file is checked to ensure that the image is a JPEG, GIF,
or PNG. If the image is a compatible image type, the image is copied from the temporary
folder to the images folder. If the uploaded file wasn’t one of the allowed image types, it is
deleted from the file system.
Next, a directory listing of the image folder is created and looped over using a while loop.
Each file in the images folder is added to an array and then sorted. If the current number
of files in the images folder is greater than the value of $MAXIMUM_FILE_COUNT, files are
deleted until there are only $MAXIMUM_FILE_COUNT images remaining. This prevents the
images folder from growing to an unmanageable size, as there can be only 10 images in the
folder at one time, and each image can only be 200KB or smaller (or roughly 2 MB of
images at any time).
3. Save your changes to the PHP document.
4. Upload the SWF, HTML, and PHP files to your web server.
5. View the remote HTML document in a web browser, and click the Upload Image button
in the SWF file.
6. Locate an image file on your hard disk and select Open from the dialog box.
The SWF file uploads the image file to the remote PHP document, and displays it in the
ScrollPane (which adds scroll bars if necessary). If you want to view a previously uploaded
image, you can select the filename from the ComboBox instance on the Stage. If the user
tries to upload an image that isn’t an allowed image type (only a JPEG, GIF, or PNG
image is allowed) or the file size is too big (over 200 KB), Flash displays the error message
from the Message movie clip in the Library.
For a sample source file for this example, FileUpload.fla, see the Flash Samples page at
www.adobe.com/go/learn_fl_samples. Download the Samples zip file and navigate to the
ActionScript2.0/FileUpload folder to access this sample.
About XML
Extensible Markup Language (XML) is becoming the standard for exchanging structured data
in Internet applications. You can integrate data in Flash with servers that use XML technology
to build sophisticated applications, such as chat or brokerage systems.
In XML, as with HTML, you use tags to specify, or mark up, a body of text. In HTML, you
use predefined tags to indicate how text should appear in a web browser (for example, the <b>
tag indicates that text should be bold). In XML, you define tags that identify the type of a
piece of data (for example, <password>VerySecret</password>). XML separates the
structure of the information from the way it appears, so the same XML document can be used
and reused in different environments.
Every XML tag is called a node, or an element. Each node has a type (1, which indicates an
XML element, or 3, which indicates a text node), and elements might also have attributes. A
node nested in a node is called a child node. This hierarchical tree structure of nodes is called
the XML DOM—much like the JavaScript DOM, which is the structure of elements in a
web browser.
In the following example, <portfolio> is the parent node; it has no attributes and contains
the child node <holding>, which has the attributes symbol, qty, price, and value:
<portfolio>
<holding symbol="rich"
qty="75"
price="245.50"
value="18412.50" />
</portfolio>
■ The load() method downloads XML from a URL and places it in an ActionScript
XML object.
■ The send()method encodes the XML object into an XML document and sends it to a
specified URL using the POST method. If specified, a browser window displays
returned data.
■ The sendAndLoad() method sends an XML object to a URL. Any returned information
is placed in an ActionScript XML object.
For example, you could create a brokerage system that stores all its information (user names,
passwords, session IDs, portfolio holdings, and transaction information) in a database.
The flow and conversion of data between a SWF file, a server-side script, and a database
The password validation for the brokerage system requires two scripts: a function defined on
Frame 1, and a script that creates and then sends the XML objects created in the document.
When a user enters information into text fields in the SWF file with the variables username
and password, the variables must be converted to XML before being passed to the server. The
first section of the script loads the variables into a newly created XML object called loginXML.
When a user clicks a button to log in, the loginXML object is converted to a string of XML
and sent to the server.
The server receives the XML, generates an XML response, and sends it back to the SWF file.
If the password is accepted, the server responds with the following:
<LOGINREPLY STATUS="OK" SESSION="4D968511" />
This XML includes a session attribute that contains a unique, randomly generated session
ID, which is used in all communications between the client and server for the rest of the
session. If the password is rejected, the server responds with the following message:
<LOGINREPLY STATUS="FAILURE" />
The loginreply XML node must load into a blank XML object in the SWF file. The
following statement creates the XML object loginreplyXML to receive the XML node:
// Construct an XML object to hold the server's reply
var loginReplyXML:XML = new XML();
loginReplyXML.onLoad = function(success:Boolean) {
The second statement in this ActionScript defines an anonymous (inline) function, which is
called when the onLoad event triggers.
The login button (login_btn instance) is used to send the user name and password as XML
to the server and to load an XML response back into the SWF file. You can use the
sendAndLoad() method to do this, as shown in the following example:
loginXML.sendAndLoad("http://www.flash-mx.com/mm/main.cfm", loginReplyXML);
This function must always be on the frame that contains the ActionScript for the login
button.
If the login is successful, the SWF file progresses to the welcome frame label. If the login is not
successful, then the playhead moves to the loginfailure frame label. This is processed using
a condition and case statement.
The CFM file contains the following code:
<cfif (Compare(Form.username, "Herbert") EQ 0) AND (Compare(Form.password,
"glasses") EQ 0)>
<cfoutput>&isValidLogin=1&session=#URLEncodedFormat(CreateUUID())#</
cfoutput>
<cfelse>
<cfoutput>&isValidLogin=0</cfoutput>
</cfif>
For more information on case and break statements, see case statement and break statement in
the ActionScript 2.0 Language Reference. For more information on conditions, see if statement
and else statement in the ActionScript 2.0 Language Reference.
N OTE
This design is only an example, and Adobe makes no claims about the level of security it
provides. If you are implementing a secure password-protected system, make sure you
have a good understanding of network security.
For more information, see Integrating XML and Flash in a Web Application at http://
www.adobe.com/support/flash/applications/xml/ and the XML entry in the ActionScript 2.0
Language Reference. For more information on local file security, see “About local file security
and Flash Player” on page 633.
For a sample source file, login.fla, that shows how to add simple login functionality to your
websites using ActionScript 2.0, see the Flash Samples page at www.adobe.com/go/
learn_fl_samples. Download the Samples zip file and navigate to the ActionScript2.0/Login
folder to access this sample. The sample uses ActionScript and components to create a small
form in which you enter a user name and password and then click a button to enter a site.
The previous code defines a new XML object with the variable name my_xml, defines two
event handlers (onHTTPStatus and onLoad), and loads an external XML file. The onLoad
event handler checks to see whether the XML file was successfully loaded and if so sends a
message to the Output panel as well as traces the XML object’s status property. It is
important to remember that the onHTTPStatus event listener returns the status code
returned from the web server, whereas the XML.status property contains a numeric value
that indicates whether the XML object was able to be parsed successfully.
Don’t confuse the HTTP httpStatus codes with the XML class’s status property. The
onHTTPStatus event handler returns the server’s status code from an HTTP request
and the status property automatically sets and returns a numeric value that indicates
whether an XML document was successfully parsed into an XML object.
CA UT ION
If a web server does not return a status code to the Flash Player, the number 0 is
returned to the onHTTPStatus event handler.
For a source sample file that demonstrates how to create a web log tracker by loading, parsing,
and manipulating XML data, xml_blogTracker.fla, see the Flash Samples page at
www.adobe.com/go/learn_fl_samples. Download the Samples zip file and navigate to the
ActionScript2.0/XML_BlogTracker folder to access this sample.
For a source sample file that demonstrates how to use XML and nested arrays to select strings
of different languages to populate text fields, xml_languagePicker.fla, see the Flash Samples
page at www.adobe.com/go/learn_fl_samples. Download the Samples zip file and navigate to
the ActionScript2.0/XML_LanguagePicker folder to access this sample.
For a source sample file that demonstrates how to create a dynamic menu with XML data,
xmlmenu.fla, see the Flash Samples page at www.adobe.com/go/learn_fl_samples. Download
the Samples zip file and navigate to the ActionScript2.0/XML_Menu folder to access this
sample. The sample calls the ActionScript XmlMenu() constructor and passes it two
parameters: the path to the XML menu file and a reference to the current timeline. The rest of
the functionality resides in a custom class file, XmlMenu.as.
The XMLSocket class cannot tunnel through firewalls automatically because, unlike the
Real-Time Messaging Protocol (RTMP), XMLSocket has no HTTP tunneling capability.
If you need to use HTTP tunneling, consider using Flash Remoting or Flash Media
Server (which supports RTMP) instead.
You can use the connect() and send() methods of the XMLSocket class to transfer XML to
and from a server over a socket connection. The connect() method establishes a socket
connection with a web server port. The send() method passes an XML object to the server
specified in the socket connection.
When you invoke the connect() method, Flash Player opens a TCP/IP connection to the
server and keeps that connection open until one of the following events happens:
■ The close() method of the XMLSocket class is called.
■ No more references to the XMLSocket object exist.
■ Flash Player exits.
■ The connection is broken (for example, the modem disconnects).
The following example creates an XML socket connection and sends data from the XML
object myXML. To understand the script, read the commented lines (indicated by the characters
//):
// Create XMLSocket object
var theSocket:XMLSocket = new XMLSocket();
// Connect to a site on unused port above 1024 using connect() method.
// Enter localhost or 127.0.0.1 for local testing.
// For live server, enter your domain www.yourdomain.com
theSocket.connect("localhost", 12345);
// displays text regarding connection
theSocket.onConnect = function(myStatus) {
For more information, see the XMLSocket entry in the ActionScript 2.0 Language Reference.
For more information on local file security, see “About local file security and Flash Player”
on page 633.
The External API is a replacement for fscommand() in Flash 8 and later for interoperating
with a HTML page or a container application. The External API offers more robust
functionality than fscommand() in this situation. For more information, see “About the
External API” on page 621.
You use the fscommand() function to send a message to whichever program is hosting
Flash Player, such as a web browser.
N OTE
Using the fscommand() to call JavaScript does not work on the Safari or Internet Explorer
browsers for the Macintosh.
The fscommand() function has two parameters: command and arguments. To send a message
to the stand-alone version of Flash Player, you must use predefined commands and
arguments. For example, the following event handler sets the stand-alone player to scale the
SWF file to the full monitor screen size when the button is released:
my_btn.onRelease = function() {
fscommand("fullscreen", true);
};
The following table shows the values you can specify for the command and arguments
parameters of fscommand() to control the playback and appearance of a SWF file playing in
the stand-alone player, including projectors.
NOT E
A projector is a SWF file saved in a format that can run as a stand-alone application—that
is, embedding Flash Player with your content in an executable file.
To use fscommand() to open a message box from a SWF file in the HTML page
through JavaScript:
1. Create a new FLA file, and save it as myMovie.fla.
2. Drag two instances of the Button component to the Stage and give them the instance
names window_btn and alert_btn, respectively, and the labels Open Window and Alert.
3. Insert a new layer on the Timeline, and rename it Actions.
4. Select Frame 1 of the Actions layer, and add the following ActionScript in the
Actions panel:
window_btn.onRelease = function() {
fscommand("popup", "http://www.adobe.com/");
};
alert_btn.onRelease = function() {
fscommand("alert", "You clicked the button.");
};
5. Select File > Publish Settings, and make sure that Flash with FSCommand is selected in the
Template menu on the HTML tab.
6. Select File > Publish to generate the SWF and HTML files.
This functionality replaces the older fscommand() function for interoperating with a HTML
page or a container application. The External API offers more robust functionality than
fscommand() in this situation. For more information, see “About the External API”
on page 621.
send_button.addEventListener("click", clickListener);
function clickListener(eventObj:Object):Void {
trace("click > " + out_ti.text);
ExternalInterface.call("jsFunc", out_ti.text);
}
The previous code is split into three sections. The first section imports the
ExternalInterface class so you don’t have to use its fully qualified class name. The second
section of code defines a callback function, asFunc(), which is called from JavaScript in
an HTML document created in an upcoming example. This function sets the text within
a TextInput component on the Stage. The third section of code defines a function and
assigns it as an event listener for when the user clicks the Button component instance on
the Stage. Whenever the button is clicked, the SWF file calls the jsFunc() JavaScript
function in the HTML page and passes the text property of the out_ti text input
instance.
7. Select File > Publish Settings and then select the Formats tab and make sure that Flash and
HTML are both selected.
8. Click Publish to create the HTML and SWF files.
When you’re finished, go on to the next procedure to create the container for the
SWF file.
function makeCall(str) {
thisMovie("extint").asFunc(str);
}
function jsFunc(str) {
document.inForm.inField.value = "AS > Hello " + str;
}
// -->
</script>
This JavaScript code defines three methods. The first method returns a reference to the
embedded SWF file based on whether the user’s browser is Microsoft Internet Explorer
(IE) or a Mozilla browser. The second function, makeCall(), calls the asFunc() method
that you defined within the Flash document in the previous example. The "extint"
parameter in the thisMovie() function call refers to the object ID and embed name of
the embedded SWF file. If you saved your Flash document with a different name, you
need to change this string to match the values in the object and embed tags. The third
function, jsFunc(), sets the value of the inField text field in the HTML document.
This function is called from the Flash document when a user clicks the send_button
Button component.
4. Add the following HTML code before the closing </body> tag:
<form name="outForm" method="POST"
action="javascript:makeCall(document.outForm.outField.value);">
Sending to AS:<br />
<input type="text" name="outField" value="" /><br />
<input type="submit" value="Send" />
</form>
This HTML code creates two HTML forms similar to the forms created in the Flash
environment in the previous exercise. The first form submits the value of the outField
text field to the makeCall() JavaScript function defined in an earlier step. The second
form is used to display a value that gets sent from the SWF file when the user clicks the
send_button instance.
5. Save the HTML document and upload both the HTML and SWF files to a web server.
6. View the HTML file in a web browser, enter a string in the out_ti TextInput instance,
and click the Send button.
Flash calls the jsFunc() JavaScript function and passes the contents of the out_ti text
field, which displays the contents in the HTML form inForm inField input text field.
7. Type a value into the outField HTML text field and click the Send button.
Flash calls the SWF file’s asFunc() function, which displays the string in the in_ti
TextInput instance.
For a sample source file, ExtInt.fla, see the Flash Samples page at www.adobe.com/go/
learn_fl_samples. Download the Samples zip file and navigate to the ActionScript2.0/
ExternalAPI folder to access this sample.
For a more complex example that uses the External API, see “Controlling Flash Video with
the External API” on page 625. For more information on local file security, see “About local
file security and Flash Player” on page 633.
N OTE
function playVideo(url:String):Void {
video_ns.play(url);
}
function pauseResume():Void {
video_ns.pause();
}
The first part of this ActionScript code defines two ExternalInterface callback functions,
playVideo() and pauseResume(). These functions are called from the JavaScript in the
next procedure. The second part of the code creates a new NetConnection and NetStream
object, which you use with the video instance to dynamically play back FLV files.
Review the code comments in the following example. A code overview follows this
code example.
<script language="JavaScript">
// Use a variable to reference the embedded SWF file.
var flashVideoPlayer;
/* When the HTML page loads (through the onLoad event of the <body>
tag), it calls the initialize() function. */
function initialize() {
/* Check whether the browser is IE. If so, flashVideoPlayer is
window.videoPlayer. Otherwise, it's document.videoPlayer. The
videoPlayer is the ID assigned to the <object> and <embed> tags. */
var isIE = navigator.appName.indexOf("Microsoft") != -1;
flashVideoPlayer = (isIE) ? window['videoPlayer'] :
document['videoPlayer'];
}
/* When the user clicks the play button in the form, update the
videoStatus text area, and call the playVideo() function within the
SWF file, passing it the URL of the FLV file. */
function callFlashPlayVideo() {
var comboBox = document.forms['videoForm'].videos;
var video = comboBox.options[comboBox.selectedIndex].value;
updateStatus("____" + video + "____");
flashVideoPlayer.playVideo("http://www.helpexamples.com/flash/
video/" + video);
}
/* The updateStatus() function is called from the SWF file from the
onStatus() method of the NetStream object. */
function updateStatus(message) {
document.forms['videoForm'].videoStatus.value += message + "\n";
}
</script>
</head>
<body bgcolor="#ffffff" onLoad="initialize();">
<form name="videoForm">
Select a video:<br />
<select name="videos">
<option value="lights_long.flv">lights_long.flv</option>
<option value="clouds.flv">clouds.flv</option>
<option value="typing_long.flv">typing_long.flv</option>
<option value="water.flv">water.flv</option>
</select>
<input type="button" name="selectVideo" value="play"
onClick="callFlashPlayVideo();" />
<br /><br />
</body>
</html>
For more information on local file security, see “About local file security and Flash Player”
on page 633.
NO TE
Understanding Security 16
In Flash CS3 Professional, you can use ActionScript to load data from external sources into a
SWF file or send data to a server. When you load data into a SWF file, you need to
understand and accommodate the Flash security model. When you open a SWF file on your
hard disk, you might need to make special configurations so you can test your file locally.
For information on local file security, see “About local file security and Flash Player”
on page 633. For information on the changes between the Flash Player 7 and Flash Player 8
and later security models, see “About compatibility with previous Flash Player security
models” on page 631. For information on how to load and parse data from a server, read
Chapter 15, “Working with External Data,” on page 589. For more information on security,
see www.adobe.com/devnet/security and www.adobe.com/software/flashplayer/security/.
For more information on security in Flash 8 and later, see the following topics:
About compatibility with previous Flash Player security models . . . . . . . . . . . . . . . 631
About local file security and Flash Player . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .633
Restricting networking APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .648
Server-side policy files for permitting access to data. . . . . . . . . . . . . . . . . . . . . . . . . 657
HTTP to HTTPS protocol access between SWF files. . . . . . . . . . . . . . . . . . . . . . . .662
631
In Flash Player 7 and later, if a version 6 (or earlier) SWF file attempts to load data from a
server that resides in another domain, and that server doesn’t provide a policy file that allows
reading from that SWF file’s domain, the Flash Player Settings dialog box appears. The dialog
box asks the user to allow or deny the cross-domain data access.
If the user clicks Allow, the SWF file can access the requested data; if the user clicks Deny, the
SWF file cannot access the requested data.
To prevent this dialog box from appearing, you should create a security policy file on the
server providing the data. For more information, see “Allowing cross-domain data loading”
on page 658.
Flash Player 7 and later do not allow cross-domain access without a security policy file.
Flash Player 8 and later changed the way it handles System.security.allowDomain. A Flash
SWF file (Flash 8 and later) that calls System.security.allowDomain with any argument,
or any other SWF file that uses the wildcard (*) value, permits access only to itself. There is
now support for a wildcard (*) value, for example: System.security.allowDomain("*")
and System.security.allowInsecureDomain("*"). If a SWF file of version 7 or earlier
calls System.security.allowDomain or System.security.allowInsecureDomain with an
argument other than wildcard (*), this will affect all SWF files of version 7 or lower in the
calling SWF file’s domain, as it did in Flash Player 7. However, this kind of call does not affect
any Flash Player 8 (or later) SWF files in the calling SWF file’s domain. This helps minimize
legacy content breaking in Flash Player.
For more information, see “Restricting networking APIs” on page 648, allowDomain
(security.allowDomain method), and allowInsecureDomain (security.allowInsecureDomain
method).
Flash Player 8 and later does not allow local SWF files to communicate with the Internet
without a specific configuration on your computer. Suppose you have legacy content that was
published before these restrictions were in effect. If that content tries to communicate with
the network or local file system, or both, Flash Player stops the operation, and you must
explicitly provide permission for the application to work properly. For more information, see
“About local file security and Flash Player” on page 633
The restrictions that are discussed in this section do not affect SWF files that are on the
Internet.
When you create a FLA file, you can indicate whether a SWF file is allowed to communicate
with a network or with a local file system. In previous versions of Flash Player (7 and earlier),
local SWF files could interact with other SWF files and load data from any remote or local
location. In Flash Player 8 and later, a SWF file cannot make connections to the local file
system and the Internet. This is a safety change, so a SWF file cannot read files on your hard
disk and then send the contents of those files across the Internet.
This security restriction affects all locally deployed content, whether it is legacy content (a
FLA file created in an earlier version of Flash) or created in Flash 8 and later. Suppose you
deploy a Flash application, using Flash MX 2004 or earlier, that runs locally and also accesses
the Internet. In Flash Player 8 and later, this application now prompts the user for permission
to communicate with the Internet.
When you test a file on your hard disk, there are a series of steps to determine whether the file
is a local trusted document or a potentially untrusted document. If you create the file in the
Flash authoring environment (for example, when you select Control > Test Movie), your file
is trusted because it is in a test environment.
In Flash Player 7 and earlier, local SWF files had permissions to read from both a local file
system and the network (such as the Internet). In Flash Player 8 and later, local SWF files can
have the following levels of permission:
Access the local file system only (default) A local SWF file can read from the local file
system and universal naming convention (UNC) network paths but cannot communicate
with the Internet. For more information on local file access SWF files, see “Access local files
only (default)” on page 640.
Access the network only A local SWF file can access the network (such as the Internet)
but not the local file system where it is installed. For more information on network-only SWF
files, see “Access network only” on page 641.
Local-with-file-system
For security purposes, Flash Player places all local SWF files, including all legacy local SWF
files, in the local-with-file-system sandbox, by default (unless some other setting is made). For
some legacy SWF files (Flash Player 7 and earlier), operations could be affected by enforcing
restrictions on their access (no outside network access), but this provides the most secure
default for the users’ protection.
From this sandbox, SWF files may read from files on local file systems or UNC network paths
(by using the XML.load() method, for example), but they may not communicate with the
network in any way. This assures the user that local data cannot be leaked out to the network
or otherwise inappropriately shared.
Local-trusted
SWF files assigned to the local-trusted sandbox can interact with any other SWF files, and
load data from anywhere (remote or local).
Click Settings to access the Global Security Settings panel, where you can specify that
certain Flash applications on your computer may communicate with the Internet.
To change your security settings or learn more about your options, you use the Global
Security Settings panel. Use this panel to reset the privacy settings in Adobe Flash Player:
■ If you select Always Deny and then confirm your selection, any website that tries to use
your camera or microphone is denied access. You are not asked again whether a website
can use your camera or microphone. This action applies both to websites you have already
visited and to those you haven’t yet visited.
■ If you select Always Ask and then confirm your selection, any website that tries to use your
camera or microphone must ask your permission. This action applies both to websites you
have already visited and to those you haven’t yet visited.
After you select either Always Ask or Always Deny (or instead of doing so), you can specify
privacy settings for individual websites that you have already visited. For example, you might
select Always Deny here, then use the Website Privacy Settings panel and select Always Allow
for individual websites that you know and trust.
For locally deployed content and local data, users have another option: They can specify
which SWF files may access the Internet using the Global Security Settings panel. For more
information on specifying settings in the Global Security Settings panel, see “Specifying
trusted files using the Settings Manager” on page 642. For more information on the Global
Security Settings panel, see www.adobe.com/support/documentation/en/flashplayer/help/
settings_manager04a.html.
NO TE
The selections users make in the Global Security Settings panel override any decisions
made in the security pop-up dialog box.
To fix SWF files for local playback, use any of the following options:
Redeploy Run the Local Content Updater. The Local Content Updater reconfigures your
SWF file to make it compatible with the security model (for Flash Player 8 and later). You
reconfigure the local SWF file so it can either access only the network or only the local file
system. For more information, and to download the Local Content Updater, see
www.adobe.com/support/flashplayer/downloads.html.
Any of these options require that you either republish or redeploy your SWF file.
If you specify network access for a local file, you must also enable permissions in the
SWF, HTML, data, and server files that are accessed by the local SWF file.
Network SWF files SWF files that download from a network (such as an online server) are
placed in a separate sandbox that corresponds to their unique website origin domains. Local
SWF files that specify they have network access are placed in the local-with-networking
sandbox. By default, these files can read data from only the same site from which they
originated. Exact-domain matching applies to these files. Network SWF files can access data
from other domains if they have the proper permissions. For more information on network
SWF files, see “Access network only” on page 641.
To specify that a local SWF file can communicate with the Internet and local
file system:
1. In the Global Security Settings panel, click the pop-up menu and select Add Location.
The Add Location box opens.
If you arrived at the Settings Manager by clicking the Settings button in a dialog box, the
Add Location box contains a path that is similar to C:\directoryname\filename.swf or /
Users/directoryname/filename.swf; this path tells you which file tried to communicate with
the Internet and was stopped by Flash Player security. If the path contains the content that
you want to let communicate with the Internet, copy and paste the path into the Trust
This Location box. Or, click one of the Browse buttons and find the content yourself.
If the FlashAuthor.cfg file is deleted, the file is recreated when you launch the Flash
authoring tool.
In the #Security directory on your hard disk, you can create a FlashPlayerTrust directory
where you can store unique configuration files. Inside these files, you can specify directories or
applications to trust on your hard disk. This directory does not require administrative access,
so users without administrative permissions can set permissions for SWF files and test
applications.
If you do not specify a directory, your content might not function as intended. Configuration
files inside a FlashPlayerTrust directory contain directory paths. The file can contain a list of
several directories, and you can append new paths to the file. Flash Player expects one path per
line in configuration files. Any line that begins with a # punctuator (with no leading space
before it) is treated as a comment.
You should develop a unique naming scheme to avoid conflicts with other applications that
might install files in this directory. For example, you might want to use your unique company
and software name in the filename to avoid conflicts.
TIP
If you do not want to use configuration files, you could publish your Flash applications to
a separate, testing server instead of providing clients or other developers SWF files to
run on their local hard disks.
These files include legacy content that plays in Flash Player 8 and later. If you are developing
content in Flash CS3, or you have content that falls into one of the following categories, you
(or your users) should register the file as trusted. For information on registering a file as
trusted, see “Specifying trusted files using the Settings Manager” on page 642. For
information on granting permission for local file playback using configuration files, see
“Creating configuration files for Flash development” on page 644.
Local-with-file-system SWF files have the following restrictions:
■ Cannot access the network, which includes the following:
■ Loading other SWF files from the network (except using non-Internet UNC paths)
■ Sending HTTP requests
■ Making connections using XMLSocket, Flash Remoting, or NetConnection
■ Calling getURL() except if you use getURL("file:...") or getURL("mailto:...")
Local-with-file-system SWF files have read access to known files on the local file system.
For example, you can use XML.load() in a local-with-file-system SWF file as long as you
load from the local file system and not the Internet.
■ Local-with-file-system SWF files cannot communicate with HTML pages, which includes
the following:
■ Inbound scripting (such as ExternalInterface API, ActiveX, LiveConnect, and
XPConnect)
■ Outbound scripting (such as custom fscommand calls, and
getURL("javascript:..."))
N OTE
In addition to the previous APIs, the following APIs are prevented when allowNetworking is
set to "none":
■ XML.load
■ XML.send
■ XML.sendAndLoad
■ LoadVars.load()
■ LoadVars.send
■ LoadVars.sendAndLoad
■ loadVariables
■ loadVariablesNum
■ MovieClip.loadVariables
■ NetConnection.connect
■ NetStream.play
■ loadMovie
■ loadMovieNum
■ MovieClip.loadMovie
■ MovieClipLoader.loadClip
Even if the selected allowNetworking setting permits a SWF file to use a networking API,
there may be other restrictions based on security sandbox limitations, as described in this
chapter.
When allowNetworking is set to "none", an <img> tag in the htmlText property of a
TextField does not display network content.When allowNetworking is set to "none", a
symbol from an imported shared library added in the Flash authoring tool (not ActionScript)
is prevented at run time.
www.adobe.com www.adobe.com
data.adobe.com data.adobe.com
65.57.83.12 65.57.83.12
www.adobe.com data.adobe.com
adobe.com www.adobe.com
www.adobe.com adobe.com
Flash Player 8 and later does not allow local SWF files to communicate with the Internet
without a proper configuration. For information on setting up a configuration file to test
content locally, see “Creating configuration files for Flash development” on page 644.
For more information on security, see www.adobe.com/devnet/security/ and
www.adobe.com/software/flashplayer/security/.
For more information, see the following topics:
■ “Domain name rules for settings and local data” on page 651
■ “Cross-domain and subdomain access between SWF files” on page 652
■ “Allowing cross-domain data loading” on page 658
The following issue affects only SWF files published for Flash Player 7. When the receiver is
HTTPS, and the sender is a local SWF file, allowDomain() is called, even though
allowInsecureDomain() should be called. However, in Flash Player 8 and later, when an
HTTPS LocalConnection receiver is Flash Player 8 and later, and the sender is a local file,
allowInsecureDomain() is called.
You might encounter a situation when you load a child SWF file from a different domain
than the one calling it. You might want to allow that file to script the parent SWF file, but you
don’t know the final domain from which the child SWF file will come. This situation can
happen, for example, when you use load-balancing redirects or third-party servers. In this
situation, you can use the MovieClip._url property as an argument to this method. For
example, if you load a SWF file into my_mc, you can call
System.security.allowDomain(my_mc._url). If you do this, you must wait until the SWF
file in my_mc begins loading because the _url property does not have its final, correct value
yet. To determine when a child SWF file has started to load, use
MovieClipLoader.onLoadStart.
The opposite situation can also occur; that is, you might create a child SWF file that wants to
allow its parent to script it, but doesn’t know what the domain of its parent SWF file will be
(meaning, it’s a SWF file that might be loaded by a variety of domains). In this situation, call
System.security.allowDomain(_parent._url) from the child SWF file. You don’t have
to wait for the parent SWF file to load because it is loaded before the child file loads.
NOT E
If the Internet SWF file being accessed is loaded from an HTTPS URL, the Internet SWF
file must call System.security.allowInsecureDomain("*").
The versions that control the behavior of Flash Player are SWF file versions (the specified
Flash Player version of a SWF file), not the version of Flash Player itself. For example, when
Flash Player 8 and later is playing a SWF file published for version 7, Flash Player applies
behavior that is consistent with version 7. This practice ensures that player upgrades do not
change the behavior of System.security.allowDomain() in deployed SWF files.
Because Flash Player 7 and later versions implement exact-domain matching rules instead of
superdomain matching rules, you might have to modify existing scripts if you want to read
them from files that are published for Flash Player 7 and later. (You can still publish the
modified files for Flash Player 6.) If you used any LocalConnection.allowDomain() or
System.security.allowDomain() statements in your files and specified superdomain sites
to permit, you must change your parameters to specify exact domains instead. The following
example shows changes you might have to make if you have Flash Player 6 code:
// Flash Player 6 commands in a SWF file at www.helpexamples.com
// to allow access by SWF files that are hosted at www.adobe.com
// or at store.adobe.com
System.security.allowDomain("adobe.com");
my_lc.allowDomain = function(sendingDomain) {
return(sendingDomain=="adobe.com");
}
// Corresponding commands to allow access by SWF files
// that are published for Flash Player 7 or later
System.security.allowDomain("www.adobe.com", "store.adobe.com");
my_lc.allowDomain = function(sendingDomain) {
return(sendingDomain=="www.adobe.com" ||
You might also have to add statements such as these to your files if you aren’t currently using
them. For example, if your SWF file is hosted at www.adobe.com and you want to allow
access by a SWF file published for Flash Player 7 or later at store.adobe.com, you must add
statements such as the following example to the file at www.adobe.com (you can still publish
the file at www.adobe.com for Flash Player 6):
System.security.allowDomain("store.adobe.com");
my_lc.allowDomain = function(sendingDomain) {
return(sendingDomain=="store.adobe.com");
}
In addition, consider that if a Flash Player 6 application running in Flash Player 7 tries to
access data outside its exact domain, Flash Player 7 and later domain-matching rules are
enforced and the user is prompted to allow or deny access.
To summarize, you might have to modify your files to add or change allowDomain statements
if you publish files for Flash Player 7 or later that meet the following conditions:
■ You implemented cross-SWF file scripting (see “Allowing data access between cross-
domain SWF files” on page 656).
■ The called SWF file (of any version) is not hosted at a site using a secure protocol
(HTTPS), or the calling and called SWF files are both hosted at HTTPS sites. (If only the
called SWF file is HTTPS, see “HTTP to HTTPS protocol access between SWF files”
on page 662.)
■ The SWF files are not in the same domain (for example, one file is at www.adobe.com and
one is at store.adobe.com).
You must make the following changes:
■ If the called SWF file is published for Flash Player 7 or later, include
System.security.allowDomain or LocalConnection.allowDomain in the called SWF
file, using exact domain-name matching.
■ If the called SWF file is published for Flash Player 6, modify the called file to add or
change a System.security.allowDomain or LocalConnection.allowDomain
statement, using exact domain-name matching, as shown in the code examples earlier in
this section. You can publish the modified file for either Flash Player 6 or 7.
■ If the called SWF file is published for Flash Player 5 or earlier, port the called file to
Flash Player 6 or 7 and add a System.security.allowDomain statement, using exact
domain-name matching, as shown in the code examples earlier in this section.
(LocalConnection objects aren’t supported in Flash Player 5 or earlier.)
However, data.swf can grant access to SWF files served from www.adobe.com by using the
LocalConnection.allowDomain handler and the System.security.allowDomain()
method, depending on the type of access required. The following code, added to data.swf,
allows a SWF file served from www.adobe.com to access its variables and methods:
// Within data.swf
this._lockroot = true;
System.security.allowDomain("www.adobe.com");
var my_lc:LocalConnection = new LocalConnection();
my_lc.allowDomain = function(sendingDomain:String):Boolean {
return (sendingDomain == "www.adobe.com");
};
function getData():Void {
var timestamp:Date = new Date();
output_txt.text += "data.swf:" + timestamp.toString() + "\n\n";
}
output_txt.text = "**INIT**:\n\n";
Now the getData function in the loaded SWF file can be called by the adobe.swf file. Notice
that allowDomain permits any SWF file in the allowed domain to script any other SWF file
in the domain permitting the access, unless the SWF file being accessed is hosted on a site
using a secure protocol (HTTPS).
For more information on domain-name matching, see “Cross-domain and subdomain access
between SWF files” on page 652.
You can also permit access to documents originating from any domain, as shown in the
following example:
<?xml version="1.0"?>
<!-- http://www.adobe.com/crossdomain.xml -->
<cross-domain-policy>
<allow-access-from domain="*" />
</cross-domain-policy>
Each <allow-access-from> tag also has the optional secure attribute. The secure
attribute defaults to true. You can set the attribute to false if your policy file is on an
HTTPS server, and you want to allow SWF files on an HTTP server to load data from the
HTTPS server.
Setting the secure attribute to false could compromise the security offered by HTTPS.
If the SWF file you are downloading comes from an HTTPS server, but the SWF file loading
it is on an HTTP server, you need to add the secure="false" attribute to the <allow-
access-from> tag, as shown in the following code:
<allow-access-from domain="www.adobe.com" secure="false" />
If your SWF file relies on loadPolicyFile, visitors with Flash Player 6 or earlier or Flash
Player 7 (7.0.19.0) or later do not have problems. However, visitors with Flash Player 7
(7.0.14.0) do not have support for loadPolicyFile.
If you want to use a policy file in a custom location on the server, you must call
System.security.loadPolicyFile before you make any requests that depend on the policy
file, such as the following:
System.security.loadPolicyFile("http://www.adobe.com/folder1/folder2/
crossdomain.xml");
var my_xml:XML = new XML();
my_xml.load("http://www.adobe.com/folder1/folder2/myData.xml");
Any permissions granted by the policy file at that location apply to all content at the same
level or below in the server’s hierarchy. Therefore, if you try to load the following data, you
discover you can only load data from certain locations:
myLoadVars.load("http://www.adobe.com/folder/vars.txt"); // allowed
myLoadVars.load("http://www.adobe.com/folder/dir/vars2.txt"); // allowed
myLoadVars.load("http://www.adobe.com/elsewhere/vars3.txt"); // not allowed
To work around this, you can load more than one policy file into a single SWF file using
loadPolicyFile. Flash Player always waits for the completion of any policy file downloads
before denying a request that requires a policy file. Flash Player consults the default location of
crossdomain.xml if no other policies were authorized in the SWF file.
Special syntax allows policy files to be retrieved directly from an XMLSocket server:
System.security.loadPolicyFile("xmlsocket://adobe.com:414");
In this example, Flash Player tries to retrieve a policy file from the specified host and a port.
Any port can be used if the policy file is not in the default (root) directory; otherwise the port
is limited to 1024 and higher (as with earlier players). When a connection is established to the
specified port, Flash Player sends <policy-file-request />, terminated by a null byte.
The XML socket server might be configured to serve policy files in the following ways:
■ To serve policy files and normal socket connections over the same port. The server should
wait for <policy-file-request /> before transmitting a policy file.
Because the ability to connect to ports lower than 1024 is available in Flash Player 7
(7.0.19.0) and later, a policy file loaded with loadPolicyFile is always required to authorize
this, even when a SWF file is connecting to its own subdomain.
For example, if the SWF file at https://www.adobe.com/data.swf must allow access by a SWF
file at http://www.adobe.com, the following code added to data.swf allows this access:
// Within data.swf
System.security.allowInsecureDomain("www.adobe.com");
my_lc.allowInsecureDomain = function(sendingDomain:String):Boolean {
return (sendingDomain == "www.adobe.com");
};
W A R N IN G
The following code shows an example of the changes you might have to make:
// Commands in a Flash Player 6 SWF file at https://www.adobe.com
// to allow access by Flash Player 7 SWF files that are hosted
// at http://www.adobe.com or at http://www.helpexamples.com
System.security.allowDomain("helpexamples.com");
my_lc.allowDomain = function(sendingDomain) {
return(sendingDomain=="helpexamples.com");
}
// Corresponding commands in a Flash Player 7 SWF file
// to allow access by Flash Player 7 SWF files that are hosted
// at http://www.adobe.com or at http://www.helpexamples.com
System.security.allowInsecureDomain("www.adobe.com",
"www.helpexamples.com");
my_lc.allowInsecureDomain = function(sendingDomain) {
return(sendingDomain=="www.adobe.com" ||
sendingDomain=="www.helpexamples.com");
}
You might also have to add statements such as these to your files if you aren’t currently using
them. A modification might be necessary even if both files are in the same domain (for
example, a file in http://www.adobe.com is calling a file in https://www.adobe.com).
665
■ When you work on applications
Multiple authors can work on an application with fewer conflicts and greater efficiency.
Project or site administrators can manage and structure complex projects or applications
with fewer conflicts or redundancies if you follow best practices and coding conventions.
■ When you are learning or teaching Flash and ActionScript
Learning how to build applications by using best practices and following coding
conventions reduces the need to relearn particular methodologies. If students learning
Flash practice consistent and better ways to structure code, they might learn the language
more quickly and with less frustration.
Consistent techniques and the following guidelines help people learning Flash, or people
working effectively in team environments. Consistent methods help you remember how you
structured your document when you work by yourself, particularly if you have not worked on
the FLA file recently.
These are only a few of the reasons to learn and follow best practices. You are bound to
discover many more when you read these best practices and develop your own good habits.
Consider the following topics as a guideline when you are working with Flash; you might
choose to follow some or all of the recommendations. You can also modify the
recommendations to suit the way you work. Many of the guidelines in this chapter help you
develop a consistent way of working with Flash and writing ActionScript code.
This chapter covers the following subjects on coding conventions and best practices:
Naming conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .666
Using comments in your code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 677
ActionScript coding conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 679
ActionScript and Flash Player optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 695
Formatting ActionScript syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .697
Naming conventions
Typically, you spend 80% of your development time debugging, troubleshooting, and
practicing general maintenance, especially on larger projects. Even when you work on small
projects, you’ll spend a significant amount of time analyzing and fixing code. The readability
of your code is important for your benefit and the benefit of your team members. When you
follow naming conventions, you increase readability, which increases workflow and enables
you to find and fix any errors in your code. All programmers follow a standardized way of
writing code; this improves the project in many ways.
Flash Player 7 and later loosely follow the ECMAScript (ECMA-262) edition 3 language
specification. It is useful to see this specification for information on how the language
works. (See www.ecma-international.org/publications/standards/Ecma-262.htm.)
Never use different cases to avoid conflicting with reserved words. For example, naming
an instance of the textfield TextField class (which doesn’t conflict with TextField
because Flash is case-sensitive) is a poor coding practice.
gt if ifFrameLoaded implements
intrinsic le it ne
The following words are reserved for future use in Flash, from the ECMAScript (ECMA-262)
edition 4 draft language specification. Avoid using these words because they might be used in
future releases of Flash.
volatile
Use strict data typing with your variables whenever possible because it helps you in the
following ways:
■ Adds code completion functionality, which speeds up coding.
■ Generates errors in the Output panel so you don’t have a silent failure when you compile
your SWF file. These errors help you find and fix problems in your applications.
To add a data type to your variables, you must define the variable using the var keyword. In
the following example, when creating a LoadVars object, you would use strict data typing:
var paramsLv:LoadVars = new LoadVars();
Strict data typing provides you with code completion, and ensures that the value of paramsLv
contains a LoadVars object. It also ensures that the LoadVars object will not be used to store
numeric or string data. Because strict typing relies on the var keyword, you cannot add strict
data typing to global variables or properties within an object or array. For more information
on strict typing variables, see “About assigning data types and strict data typing” on page 45.
NO TE
Strict data typing does not slow down a SWF file. Type checking occurs at compile time
(when the SWF file is created), not at runtime.
Use the following guidelines when you name variables in your code:
■ All variables must have unique names.
■ Don’t use the same variable name with different cases.
Don’t use, for example, firstname and firstName as different variables in your
application. Although names are case-sensitive in Flash Player 7 and later, using the same
variable name with a different case can be confusing to programmers reading your code
and can cause problems in earlier versions of Flash that do not force case sensitivity.
■ Don’t use words that are part of the ActionScript 1.0 or 2.0 language as variable names.
In particular, never use keywords as instance names, because they cause errors in your
code. Don’t rely on case sensitivity to avoid conflicts and get your code to work.
Naming constants
You can use constants for situations in which you need to refer to a property whose value
never changes. This helps you find typographical mistakes in your code that you might not
find if you used literals. It also lets you change the value in a single place.
Variables should be lowercase or mixed-case letters; however, use the following guidelines for
naming static constants (variables that do not change):
■ Constants should be uppercase.
■ Separate words should contain underscores.
You can see these guidelines at work in the following ActionScript code snippet:
var BASE_URL:String = "http://www.adobe.com"; // constant
var MAX_WIDTH:Number = 10; // constant
Do not directly code numerical constants unless the constant is 1, 0, or -1, which you might
use in a for loop as a counter value.
Or for a variable indicating whether a user is logged in (or not), you might use the following:
isLoggedIn
You might have public and private member variables in a class. The class can contain variables
that you do not want users to set or access directly. Make these variables private and allow
users to access the values only by using getter/setter methods.
Naming interfaces
Starting interface names with an uppercase “I” helps you distinguish an interface from a class.
The following interface name, IEmployeeRecords, uses an initial uppercase letter and
concatenated words with mixed case, as follows:
interface IEmployeeRecords{}
If you use the Auto Format tool to format ActionScript, you remove the white space.
Remember to add it back or use single- line comments (//) to maintain spacing; these
lines are easy to remove after you format your code.
■ Remove any superfluous comments from the code before you deploy your project.
If you find that you have many comments in your ActionScript code, consider whether
you need to rewrite some of it. If you feel you must include many comments about how
the ActionScript code works, it is usually a sign of poorly written code.
NO TE
You use documentation comments to describe the code’s specifications, but not the
implementation. You use implementation comments to comment out code or to comment on
the implementation of particular sections of code. Documentation comments are delimited
with /** and */, and implementation comments are delimited with /* and */.
Use documentation comments to describe interfaces, classes, methods, and constructors.
Include one documentation comment per class, interface, or member, and place it directly
before the declaration. If you have additional information to document that does not fit into
the documentation comments, use implementation comments (in the format of block
comments or single-line comments).
After the documentation comments, declare the class. Implementation comments should
directly follow the declaration.
NOT E
Don’t include comments that do not directly relate to the class that’s being read. For
example, don’t include comments that describe the corresponding package.
Use block, single-line, and trailing comments within the body of your class to comment on
your ActionScript code. For more information on using comments in class files, see “Adding
comments to classes” on page 678.
Using behaviors and screens sometimes involves attaching code to objects, so different
practices apply when you use these features. For more information, see Using Flash.
Handling scope
Scope is the area where the variable is known and can be used in a SWF file, such as on a
timeline, globally across an application, or locally within a function. Typically, you can
reference scope in more than one way when you write code. Using scope correctly means that
you can create portable and reusable ActionScript code, and you don’t risk breaking your
applications as you build new modules.
It is important to understand the difference between the global and root scopes. The root
scope is unique for each loaded SWF file. The global scope applies to all timelines and scopes
within SWF files. You use relative addressing rather than references to root timelines, because
relative addressing makes your code reusable and portable. For more information on handling
scope in your applications, see the following sections:
“About variables and scope” on page 60
“About scope and targeting” on page 87
“Understanding classes and scope” on page 243.
All variables must be scoped, except for variables that are function parameters, and local
variables. Scope variables relative to their current path whenever possible, using relative
addressing, such as the this property. For more information on using the this property, see
this property in the ActionScript 2.0 Language Reference.
Using _lockroot
You can use _lockroot to target content as a way to solve the scoping issues sometimes
associated with the inappropriate use of _root. Although this solves many problems with
applications, consider _lockroot as a work-around for problems caused by using _root. If
you experience problems loading content into a SWF file or a component instance, try
applying _lockroot to a movie clip that loads the content. For example, if you have a movie
clip called myClip loading content, and it stops working after it is loaded, try using the
following code, which is placed on a timeline:
this._lockroot = true;
If you consistently add the this keyword in these situations, your ActionScript 2.0 code will
be much easier to read and understand.
Because you are trying to reference the private member variable within an onLoad handler, the
this keyword actually refers to the prodXml instance and not to the Product class, which you
might expect. For this reason, you must create a pointer to the local class file so that you can
directly reference the class from the onLoad handler.
For more information on classes, see “Understanding classes and scope” on page 243. For
more information on scope, see “Handling scope” on page 681.
This example shows better form than putting both declarations on a single line. Place
these declarations at the beginning of a block of code.
■ Initialize local variables when they are declared.
A class’s properties should only be initialized in the declaration if the initializer is a
compile-time constant.
■ Declare variables before you first use them.
This includes loops.
■ Avoid using local declarations that hide higher-level declarations.
For example, don’t declare a variable twice, as the following example shows:
var counterNum:Number = 0;
function myMethod() {
for (var counterNum:Number = 0; counterNum<=4; counterNum++) {
// statements;
}
}
This code declares the same variable inside an inner block, which is a practice to avoid.
■ Don’t assign many variables to a single value in a statement.
Follow this convention because otherwise your code is difficult to read, as the following
ActionScript code shows:
playBtn.onRelease = playBtn.onRollOut = playsound;
or
class User {
private var m_username:String, m_password:String;
}
■ Make a method or property public only if it needs to be public for a reason. Otherwise,
make your methods and properties private.
You don’t have to add these prefixes, and some developers feel it is unnecessary. Adobe
recommends that you add the this keyword as a prefix, because it can improve
readability and it helps you write clean code by providing context.
Delete variables or make variables null when you no longer need them. Setting variables to
null can still enhance performance. This process is commonly called garbage collection.
Deleting variables helps optimize memory use during runtime, because unneeded assets are
removed from the SWF file. It is better to delete variables than to set them to null. For more
information on performance, see “Optimizing your code” on page 696.
For information on naming variables, see “Naming variables” on page 670. For more
information on deleting objects, see delete statement in ActionScript 2.0 Language Reference.
One of the easiest ways to initialize code by using ActionScript 2.0 is to use classes. You can
encapsulate all your initialization for an instance within the class’s constructor function, or
abstract it into a separate method, which you would explicitly call after the variable is created,
as the following code shows:
class Product {
function Product() {
var prodXml:XML = new XML();
prodXml.ignoreWhite = true;
prodXml.onLoad = function(success:Boolean) {
if (success) {
trace("loaded");
} else {
trace("error loading XML");
}
};
prodXml.load("products.xml");
}
}
Create a new class called Socks that extends the Clothes class, as shown in the
following example:
class Socks extends Clothes {
private var color:String;
function Socks(paramColor:String) {
this.color = paramColor;
trace("[Socks] I am the constructor");
}
function getColor():String {
trace("[Socks] I am getColor");
return super.getColor();
}
function setColor(paramColor:String):Void {
this.color = paramColor;
trace("[Socks] I am setColor");
}
}
If you forgot to put the super keyword in the Socks class's getColor() method, the
getColor() method could call itself repeatedly, which would cause the script to fail because
of infinite recursion problems. The Output panel would display the following error if you
didn't use the super keyword:
[Socks] I am getColor
[Socks] I am getColor
...
[Socks] I am getColor
256 levels of recursion were exceeded in one action list.
This is probably an infinite loop.
Further execution of actions has been disabled in this SWF file.
An exception to this rule is, when you are working with the drawing API to draw shapes, you
might have several similar calls to the same methods (such as lineTo or curveTo) because of
the drawing API’s functionality. For example, when you draw a simple rectangle, you need
four separate calls to the lineTo method, as the following code shows:
this.createEmptyMovieClip("rectangleClip", 1);
with (rectangleClip) {
lineStyle(2, 0x000000, 100);
beginFill(0xFF0000, 100);
moveTo(0, 0);
lineTo(300, 0);
lineTo(300, 200);
lineTo(0, 200);
lineTo(0, 0);
endFill();
}
If you wrote each lineTo or curveTo method with a fully qualified instance name, the code
would quickly become cluttered and difficult to read and debug.
You might use these functions by adding the following ActionScript to your FLA file:
import mx.site.Utils;
var randomMonth:Number = Utils.randomRange(0, 11);
var min:Number = Utils.arrayMin([3, 3, 5, 34, 2, 1, 1, -3]);
var max:Number = Utils.arrayMax([3, 3, 5, 34, 2, 1, 1, -3]);
trace("month: "+randomMonth);
trace("min: "+min);
trace("max: "+max);
Similarly, limit the use of setInterval, and remember to clear the interval when you finish
using it to reduce processor requirements for the SWF file.
instead of:
var fontArr:Array = TextField.getFontList();
for (var i:Number = 0; i < fontArr.length; i++) {
trace(fontArr[i]);
}
or
printSize("size is " + foo + "\n");
■ Put each statement on a separate line to increase the readability of your ActionScript
code.
The following ActionScript code shows an example of this:
theNum++; // Correct
theOtherNum++; // Correct
aNum++; anOtherNum++; // Incorrect
You can control auto-indentation and indentation settings by selecting Edit >
Preferences (Windows) or Flash > Preferences (Macintosh), and then selecting the
ActionScript tab.
// if..else statement
if (condition) {
// statements
} else {
// statements
}
// else..if statement
if (condition) {
// statements
} else if (condition) {
// statements
} else {
// statements
}
When you write complex conditions, it is good form to use parentheses [()] to group
conditions. If you don’t use parentheses, you (or others working with your ActionScript 2.0
code) might run into operator precedence errors.
For example, the following code does not use parentheses around the conditions:
if (fruit == apple && veggie == leek) {}
The following code uses good form by adding parentheses around conditions:
if ((fruit == apple) && (veggie == leek)) {}
The second snippet is shorter and has fewer expressions to evaluate. It’s easier to read and to
understand.
The following example checks if the variable y is greater than zero (0), and returns the result
of x/y or a value of zero (0).
return ((y > 0) ? x/y : 0);
The following example shows another way to write this code. This example is preferable:
if (y>0) {
return x/y;
} else {
return 0;
}
The shortened if statement syntax from the first example is known as the conditional
operator (?:). It lets you convert simple if..else statements into a single line of code. In this
case, the shortened syntax reduces readability.
If you must use conditional operators, place the leading condition (before the question mark
[?]) inside parentheses to improve the readability of your code. You can see an example of this
in the previous code snippet.
Although this code validates, it is poorly written because it lacks braces around the statements.
In this case, if you add another statement after the trace statement, the code executes
regardless of whether the numUsers variable equals 0:
// bad
var numUsers:Number = 5;
if (numUsers == 0)
trace("no users found.");
trace("I will execute");
Executing the code despite the numUsers variable can lead to unexpected results. For this
reason, add braces, as shown in the following example:
var numUsers:Number = 0;
if (numUsers == 0) {
trace("no users found");
}
When you write a condition, don’t add the redundant ==true in your code, as follows:
if (something == true) {
//statements
}
// try..catch..finally
try {
// statements
} catch (myErr) {
// statements
} finally {
// statements
}
A slight variation on the first example in this section is to use the handleEvent method, but
this technique is slightly more cumbersome. Adobe does not recommend this technique
because you must use a series of if..else statements or a switch statement to detect which
event is caught.
var boxLdr:mx.controls.Loader;
var ldrListener:Object = new Object();
ldrListener.handleEvent = function(evt:Object) {
switch (evt.type) {
case "progress" :
trace("loader loading:" + Math.round(evt.target.percentLoaded) + "%");
break;
case "complete" :
trace("loader complete:" + evt.target._name);
break;
}
};
boxLdr.addEventListener("progress", ldrListener);
boxLdr.addEventListener("complete", ldrListener);
boxLdr.load("http://www.helpexamples.com/flash/images/image1.jpg");
Error Messages A
Adobe CS3 Professional provides compile-time error reporting when you publish to
ActionScript 2.0 (the default). The following table contains a list of error messages that the
Flash compiler can generate:
1096 The same member name may not be repeated more than once.
1100 A class or interface has already been defined with this name.
707
Error Message text
number
1112 A class may not extend itself.
1121 A class may not extend the same interface more than once.
1122 The implementation of the interface method doesn’t match its definition.
1126 The expression returned must match the function’s return type.
1129 A function with return type Void may not return a value.
1130 The ‘extends’ clause must appear before the ‘implements’ clause.
1139 Classes may only be defined in external ActionScript 2.0 class scripts.
1140 ActionScript 2.0 class scripts may only define class or interface constructs.
1142 The class or interface ‘<Class or Interface Name>’ could not be loaded.
1143 Interfaces may only be defined in external ActionScript 2.0 class scripts.
1146 The property being referenced does not have the static attribute.
1150 You must export your Flash movie as Flash 7 to use this action.
1151 You must export your Flash movie as Flash 7 to use this expression.
1159 Multiple implemented interfaces contain same method with different types.
1163 The keyword ‘<keyword>’ is reserved for ActionScript 2.0 and cannot be used
here.
1165 Only one class or interface can be defined per ActionScript 2.0 .as file.
709
Error Message text
number
1166 The class being compiled, ‘<A.b>’, does not match the class that was
imported, ‘<A.B>’.
(This error occurs when a class name is spelled with a different case from an
imported class. For example, compiling class mx.com.util generates error
1166 if the statement import mx.Com appears in the util.as file.)
1168 The class name you have entered contains a syntax error.
1169 The interface name you have entered contains a syntax error.
1170 The base class name you have entered contains a syntax error.
1171 The base interface name you have entered contains a syntax error.
1174 The class or interface name you have entered contains a syntax error.
1178 Instance variables and functions may not be used to initialize static variables.
1179 Runtime circularities were discovered between the following classes: <list of
user-defined classes>.
This runtime error indicates that your custom classes are incorrectly
referencing each other.
1180 The currently targeted Flash Player does not support debugging.
1181 The currently targeted Flash Player does not support the
releaseOutside event.
1182 The currently targeted Flash Player does not support the dragOver event.
1183 The currently targeted Flash Player does not support the dragOut event.
1184 The currently targeted Flash Player does not support dragging actions.
1185 The currently targeted Flash Player does not support the loadMovie action.
1186 The currently targeted Flash Player does not support the getURL action.
1187 The currently targeted Flash Player does not support the
FSCommand action.
1189 The class ‘<A.B>’ cannot be imported because its leaf name is already
resolved to the class that is being defined, ‘<C.B>’.
(For example, compiling class util generates error 1189 if the statement
import mx.util appears in the util.as file.)
1190 The class ‘<A.B>’ cannot be imported because its leaf name is already
resolved to a previously imported class ‘<C.B>’.
(For example, compiling import jv.util generates error 1190 if the statement
import mx.util also appears in the AS file.)
1192 Class member functions cannot have the same name as a superclass’
constructor function.
1193 The name of this class, ‘<ClassName>’, conflicts with the name of another
class that was loaded.
1195 The identifier ‘<className>’ will not resolve to built-in object ‘<ClassName>’
at runtime.
1196 The class ‘<A.B.ClassName>’ needs to be defined in a file whose relative path
is <‘A.B>’.
1198 The member function ‘<classname>’ has a different case from the name of the
class being defined, ‘<ClassName>’, and will not be treated as the class
constructor at runtime.
1199 The only type allowed for a for-in loop iterator is String.
1201 The only attributes allowed for constructor functions are public and private.
1202 The file 'toplevel.as', which is required for typechecking ActionScript 2.0,
could not be found. Please make sure the directory '$(LocalData)/Classes' is
listed in the global classpath of the ActionScript Preferences.
1205 The currently targeted Flash Player does not support the
FSCommand2 action.
711
Error Message text
number
1206 Member function '<functionName>' is larger than 32K.
1210 The package name '<PackageName>' cannot also be used as a method name.
1212 The ASO file for the class '<ClassName>' could not be created. Please make
sure the fully-qualified class name is short enough so that the ASO filename,
'<ClassName.aso>', is less than 255 characters.
1213 This type of quotation mark is not allowed in ActionScript. Please change it to
a standard (straight) double quote.
Deprecated Flash 4
operators
B
The following table lists Flash 4–only operators, which are deprecated in ActionScript 2.0. Do
not use these operators unless you are publishing to Flash Player 4 and earlier.
713
714 Deprecated Flash 4 operators
APPENDIX C
For more information on the Key class, see Key in ActionScript 2.0 Language Reference. To trap
keys when you test a SWF file in the authoring environment (Control > Test Movie), make
sure that you select Control > Disable Keyboard Shortcuts.
B 66 66
715
Letter or number key Key code ASCII key code
C 67 67
D 68 68
E 69 69
F 70 70
G 71 71
H 72 72
I 73 73
J 74 74
K 75 75
L 76 76
M 77 77
N 78 78
O 79 79
P 80 80
Q 81 81
R 82 82
S 83 83
T 84 84
U 85 85
V 86 86
W 87 87
X 88 88
Y 89 89
Z 90 90
0 48 48
1 49 49
2 50 50
3 51 51
4 52 52
5 53 53
7 55 55
8 56 56
9 57 57
a 65 97
b 66 98
c 67 99
d 68 100
e 69 101
f 70 102
g 71 103
h 72 104
i 73 105
j 74 106
k 75 107
l 76 108
m 77 109
n 78 110
o 79 111
p 80 112
q 81 113
r 82 114
s 83 115
t 84 116
u 85 117
v 86 118
w 87 119
x 88 120
y 89 121
z 90 122
717
Keys on the numeric keypad
The following table lists the keys on a numeric keypad, with the corresponding key code
values that are used to identify the keys in ActionScript:
Numpad 1 97 49
Numpad 2 98 50
Numpad 3 99 51
Numpad 4 100 52
Numpad 5 101 53
Numpad 6 102 54
Numpad 7 103 55
Numpad 8 104 56
Numpad 9 105 57
Multiply 106 42
Add 107 43
Enter 13 13
Subtract 109 45
Decimal 110 46
Divide 111 47
Function keys
The following table lists the function keys on a standard keyboard, with the corresponding
key code values that are used to identify the keys in ActionScript:
F2 113 0
F3 114 0
F4 115 0
F5 116 0
F7 118 0
F8 119 0
F9 120 0
F11 122 0
F12 123 0
F13 124 0
F14 125 0
F15 126 0
Other keys
The following table lists keys on a standard keyboard other than letters, numbers, numeric
keypad keys, or function keys, with the corresponding key code values that are used to
identify the keys in ActionScript:
Tab 9 9
Enter 13 13
Shift 16 0
Control 17 0
Caps Lock 20 0
Esc 27 27
Spacebar 32 32
Page Up 33 0
Page Down 34 0
End 35 0
Home 36 0
719
Key Key code ASCII key code
Left Arrow 37 0
Up Arrow 38 0
Right Arrow 39 0
Down Arrow 40 0
Insert 45 0
Delete 46 127
ScrLk 145 0
Pause/Break 19 0
;: 186 59
=+ 187 61
-_ 189 45
/? 191 47
`~ 192 96
[{ 219 91
\| 220 92
]} 221 93
"' 222 39
, 188 44
. 190 46
/ 191 47
For additional key code and ASCII values, use the ActionScript at the beginning of this
appendix and press the desired key to trace its key code.
You can review surveys for Flash Player version penetration on the Adobe website; see
www.adobe.com/software/player_census/flashplayer/.
721
Using Flash to create content for
Flash Player 4
To use Flash to create content for Flash Player 4, specify Flash Player 4 on the Flash tab of the
Publish Settings dialog box (File > Publish Settings).
Flash Player 4 ActionScript has only one basic primitive data type, which is used for numeric
and string manipulation. When you write an application for Flash Player 4, you must use the
deprecated string operators located in the Deprecated > Operators category in the
ActionScript toolbox.
You can use the following Flash features when you publish for Flash Player 4:
■ The array and object access operator ([])
■ The dot operator (.)
■ Logical operators, assignment operators, and pre- and post-increment/
decrement operators
■ The modulo operator (%), and all methods and properties of the Math class
The following language elements are not supported natively by Flash Player 4. Flash exports
them as series approximations, which creates results that are less numerically accurate. In
addition, because of the inclusion of series approximations in the SWF file, these language
elements need more space in Flash Player 4 SWF files than they do in Flash Player 5 or later
SWF files.
■ The for, while, do..while, break, and continue actions
■ The print() and printAsBitmap() actions
■ The switch action
For additional information, see “About targeting earlier versions of Flash Player” on page 721.
If you used any Flash 5 or later keywords as variable names in your Flash 4
ActionScript, the syntax returns an error when you compile it in Flash. To solve this
problem, rename your variables in all locations. For information, see “About reserved
words” on page 103 and “About naming variables” on page 55.
To write the same target path in dot syntax, which is supported by Flash Player 5 and later
versions, use the following syntax:
myMovieClip.childMovieClip.myVariable
Slash syntax was most commonly used with the tellTarget action, but its use is also no
longer recommended. The with action is now preferred because it is more compatible with
dot syntax. For more information, see tellTarget function and with statement in the
ActionScript 2.0 Language Reference.
Object-Oriented Programming
with ActionScript 1.0
E
The information in this appendix comes from the Adobe Flash documentation and provides
information on using the ActionScript 1.0 object model to write scripts. It is included here for
the following reasons:
■ If you want to write object-oriented scripts that support Flash Player 5, you must
use ActionScript 1.0.
■ If you already use ActionScript 1.0 to write object-oriented scripts and aren’t ready to
switch to ActionScript 2.0, you can use this appendix to find or review information you
need while writing your scripts.
If you have never used ActionScript to write object-oriented scripts and don’t need to target
Flash Player 5, you should not use the information in this appendix because writing object-
oriented scripts using ActionScript 1.0 is deprecated. Instead, for information on using
ActionScript 2.0, see Chapter 6, “Classes,” on page 187.
This chapter contains the following sections:
About ActionScript 1.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 726
Creating a custom object in ActionScript 1.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 728
Assigning methods to a custom object in ActionScript 1.0. . . . . . . . . . . . . . . . . . . .729
Defining event handler methods in ActionScript 1.0 . . . . . . . . . . . . . . . . . . . . . . . . .730
Creating inheritance in ActionScript 1.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 732
Adding getter/setter properties to objects in ActionScript 1.0 . . . . . . . . . . . . . . . . . 734
Using Function object properties in ActionScript 1.0 . . . . . . . . . . . . . . . . . . . . . . . . . 735
NOT E
Some examples in this appendix use the Object.registerClass() method. This method is
supported only in Flash Player 6 and later versions; don’t use this method if you are
targeting Flash Player 5.
725
About ActionScript 1.0
NOT E
Many Flash users can greatly benefit from using ActionScript 2.0, especially with
complex applications. For information on using ActionScript 2.0, see Chapter 6,
“Classes,” on page 187.
In object-oriented scripting, classes can receive properties and methods from each other
according to a specific order, which is called inheritance. You can use inheritance to extend or
redefine the properties and methods of a class. A class that inherits from another class is called
a subclass. A class that passes properties and methods to another class is called a superclass. A
class can be both a subclass and a superclass.
An object is a complex data type containing zero or more properties and methods. Each
property, like a variable, has a name and a value. Properties are attached to the object and
contain values that can be changed and retrieved. These values can be of any data type: String,
Number, Boolean, Object, MovieClip, or undefined. The following properties are of various
data types:
customer.name = "Jane Doe";
customer.age = 30;
customer.member = true;
customer.account.currentRecord = 609;
customer.mcInstanceName._visible = true;
The property of an object can also be an object. In line 4 of the previous example, account is
a property of the object customer, and currentRecord is a property of the object account.
The data type of the currentRecord property is Number.
Many Flash users can greatly benefit from using ActionScript 2.0, especially with
complex applications. For information on using ActionScript 2.0, see Chapter 6,
“Classes,” on page 187.
To create a custom object, you define a constructor function. A constructor function is always
given the same name as the type of object it creates. You can use the keyword this inside the
body of the constructor function to refer to the object that the constructor creates; when you
call a constructor function, Flash passes this to the function as a hidden parameter. For
example, the following code is a constructor function that creates a circle with the property
radius:
function Circle(radius) {
this.radius = radius;
}
After you define the constructor function, you must create an instance of the object. Use the
new operator before the name of the constructor function, and assign a variable name to the
new instance. For example, the following code uses the new operator to create a Circle object
with a radius of 5 and assigns it to the variable myCircle:
myCircle = new Circle(5);
NOT E
Many Flash users can greatly benefit from using ActionScript 2.0, especially with
complex applications. For information on using ActionScript 2.0, see Chapter 6,
“Classes,” on page 187.
You can define the methods of an object inside the object’s constructor function. However,
this technique is not recommended because it defines the method every time you use the
constructor function. The following example creates the methods getArea() and
getDiameter(): and traces the area and diameter of the constructed instance myCircle with
a radius set to 55:
function Circle(radius) {
this.radius = radius;
this.getArea = function(){
return Math.PI * this.radius * this.radius;
};
this.getDiameter = function() {
return 2 * this.radius;
};
}
var myCircle = new Circle(55);
trace(myCircle.getArea());
trace(myCircle.getDiameter());
Each constructor function has a prototype property that is created automatically when you
define the function. The prototype property indicates the default property values for objects
created with that function. Each new instance of an object has a __proto__ property that
refers to the prototype property of the constructor function that created it. Therefore, if you
assign methods to an object’s prototype property, they are available to any newly created
instance of that object. It’s best to assign a method to the prototype property of the
constructor function because it exists in one place and is referenced by new instances of the
object (or class). You can use the prototype and __proto__ properties to extend objects so
that you can reuse code in an object-oriented manner. (For more information, see “Creating
inheritance in ActionScript 1.0” on page 732.)
The following procedure shows how to assign an getArea() method to a custom
Circle object.
2. Define the getArea() method of the Circle object. The getArea() method calculates the
area of the circle. In the following example, you can use a function literal to define the
getArea() method and assign the getArea property to the circle’s prototype object:
Circle.prototype.getArea = function () {
return Math.PI * this.radius * this.radius;
};
4. Call the getArea() method of the new myCircle object using the following code:
var myCircleArea = myCircle.getArea();
trace(myCircleArea); // traces 50.265...
ActionScript searches the myCircle object for the getArea() method. Because the object
doesn’t have a getArea() method, its prototype object Circle.prototype is searched for
getArea(). ActionScript finds it, calls it, and traces myCircleArea.
Many Flash users can greatly benefit from using ActionScript 2.0, especially with
complex applications. For information on using ActionScript 2.0, see Chapter 6,
“Classes,” on page 187.
You can create an ActionScript class for movie clips and define the event handler methods in
the prototype object of that new class. Defining the methods in the prototype object makes all
the instances of this symbol respond the same way to these events.
You can also add an onClipEvent() or on() event handler methods to an individual instance
to provide unique instructions that run only when that instance’s event occurs. The
onClipEvent() and on() methods don’t override the event handler method; both events
cause their scripts to run. However, if you define the event handler methods in the prototype
object and also define an event handler method for a specific instance, the instance definition
overrides the prototype definition.
This new class is assigned to all instances of the movie clip that are added to the
application by the timeline or that are added to the application with the attachMovie()
or duplicateMovieClip() method. If you want these movie clips to have access to the
methods and properties of the built-in MovieClip object, you need to make the new class
inherit from the MovieClip class.
3. Enter code, such as the following example:
// inherit from MovieClip class
myClipClass.prototype = new MovieClip();
Now, the class myClipClass inherits all the properties and methods of the
MovieClip class.
4. Enter code, such as the following example, to define the event handler methods for the
new class:
// define event handler methods for myClipClass class
myClipClass.prototype.onLoad = function() {trace("movie clip loaded");}
myClipClass.prototype.onEnterFrame = function() {trace("movie clip
entered frame");}
5. Select Window > Library to open the Library panel if it isn’t already open.
6. Select the symbols that you want to associate with your new class, and select Linkage from
the Library panel pop-up menu.
7. In the Linkage Properties dialog box, select Export for ActionScript.
8. Enter a linkage identifier in the Identifier text box.
The linkage identifier must be the same for all symbols that you want to associate with the
new class. In the myClipClass example, the identifier is theID.
9. Enter code, such as the following example, in the Actions panel:
// register class
Object.registerClass("theID", myClipClass);
this.attachMovie("theID","myName",1);
myClipClass.prototype.onEnterFrame = function(){
trace("movie clip entered frame");
}
myClipClass.prototype.myfunction = function(){
trace("myfunction called");
}
Object.registerClass("myclipID",myClipClass);
this.attachMovie("myclipID","clipName",3);
Many Flash users can greatly benefit from using ActionScript 2.0, especially with
complex applications. For information on using ActionScript 2.0, see Chapter 6,
“Classes,” on page 187.
The following code adds the roll() method to the Bike class:
Bike.prototype.roll = function() {return this.pos += 20;};
Then, you can trace the position of the bike with the following code:
var myBike = new Bike(55, "blue");
trace(myBike.roll()); // traces 20.
trace(myBike.roll()); // traces 40.
Instead of adding roll() to the MountainBike class and the Tricycle class, you can create the
MountainBike class with Bike as its superclass, as shown in the following example:
MountainBike.prototype = new Bike();
Now you can call the roll() method of MountainBike, as shown in the following example:
var myKona = new MountainBike(20, "teal");
trace(myKona.roll()); // traces 20
Movie clips do not inherit from each other. To create inheritance with movie clips, you can
use Object.registerClass() to assign a class other than the MovieClip class to movie clips.
Many Flash users can greatly benefit from using ActionScript 2.0, especially with
complex applications. For information on using ActionScript 2.0, see Chapter 6,
“Classes,” on page 187.
You can create getter/setter properties for an object using the Object.addProperty()
method.
A getter function is a function with no parameters. Its return value can be of any type. Its
type can change between invocations. The return value is treated as the current value of
the property.
A setter function is a function that takes one parameter, which is the new value of the property.
For instance, if property x is assigned by the statement x = 1, the setter function is passed the
parameter 1 of type Number. The return value of the setter function is ignored.
When Flash reads a getter/setter property, it invokes the getter function, and the function’s
return value becomes a value of prop. When Flash writes a getter/setter property, it invokes
the setter function and passes it the new value as a parameter. If a property with the given
name already exists, the new property overwrites it.
You can add getter/setter properties to prototype objects. If you add a getter/setter property to
a prototype object, all object instances that inherit the prototype object inherit the getter/
setter property. You can add a getter/setter property in one location, the prototype object, and
have it propagate to all instances of a class (similar to adding methods to prototype objects). If
a getter/setter function is invoked for a getter/setter property in an inherited prototype object,
the reference passed to the getter/setter function is the originally referenced object, not the
prototype object.
The Debug > List Variables command in test mode supports getter/setter properties that you
add to objects using Object.addProperty(). Properties that you add to an object in this way
appear with other properties of the object in the Output panel. Getter/setter properties are
identified in the Output panel with the prefix [getter/setter]. For more information on
the List Variables command, see Using Flash.
Many Flash users can greatly benefit from using ActionScript 2.0, especially with
complex applications. For information on using ActionScript 2.0, see Chapter 6,
“Classes,” on page 187.
You can specify the object to which a function is applied and the parameter values that are
passed to the function, using the call() and apply() methods of the Function object. Every
function in ActionScript is represented by a Function object, so all functions support call()
and apply(). When you create a custom class using a constructor function, or when you
define methods for a custom class using a function, you can invoke call() and apply() for
the function.
Many Flash users can greatly benefit from using ActionScript 2.0, especially with
complex applications. For information on using ActionScript 2.0, see Chapter 6,
“Classes,” on page 187.
In some situations, you might want this to point somewhere else; for instance, if a function
must be invoked as a method of an object but is not actually stored as a method of that object,
as shown in the following example:
myObject.myMethod.call(myOtherObject, 1, 2, 3);
You can pass the value null for the thisObject parameter to invoke a function as a regular
function and not as a method of an object. For example, the following function invocations
are equivalent:
Math.sin(Math.PI / 4)
Math.sin.call(null, Math.PI / 4)
Many Flash users can greatly benefit from using ActionScript 2.0, especially with
complex applications. For information on using ActionScript 2.0, see Chapter 6,
“Classes,” on page 187.
The Function.apply() method specifies the value of this to be used within any function
that ActionScript calls. This method also specifies the parameters to be passed to any
called function.
The parameters are specified as an Array object. This is often useful when the number of
parameters to be passed is not known until the script actually executes.
For more information, see apply (Function.apply method) in the ActionScript 2.0
Language Reference.
737
array literal 130 coding conventions 666
arrays comments 677
about 125 comments in classes 678
about multidimensional 131 functions 693
adding and removing elements 129 naming Booleans 672
analogy 125 naming classes and objects 673
and Object class 137 naming constants 672
and sortOn() method 184 naming functions and methods 673
assigning values to 53 naming interfaces 675
associative 134 naming packages 675
associative array 134 naming variables 670
associative array using Object 135 scope 681
associative array using the Array constructor 137 bevel filter
creating 53 about 475
elements of 125 using 476
examples of 125, 126 binding components with ActionScript 545
indexed 130 bindings
iterating through a multidimensional array 132 creating a one-way binding 538
modifying 125, 127 creating a two-way binding 540
multidimensional array 131 creating with ActionScript 538
multidimensional using a for loop 132 bitmap
pass by reference 59 text 369
referencing and finding length 128 bitmap caching
shorthand syntax 125 about 330, 440
to create object 73 and alpha channel masking 338
using 126 and filters 460
using shorthand syntax to create 54 defined 331
ASCII values enabling 330
function keys 718 opaqueBackground property 331
keyboard keys 715 scrollRect 331
numeric keypad keys 718 surfaces 330
other keys 719 when to avoid 333
ASCII, defined 412 when to use 332
ASO files 242 BitmapData class
deleting 243 about 493
using 242 applying filters to 462
associative array, about 134 noise effect 494
associativity, of operators 140 using 494, 559
asynchronous actions 591 with displacement map filter 495
attaching sounds 531 blend modes.See blending modes
blending modes
about 496
B applying 497
backslash character, in strings 420 blur filter
balance (sound), controlling 533 about 465
behaviors animated with Tween class 491
Zoom transition 442 using and animating 466
best practices Boolean
ActionScript 1 and ActionScript 2.0 33 data type 38
Bounce easing class 447
738 Index
broadcaster object 296 about built-in 188
built-in functions 167 accessing built-in properties 257
and ASO files 242
and constructor functions 228
C and inheritance 263
cacheAsBitmap property 331 and instance variables 232
callback functions and polymorphism 271
writing 170 and scope 222, 243
calling methods 40 as blueprints 191
caps styles as data types 188
about 506 assigning to an instance in Flash 239
setting 506 assigning to movie clips 339
caps styles, setting 506 benefit of using 189
cascading style sheets best practices for writing 224
and TextField.StyleSheet class 385 built-in and top-level 246
applying style classes 389 calling built-in object methods 258
applying to text fields 387 class members 211
assigning styles to built-in HTML tags 390 classpaths 202
combining styles 389 compared to interfaces 276
defining styles in ActionScript 387 compared with packages 191
example with HTML tags 391 compiler resolving references 205
example with XML tags 394 compiling and exporting 240
formatting text with 382 controlling member access 233
loading 385 create an instance 215
properties supported 384 creating a class file 205
using to define new tags 393 creating a new instance of built-in class 257
case sensitivity creating an instance of 238
about 80 creating and packaging 226
and Flash Player version 81 creating dynamic 219
casting objects 74 defined 256
character embedding dialog box documenting 234
using 363 encapsulation 221
character encoding 412 excluding built-in classes 259
character sequences. See strings flash.display classes 252
character sets flash.external classes 253
creating custom set 364 flash.filters classes 253
characters flash.geom classes 254
adding and removing embedded 359 flash.net classes 255
checking flash.text classes 255
for loaded data 591 getter/setter methods 216
child importing 201
movie clips, defined 313 importing and packaging 236
node 608 inheritance example 266
class file initializing properties at runtime 340
guidelines for organizing 686 instantiation 188
structuring 685 methods and properties 206
class members 194, 258 mx.lang classes 255
about 194 naming class files 225
classes organizing in packages 189
overriding methods and properties 268
Index 739
preloading 260 in class files 234
private methods and properties 209 inside classes 98
properties of 208 multiline 97
public, private, and static methods and properties single line 96
208 trailing 98
resolving class references 205 writing in class files 678
scoping 684 communicating with the Flash Player 617
static members of built-in classes 258 comparison operators 151
static methods and properties 210 compile time, defined 13
superclass 265 complex data type (data value) 37
System and TextField classes 256 component-based architecture, defined 313
top-level 249 components, coding conventions 676
using class members 214 compound literals 94
using custom classes in Flash 236 compound statements 104
using getter/setter methods 216 writing 701
working with built-in 256 concatenating strings 43
working with custom 199 conditional expressions 114
writing a subclass 265 conditional operator 114
writing custom 196 conditional statements
writing custom example 223 writing 700
writing methods and properties 230 conditions
classpath writing 105
about 34 conditions, about 105
defined 202 constants
delete directory from 203 about 99
document level 204 best practices 672
global 203 using 100
search order of 205 constructor functions
clone() method sample 726
about 492 writing 173
using 492 continuous stroke modulation 370
code conventions, naming 666
examples, copying and pasting 13 converting data types 36
coding conventions convolution filter
ActionScript 679 about 486
components 676 about applying 486
collisions, detecting 534 using 486
between movie clip and Stage point 535 counters, repeating action with 116, 117
between movie clips 535 creating objects 257
colons, about 89 creating strings 419
color matrix filter CSM
about 483 about 370
using 435, 484 about parameters 370
colors CSS. See cascading style sheets
values, setting 530 cue points
comments creating 572
about 95 navigation, event, and ActionScript 568
and syntax coloring 96 tracing 568
best practices 677 using 568
cluttered or clustered 96 viewing 570
740 Index
working with 570 security features 650
curly braces, about 90 sending and loading 590
cursors, creating custom 524 debugging
custom anti-alias compiler error messages 707
defined 369 Delegate class
custom character sets, creating 363, 364 about 310
custom formatters using 310
about 542 deprecated Flash 4 operators 713
using 542 depth
custom functions 163 defined 327
CustomFormatter class determining for movie clips 329
about 543 determining instance at 328
using 543 determining next available 328
managing 327
design patterns
D encapsulation 221
data Singleton 213
about 35 detecting collisions 534
and variables 35 device fonts
defined 35 defined 369
loading and progress bar 592 masking 338
organizing into objects 72 displacement map filter
data types about 487
and values 193 applying to an image 495
annotations 50 using 487
assigning 46 with BitmapData class 495
automatically assigning 45 do..while loops 123
basic 36 documentation, additional resources 17
Boolean 38 DOM (Document Object Model), XML 608
complex 37 domain names and security 650
converting 36 dot syntax (dot notation) 83
defined 36 double-quote character, in strings 420
determining type 49 dragging movie clips 320
MovieClip 40 drawing
null 41 with code 499
Number 42 Drawing API
Object 42 about 499
primitive 37 and line styles 506
String 43 complex gradient fills 505
undefined 44 drawing circles 503
void 44 drawing curves 500
data, external 589, 631 drawing lines, curves, and shapes 500
access between cross-domain SWFs 656, 660 drawing rectangles 501
and LoadVars object 596 drawing rounded rectangles 502
and messages 617 drawing specific shapes 499, 501
and server-side scripts 594 drawing triangles 501, 504
and XML 608 lines and fills 536
and XMLSocket object 616 progress bar 592
checking if loaded 591 using 592
drawing methods
Index 741
See also drawing API attaching to buttons or movie clips 300
drawingAPI attaching to objects 304
with Tween and TransitionManager classes 512 defined 291
drop shadow filter defined by ActionScript classes 293, 294
about 467 in ActionScript 2.0 309
and clone() method 492 scope 306
animating 470 event handler mthods
applying to transparent image 471 checking for XML data 591
using 467 event listeners 296
duplicating, movie clips 323 classes that can broadcast 296
dynamic classes 219 scope 306
dynamic text 344 event model
for event handler methods 294
for event listeners 296
E for on() and onClipEvent() handlers 300
easing events
about 447 and movie clips 339
defining 441 broadcasting 305
with code 449 defined 291
ECMA-262 specification 79 expressions
effects manipulating values in 137
blending modes 497 extends keyword 264
brightness 484 about 264
brightness and color 434 syntax 265
brightness tween 436 Extensible Markup Language. See XML
fading 432 External API
grayscale 435 about 621
noise 494 using 622
panning an image 438 external class files
effects. See filters using classpaths to locate 202
elements, of an array 125 external media 549
embedded characters about loading 550
adding and removing 359 and the root timeline 555
using with text fields 360 creating progress bar animations 580
embedded fonts loading images and SWF files 551
embedding a font symbol 361 loading MP3 files 583
using with TextField class 365 loading SWF and image files 581
encapsulation loading SWF files and JPEG files 551
about 195 MP3 files 555
using 221 playing FLV files 561
endpoints 541 preloading 566, 580
equality operators 151 ProgressBar component 553
error handling and filters 462 reasons for using 549
error messages 707 external sources, connecting Flash with 589, 631
escape character 420 ExternalInterface class
escape sequences 43 about 621
event handler methods using 622
and on() and onClipEvent() 300
assigning functions to 295
742 Index
F Flash Player 8
deprecated language elements 27
fading objects 432 new and changed ActionScript editor features 27
FileReference class new and changed language elements 22
about 600 Flash Video
and download() method 601 See video
and security 601 FlashVars
building an application 602 about 353
files, uploading 600 using to display text 354
filters FlashVars property
adjusting properties 489 about 353
and ActionScript 463 using 67
and error handling 462 FLV files
and memory usage 463 and Macintosh 580
and out-of-memory error 462 configuring the server for FLV 579
and performance 462 creating a FLV banner 564
and transparency 464 creating a progress bar 585
animating 491 cue points 568
applying to instances 462 external video 561
array 490 loading external files at runtime 563
changing brightness level 484 metadata 577
defining 456 navigating with code 574
getting and setting 460 preloading 566
glow filter 457 preloading external video 566
manipulating with code 489 See also video
modifying properties 460 working with cue points 570
noise 494 FLV Video. See video
rotating and skewing 461 FLVPlayback component
rotating, skewing, and scaling 461 and cue points 571
understanding packages 458 and seek() method 574
Flash 4 files, opening with Flash 8 722 creating cue points to work with 572
Flash 8, new and changed ActionScript features 20 seek to a specified duration 574
Flash Play 9.x, new and changed ActionScript 2.0 seek to cue point 575, 576
features 19 using cue points with 572
Flash Player font outlines 373
and ActionScript 695 font rendering
classes, about 247 about 367
coding standards 695 methods 368
communicating with 617 options 369
displaying full screen 618 font symbols, embedding 361
displaying or dimming the context menu 619 font tables
methods 621 creating 373
normal menu view 618 cutoff values 373
publish settings 34 setting 373
scaling SWF files to 618 fonts
Flash Player 4 about 359
creating content for 722 adding and removing 359
Flash Player 7 cutoff values 373
new security model 652, 657, 663 defined 359
porting existing scripts 631 sharing 367
Index 743
for loops 119 passing parameters to 180
example 132 returning values from 182
for statements, writing 702 reusing 176
for..in loops 120 standard format for named functions 168
form feed character 420 targeting and calling user-defined functions 174
formatting text top-level 166
using 376 types of 165
frame rate using a named function 169
about 431 using in Flash 176
and onEnterFrame 431 using variables in 179
choosing 431 writing anonymous functions 170
with Tween class 451 writing named functions 168
frame scripts
about 293
fscommand() function G
commands and arguments 618 garbage collection 688
communicating with Director 620 getter methods
using 618 about 216
fully qualified name using 216
defining 458 getting information from remote files 590
using 458 getting mouse pointer position 525
function getURL() method 522
function block 169 global variables 60
function keys, ASCII key code values 718 glow filter
function literal about 472
about 172 animate 457
redefining 172 using 472
functions glyphRange node, about 363
about 163 gradient bevel filter
as black box 164 about 477
asynchronous 591 and blurX and blurY properties 478
best practices 693 and fill 477
built-in and top-level 167 and highlight 480
callback 170 and knockout and type properties 478
calling top-level functions 168 and movie clip fill 480
compared with methods 185 and strength property 478
comparing named and anonymous 177 applying 482
constructor 173, 726 applying to a movie clip 482
conversion 36 color distribution 478
creating and calling 176 colors array 478
custom 163 ratio array 478
defining 173 ratio value and angle 480
defining global and timeline 173 using 479
for controlling movie clips 315 gradient glow filter
function block 169 about 473
function literal 172 using 474
in a class file 178 grayscale image 435
named function syntax 164 grid fit types, using 378
naming 176
nested 183
744 Index
H using 416
input text 345
handlers. See event handlers instance names
hitTest() method 534 and target paths 83
HTML compared with variable names 348
example of using with styles 391 defined 313
styling built-in tags 390 instances 432
supported tags 398 and OOP 194
tags enclosed in quotation marks 398 applying filters to 462
text field 347 defined 256
using <img> tag to flow text 397, 400, 406 targeting 83
using cascading style sheets to define tags 393 targeting dynamic 85
using in text fields 397 targeting nested 84
HTTP protocol instantiation
communicating with server-side scripts 594 defined 188
with ActionScript methods 590 of objects 257
HTTPS protocol 590 interactivity, in SWF files
creating 519
techniques for 524
I interface keyword 277
ID3 tags 558 interfaces
if..else if statements, writing 108 about 275
if..else statements, writing 107 and OOP 195
IIS 6.0 web server 579 complex interface example 285
images creating 278
applying blending modes 497 creating as data type 280
embedding in text fields 406 defining and implementing 278
loading into movie clips 319 example 283
See also external media naming 277
IME (input method editor) understanding inheritance and 282
about 416 IP addresses
using 416 policy files 659
import security 650
about the statement 458
multiple classes within package 459
using wildcard 459 J
importing JavaScript
class files 201 and ActionScript 79
In 649 and Netscape 621
indexed array 126, 130 international standard 79
information, passing between SWF files 590 sending messages to 619
inheritance JPEG files
about 263 embedding in text fields 406
and OOP 194 loading into movie clips 319, 551
and subclasses 264 jumping to a URL 522
example 266
initialization, writing ActionScript 688
initializing movie clip properties 340
input method editor
about 416
Index 745
K loaded SWF files
identifying 86
key codes, ASCII removing 317
function keys 718 loading
letter and number keys 715 displaying XML files 358
numeric keypad 718 external media 550
other keys 719 loading data
keyboard from server 68
ASCII key code values 715 variables 69
keyboard controls loadMovie() function 591
to activate movie clips 528 loadVariables() function 591
keywords LoadVars class
_root 87 checking HTTP status 598
about 99 loading variables from text file 357
extends 264 using 596
interface 277 using to display text 355
this 87 LoadVars object, creating 596
using 102 local variable, about 62
Locale class
about 414
L using 414
levels looping statements 116, 117
loading 317 loops
levels, identifying depth 86 creating and ending 118
line styles do..while 123
about 506 for 119
alpha 509 for..in 120
and drawing API 506 nested 124
capsStyle and jointStyle 509 using 115
color 508 while 122
miterLimit 512
parameters 507
pixelHinting 509 M
scaling 509 Macromedia Director, communicating with 620
stroke and cap styles 506 manipulating numbers 42
thickness 507 masks 337
lines 506 and alpha channel masking 338
linkage and device fonts 338
coding conventions 676 scripting to create 512
identifier 323, 339 strokes ignored 337, 499
Linkage Properties dialog box 323, 324, 339 MediaPlayback component
linking, movie clips 324 using cue points with 573
listener objects 296 members (methods and properties)
unregistering 297 public, private, and static 208
listener syntax 705 message box, displaying 619
literals metadata
about 94 about 577
compound 94 using 577
LiveDocs, about 15 methods
loaded data, checking for 591
746 Index
about 163, 184 loading MP3 files into 555
and arrays 184 loading SWF files and JPEG files into 551
asynchronous 591 looping through children 117
compared with functions 185 managing depth 327
defined 184 methods and functions compared 314
for controlling movie clips 315 methods, listed 315
naming 185 methods, using to draw shapes 499
of objects, calling 258 nested, defined 313
private 209 parent, defined 313
pubic 209 properties 319
static 210 properties, initializing at runtime 340
types of 165 removing 323
MIME format, standard 595 sharing 324
MIME type 579 starting and stopping 521
mouse pointer. See cursors targeting dynamically created 85
mouse position, getting 525 using as masks 337
movie clips See also SWF files
activating with keyboard 528 MovieClip class
adding parameters 325 adjusting the filters property 489
adjusting color 530 and scale9Grid property 515
_root property 317 blendMode property 496
and with statement 316 drawing methods 499
apply glow filter 457 filters property 460
assigning a custom class to 239 MovieClip data type, defined 40
assigning button states to 305 moviename_DoFSCommand function 619
attaching on() and onClipEvent() handlers 301 MP3 files
attaching to symbol on Stage 323 creating a progress bar 583
background 336 ID3 tags 558
calling multiple methods 316 loading 555, 556
changing color and brightness 434 loading into movie clips 555
changing properties while playing 319 preloading 557, 566
child, defined 313 reading ID3 tags 558
controlling 314 multidimensional arrays, about 131
creating an empty instance 322
creating at runtime 321
creating subclasses 339 N
data type 40 named functions 169
deleting 323 naming classes and objects, best practices 673
detecting collisions 534 naming conventions 666
determining depth of 329 Booleans 672
determining next available depth 328 classes and objects 673
dragging 320 functions and methods 673
duplicating 323 interfaces 675
embedding in text fields 406 packages 190, 675
fading with code 432 variables 670
filters property 480 naming interfaces, best practices 675
functions 315 naming packages, best practices 675
initializing properties at runtime 340 navigation
instance name, defined 313 controlling 519
invoking methods 314
Index 747
jumping to frame or scene 520 defined 331
nested movie clips, defined 313 using 336
Netscape, JavaScript methods supported 621 operands 138
NetStream class operation order 498
and onMetaData handler 577 operator precedence and associativity 140
using onMetaData handler 577 operators
networking about 137
restricting networking APIs 648 additive 148
newline character 420 assignment 140, 154
nodes 608 associativity 140
noise effect 494 bitwise logical 158
null data type 41 bitwise shift 157
numbers, manipulating with methods 42 combining with values 137
numeric keypad, ASCII key code values 718 comparison 144
conditional 114, 151, 160
deprecated 713
O dot and array access 145
object literal 136 equality 150, 151
object properties logical 155, 156
assigning values to 257 manipulating values 139
object-oriented programming 193 mathematical expressions 137
Object-oriented programming. SeeOOP multiplicative 148
objects numeric 149
accessing properties 257 operands 138
calling methods 258 postfix 147
coding standards 680 precedence and associativity 140
creating 54, 72, 257 relational 150
creating in Flash 72 relational and equality 151
data type 42 unary 147
fading out 432 using assignment 155
looping through children of 117 using in Flash 160
organizing data in arrays 73 order of execution (operator)
old players, targeting 721 operator associativity 140
on() and onClipEvent() handlers 300 operator precedence 140
attaching to movie clips 301 organizing scripts
scope 306 ActionScript 1.0 and ActionScript 2.0 33
onEnterFrame, and frame rate 431 attaching to objects 680
online resources 16 coding conventions 679
OOP out-of-memory error 462
about 188, 193
and encapsulation 195
and inheritance 194 P
and interfaces 195 packages
and objects 193 about 189
and polymorphism 196 compared with classes 191
design 221 importing 192
instances and class members 194 naming 190
writing custom classes 196 working with 191, 458
opaqueBackground property parameters 169
748 Index
parent movie clips 313 files, communicating with 590
parentheses, about 93 sites, continuous connection 616
PDF documentation, where to find 15 removing
performance loaded SWF files 317
and filters 462 movie clips 323
and frame rate 431 repeating actions, using loops 115
bitmap caching 440 reserved words
playing movie clips 521 about 103
pointer. See cursors other recommendations 103
policy files resources, additional 14
defined 658 Restricting networking APIs 648
must be named crossdomain.xml 658 return statement 703
See also security _root property and loaded movie clips 317
polymorphism runtime data binding
about 196 about 537
using 271 creating a two-way binding 540
post colon syntax, defined 46 with CheckBox 541
prefixes, super 690 runtime, defined 13
primitive data type (data value) 37
progress bar
and drawing API 592 S
creating with code 580 sample files, about 14
for data loading 592 scale-9
projectors, executing applications from 619 about 514
properties scale-9. See 9-slice scaling
initializing at runtime 340 scope
of movie clips 319 about 87
of objects, accessing 257 best practices 681
private 209 in classes 684
public 209 this keyword 310
static 210 scripted animation
publish settings about 430
choosing Flash Player version 34 and blur filter 491
punctuators and filters 491
about 88 and Tween class 491
curly braces 90 brightness tween 436
parentheses 93 creating a progress bar 580
semicolons and colons 89 drawing API 512
moving images 438
moving objects 437
Q panning images 438
quotation marks, in strings 43 Tween and TransitionManager classes 441
scripts
about events 292
R clip events 293
registration point, and loaded images 319 frame scripts 293
relational operators 151 keyboard events 292
relative paths 87 porting to Flash Player 7 631
remote scrolling
Index 749
and bitmap caching 440 defined 78
text 410 for 702
scrollRect property 331 guidelines for writing 103
security if 106
and policy files 658 if..else 107
and porting scripts to Flash Player 7 652, 657, 663 if..else if 108
cross-domain 650 importing 192
data access across domains 656 switch 109
Flash Player compatibility 631 try..catch..finally 111, 704
loadPolicyFile 660, 661 while and do while 703
restricting networking APIs 648 with 691
semicolons, about 89 static members 258
sending information static members. See class members
in XML format 590 static text 344
to remote files 590 stopping movie clips 521
URL-encoded format 590 strict data typing 50
via TCP/IP 590 String class
server-side scripts about 411, 418
creating 606 and substr() and substring() methods 427
languages 590 charAt() method 422
XML format 610 concat() method 425
servers, opening continuous connection 616 length property 421, 424
setInterval split() method 426
and frame rate 431 toLowerCase() and toUpperCase() methods 424
using 433 toString() method 424
setRGB method 530 strings 43
setter methods about 411
about 216 analyzing 421
using 216 comparing 421
sharing fonts comparing to other data types 423
about 367 converting and concatenating 424
single-quote character, in strings 420 converting case 424
Singleton design pattern 213 creating 419
slash syntax creating an array of substrings 426
about 88 defined 412
not supported in ActionScript 2.0 88 determining length 421
using 724 examining characters 422
socket connections finding character position 428
about 616 finding substring 427
sample script 616 forcing type comparisons 423
sounds looping over 422
attaching to Timeline 531 returning substrings 427
balance control 533 using 419
See also external media Strings panel 413
special characters 43 stroke styles 506
Stage, attaching symbols to the 323 strokes
statements setting parameters 507
about 103 setting styles 506
compound 104, 701 strong typing 45, 50
conditional 106, 700 style sheets. See cascading style sheets
750 Index
styles with XMLSocket object 616
line 506 text
stroke and caps 506 assigning to text field at runtime 346
styles, stroke and caps 506 loading and displaying 354, 355, 358
subclasses scrolling 410
creating for movie clips 339 terminology 343
example 266 using <img> tag to flow around images 400
writing 265 See also text fields
subclasses, about 264 text components 345
super prefix 690 text fields
superclass 265 about 344
surfaces and HTML text 390
defined 330 applying cascading style sheets 387
SWF files avoiding variable name conflicts 349
controlling in Flash Player 621 changing dimensions 351
embedding in text fields 406 changing position 351
jumping to frame or scene 520 controlling embedded media 408
loading and unloading 317 creating dynamically at runtime 347, 349
loading into movie clips 551 default properties 382
maintaining original size 618 dynamic 344
passing information between 590 embedding clickable images in 410
placing on Web page 522 embedding movie clips in 407
scaling to Flash Player 618 embedding SWF or image files 406
See also movie clips flowing text around embedded images 397, 400
switch statements formatting 380
conventions 703 formatting with cascading style sheets 382
using 109 HTML formatting 347
syntax instance and variable names compared 348
case sensitivity 81 instance names 348
slash 88 loading variables into 353
system manipulating 350
event, defined 291 populating with external text 356
requirements, for ActionScript 2.0 10 setting thickness 365
specifying image dimensions 408
See also TextField class, TextFormat class, and
T TextField.StyleSheet class
tab character 420 text formatting
target path about 375
and dot syntax 82 text layout 375
and nested instances 84 text rendering options 369
and targeting an instance 83 TextField class
inserting 88 creating scrolling text 410
using 175 using 346
using button 88 TextField methods, using 365
targeting TextField.StyleSheet class 383
and scope 87 and cascading style sheets 385
loaded content 85 and TextField.styleSheet property 383, 387
TCP/IP connection creating text styles 387
sending information 590 TextFormat class
about 375
Index 751
using 380 U
this keyword 87, 547
and scope 87 UCS (Universal Character Set), defined 412
as prefix 687 undefined data type 44
in classes 222 Unicode
scope 222 character code 412
using 683 defined 412
timeline variable, about 61 Universal Character Set (UCS) 412
trace statements, writing ActionScript 689 URL variables, about 64
transferring variables between movie and server 596 URL-encoded format, sending information 590
Transition class user event 291
animating brightness level 484 user-defined functions
TransitionManager class writing 174
about 441 UTF-16 encoding standard 412
and easing 441 UTF-8 (Unicode) 412
using 444
with drawing API 512
with Tween class 455
V
transitions values
adding with ActionScript 444 and data types 193
adding with behaviors 442 manipulating in expressions 137
defining 443 variables
transparency, and masking 338 and operators 54
try..catch..finally statement, writing 111, 704 and scope 60
Tween class assigning values 52
_alpha property 455 avoiding name conflicts 349
about 441, 448 changing value 53
and easing 441 comparing undefined and defined 56
animating blur filters 491 converting to XML 610
animating brightness level 484 declaring 51
continueTo() method 452, 455 default values 52
fading objects with 450 defined 50
importing 449 instance 232
onMotionFinished event handler 453 loading 64, 68
setting duration of frames 451 loading from external text file 357
to trigger animation completed 452 loading into text fields 353
using 444, 449 local 62
with Drawing API 512 naming rules and guidelines 55
with TransitionManager class 455 passing by reference 58
yoyo() method 453, 455 passing from HTML 354
tweens passing values from URL string 64
adding with ActionScript 444 sending to URL 522
adding with behaviors 442 setting using a path 86
type checking timeline 61
defined 48 transferring between movie clip and server 596
dynamic 49 URL encoded 64
example 48 using 57
typographical conventions 13 using FlashVars to pass 67
using in a project 69
using in an application 56
752 Index
variables, global 60 sending information via TCP/IP socket 590
video sending information with XML methods 590
about 560 XML class, methods 609
about external FLV files 561 XML files, updating for Flash 8 installation 10
adding seek functionality 574 XML Localization Interchange File Format 414
and Macintosh 580 XMLSocket object
configuring the server for FLV 579 checking for data 591
creating a banner 564 loadPolicyFile 661
creating a progress bar to load FLV 585 methods 616
creating a video object 562 using 616
creating FLV files 561
cue points 568
metadata 577 Z
navigating a FLV file 574 Zoom transition behavior 442
playing FLV files at runtime 563
preloading 566
seek to a specified duration 574
seek to cue point 575, 576
tracing cue points 568
using the onMetaData handler 577
working with cue points 570
video, alternative to importing 561
void data type 44
volume, creating sliding control 532
W
web applications, continuous connection 616
while loops 122
with statement 691
writing ActionScript
super prefix 690
trace 689
with statement 691
writing syntax and statements
listener 705
return 703
switch 703
X
XLIFF files 414
XML 608
DOM 608
example of using with styles 394
hierarchy 608
in server-side scripts 610
loading and displaying text 358
sample variable conversion 609
Index 753
754 Index