Professional Documents
Culture Documents
Interactivity
Web Animation and Interactivity
No part of this book may be reproduced or copied in any form or by any means – graphic, electronic or
mechanical, including photocopying, recording, taping, or storing in information retrieval system or sent
or transferred without the prior written permission of copyright owner Aptech Limited.
APTECH LIMITED
Edition 1 – 2013
This book, Web Animation and Interactivity, introduces you to the various features of Flash CS6 and ActionScript 3.0
(AS3.0). It meets almost all your requirements of Web related graphics and basic concepts of programming that provides
a foundation for developing applications in ActionScript.
The ARENA Design team has designed this course keeping in mind that motivation coupled with relevant training and
methodology can bring out the best. The team will be glad to receive your feedback, suggestions, and recommendations
for improvement of the book.
Iconography
: System Requirements
: Note
: Tip
: Quick Test
: Quick Answers
: Exercise Answers
S e s s io n 1
Working with Flash CS6
Learning Outcomes
In this session, you will learn to:
¾¾ Describe the Flash CS6 interface
¾¾ Draw and reshape objects
¾¾ Work with layers
Adobe Flash Professional CS6 is a useful tool for the creation of multimedia content and animation. The interactive
designs thus created can be presented consistently in desktops as well as other multiple devices, which include tablets,
smartphones, and televisions.
System Requirements
• Windows Operating System
• 2 GB of RAM (3 GB recommended)
In order to begin working, you can either use the commands available in the File menu or select an option present in the
welcome panel. It includes the following three columns:
¾¾ Predefined templates, which define standard workspace sizes, are present in the left column.
¾¾ Different Flash variants are present in the middle column.
¾¾ Links to Adobe’s introductory text from Flash development center are present in the right column. The respective
content open in the default Web browser.
Refer to Figure 1.1. On clicking the Don’t show again option, which appears on the bottom left corner, the welcome
panel does not appear anymore. However, the options present in the welcome panel can be accessed through the File
menu. It is possible to launch the welcome panel again. To do so, from the Edit menu, click Preferences. In the dialog
box that appears, under the General category, select Welcome Screen from the On Launch: drop-down list.
Figure 1.1: Welcome screen
ActionScript 3.0 is the latest Flash scripting standard. Hence, it is recommended to select AS3 before beginning work in
Flash. A 550x400 px workspace opens, where Flash can be configured for AS3.
Flash documents are based on scripting languages, of which, ActionScript 2.0 or ActionScript 3.0 can be used. To open
a new document, choose New from File menu. Alternatively, an option for creating a new document is present in the
welcome panel.
A new document in Flash is titled Untitled-1, by default. Successive new documents are named consecutively. In
addition, a user can work on multiple documents simultaneously. Refer to Figure 1.2.
To create a new document, click the General tab in the New Document dialog box. Set the scripting language to
ActionScript 3.0. The document type can be selected from the list. Then, click OK.
Select Properties from the Window menu to access the Property Inspector window. Refer to Figure 1.3. The
Properties section in the window contains the following options:
¾¾ FPS: FPS refers to frames per second. This option is used to set the frame rate for the movie. Frame rate
defines the speed of the movie. Enter the number of animation frames to be displayed per second in the Frame
Rate box. Alternatively, drag the field to modify the frame rate.
¾¾ Size: This option is used to define the size of the animation movie. Click Edit to set the animation dimensions.
Figure 1.4 displays the Document Settings dialog box. It contains options as shown in Table 1.1.
On opening a document in Flash, a tab appears across the top of the document window. Clicking the tab,
displays the document.
1.1.5 Saving a Document
Flash documents are saved with .fla extensions, by default. On clicking Save, a prompt appears to specify the name
of the file and the location where it should be saved. A file not saved, has an asterisk displayed after the name in the
document tab. Older versions of a file can be retained while saving new files, by clicking Save as in File menu. .fla files
can also be saved in the XFL format. This format represents uncompressed version of a Flash document and can be
used in Adobe InDesign and After Effects programs.
To save a document, click Save from the File menu. In the dialog box that appears, give an appropriate name to the file,
specify the location for the file, and then, click Save.
eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Getting Started>> Saving a
Document
The panels can be opened and closed or docked and undocked as per requirement. Refer to Figure 1.5. Most
applications of Adobe Creative Suite share similar workspaces. This makes it easy to move between applications.
Each panel in the Flash workspace is equipped with certain features, which are as follows:
¾¾ The tab titles, buttons for minimizing, maximizing, and closing the window, and Options menu are all present
in the header of the panel.
¾¾ There is also a double arrow available, which helps in expanding or collapsing the panel.
¾¾ Commands to group, rename, maximize, and close a panel are present in the Options menu. Additionally, it
also has a Help option.
■■ Opening and closing a panel
Select the name of the required panel from the Window menu to open that panel. Alternatively, choose Other
Panels options from Window menu and then, select the name of the required panel. Clicking Close button on the
panel or the tab that is to be closed closes the panel.
■■ Collapsing and expanding a panel
Double-click the title tab on the header of a panel in order to collapse or expand the panel. To hide or show hidden
panels, choose the respective Hide Panels and Show Panels options in Window menu.
For auto-collapsing icon panels and auto-showing hidden panels, right-click the header tab of the panel and
then, choose Auto-Collapse Iconic Panels and Auto-Show Hidden Panels, respectively.
Click Collapse to Icons double arrow, which is present at the top of the panel in order to collapse a panel set.
Click Expand Dock double arrow, which is present at the top of the panel in order to expand a panel set. Choosing
Auto-Collapse Iconic Panels and Auto-Show Hidden panels collapses and hides panels automatically, when the
user clicks at a point away from the panel.
■■ Panel options menu
Panel options menu is present on the right side of the header bar of the panel. The commands present in the menu
are as follows:
¾¾ Help: This command is used to access help for Flash.
¾¾ Close: This command is used to close the tab that is currently displayed in the panel.
¾¾ Close group: This command is used to close all the tabs present in the panel.
■■ Docking and undocking panels
Temporary docking and undocking, attaching and detaching panels or panel groups or panel tabs can be done in
Flash. To dock or undock a panel or panel group, drag the panel(s) around the program window. When a panel
is dragged over a dockable area, an outline can be observed around the target dock. The panel now fits in the
dockable area once the mouse button is released. It remains in the dockable area till it is moved. On the other hand,
appearance of outline is not seen when a panel is moved over an undockable area.
■■ Moving panels
While moving panels, blue highlighted areas appear, indicating panel drop zones. For instance, dragging a panel
to the narrow blue drop zone, present above or below another panel moves the panel up or down within a dock.
Dropping a panel in an area, which is not a drop zone makes the panel float freely within the workspace. A panel
can be moved by dragging its tab, whereas, a panel group can be dragged by its title bar.
A drop zone is activated by the position of the mouse, but not the position of the panel. Incase a drop zone is
not visible, it can be seen by dragging the mouse to the area where the drop zone is expected to be.
Organization and workflow in Flash can be improved greatly by grouping panels. Grouping and ungrouping, and
docking and undocking panel windows can be done by using the panel tab.
¾¾ Click the header bar of a panel set or the tab of an individual panel and drag from one window to another for
grouping panels.
¾¾ Click and drag a panel till the appearance of a blue outline is seen around the panel in order to add panels.
¾¾ Click a panel and drag it till the appearance of a blue line is seen along the side of the panel in order to append
panels.
¾¾ Click a specific window and drag it away from the panels to an empty area of the Flash window in order to
ungroup panels.
■■ Resizing panels
Double-clicking the tab of a panel, a panel group, or a panel stack alters its size. Alternatively, the tab area or the
empty space present next to the tabs can be double-clicked. Dragging the sides of the panel helps in resizing the
panel.
■■ Stack floating panels
A panel, when dragged out of its dock into an area which is not a drop zone, floats freely in the workspace. This type
of floating panel can be placed in any position in the workspace. Several floating panels can be stacked into panel
groups. All these panels move as a single unit on dragging their top-most title bar. Actions that can be performed
with respect to floating panels are as follows:
¾¾ Dragging a panel by its tab and dropping it in a drop zone present at the bottom of another panel helps in
stacking the floating panels.
¾¾ Dragging a panel upward or downward using its tab changes the order of stacking of the panels.
¾¾ Dragging a panel by its tab or title bar from the stack removes it from a panel stack and makes it float by itself
in the workspace.
Customized workspaces can be accessed from the Workspace menu. Figure 1.6: Workspace menu
■■ Deleting a workspace
Navigate to the Workspace menu and choose Manage Workspaces. The Manage Workspaces dialog box
appears in which, the panel set that is to be deleted should be selected. Then, click Delete. In the prompt that
appears, click Yes, followed by OK.
Each tool in the toolbox has unique properties and performs a unique function. However, some tools are interlinked to
others. To view the available options under the Tools command, select Tools from Window menu.
2. To change the stacking order of the panels, users can drag a panel either upward or downward using its tab.
True False
This mode is the default drawing mode in Flash. In this mode, when two shapes are drawn overlapping each other,
their shapes merge automatically. In addition, on moving one merged shape, the other shape also moves. Refer to
Figure 1.10.
Through this mode, when two separate objects are drawn overlapping each other, they do not merge. Primitive
shapes, such as rectangles and ovals can be drawn through this mode. The corner radii and inner radii can also
be specified for rectangles and ovals respectively, in the Property Inspector window. In addition to the primitive
shapes, curved shapes, such as pie wedges and round off corners can be drawn using this model. Using the Object
Drawing tool from the toolbox, it is possible to draw objects in this model. When an object drawn in this model is
selected, a bounding box appears around it. Then, using a Pointer tool, this shape can be moved on the stage.
Refer to Figure 1.11.
Straight lines can be drawn using the Line tool from the Tools panel. The steps for drawing a straight line using the
Line tool are as follows:
¾¾ Select the Line tool from the toolbox.
¾¾ Navigate to the Window menu and select Properties. In the Properties panel, changes can be made in the
following fields:
• Thickness can be set between 0-200 pixel range using the Stroke option. Refer to Figures 1.12 and 1.13.
• Styles
• Colors
• Gradient fills
¾¾ In the Options section of the toolbox, click the Object Drawing button. Then, select Merge or Object Drawing
mode.
¾¾ Place the pointer at a place where the line has to start. Click and drag till the line ends. Press Shift and then
drag for constraining the angle of the line to multiples of 45°.
Rectangles and ovals can be created using the Rectangle and Oval tools respectively. Further, strokes, fills, and
rounded corners can be applied to these shapes. These tools also provide the Primitive Object Drawing mode in
addition to Merge and Object Drawing modes.
Different radii can be specified to different corners of the rectangle primitive. When the radius controls are in a
locked state, they are restrained such that all corners use the same radius. De-selecting the Lock icon in the
Rectangle Options area in the Property Inspector removes this restrain and different radii can be defined
for different corners. Refer to Figure 1.15. Click Reset in Property Inspector in order to reset the corner radii.
Click here to know more about Drawing Rectangles Primitives.
1. Select the Rectangle or the Oval tool. To do so, click and hold the Rectangle tool and drag it on the stage.
2. For the Rectangle tool, use the Round Rectangle modifier to define the corner radius values for the rectangle.
Then, drag the chosen tool on the stage.
3. Navigate to the Window menu, point to Properties, and select Fill and Stroke attributes.
4. As shown in Figure 1.18, provide the following settings in the Properties panel:
¾¾ Style: Select the Polygon tool or Star tool.
¾¾ Number of Sides: Enter a number between 3 to 32.
¾¾ Star Point Size: Enter a number, from 0 to 1 for specifying the depth of star points. Deep points are created
when the number is closer to 0. The settings should be retained as they are while drawing a polygon.
5. Once the settings are done, click OK. Then, drag on the stage.
Join refers to the intersection point of two strokes. In the Join menu, three settings, namely, Miter, Round, and Bevel
are present. These settings are used for the creation of various styles of joins in drawings involving intersection
lines. An additional option for adjustment of angle of joins is provided by the Miter Join style. This is done by
entering a value ranging between 1 and 60 in the Miter field. Refer to Figure 1.19.
The Pencil tool is used to create freehand drawings. The options offered by Pencil tool are as follows:
¾¾ Straighten: Approximations of lines, triangles, ovals, circles, rectangles, and squares can be snapped into well-
defined shapes through this option.
¾¾ Smooth: Curved lines can be smoothened with this option.
¾¾ Ink: Freehand lines can be drawn without any modifications using this option. Refer to Figure 1.20.
The Pencil tool is present in the toolbox. When this tool is selected, the mouse pointer changes to the shape of a
pencil. The options related to this tool are present at the bottom of the toolbox. The default mode for the Pencil tool
is Straighten.
To use this tool, you can begin by drawing on the stage. Then, release the mouse. A rough preview of the line
appears as you draw. However, in the Straighten mode, the line appears different. In this mode, Flash transforms
the line into a series of straight-line segments and standard curves.
■■ Pen tool
The Pen tool in Flash works similar to that in Illustrator. It is the basic tool used for vector drawings. While using this
tool, anchor points and Bezier handles are used for the creation of lines and different shapes. Functioning of the Pen
tool is same across all applications in the Adobe suite. Anchor points can be added, deleted, or converted by using
different modes of the Pen tool. Using this tool, anchor points and vectors can also be edited and desired drawings
can be created as per requirements. Refer to Figure 1.21.
Figure 1.21: Pen tool
When the Pen tool is selected, various icons appear at the lower right of the cursor. Different functions are performed
on the line by these icons. A small x appears when the cursor is hovered over an empty area of the stage. It gives
an indication that the tool is ready to place the first point on a line. The other icons are as follows:
¾¾ Small link icon: This icon has a square with a line running through it. It gets displayed when the Pen tool is
moved over an endpoint that can be connected to close a path. Clicking this point, closes the path.
¾¾ Slash (/): This is displayed when the Pen tool is moved over an endpoint that will not connect to close a path.
Clicking this point defines it as the starting point for a continuation of the path or as the first point for closing a
path.
¾¾ Carat (^): This is displayed when the Pen tool is moved over a curve point. On clicking at this point, it is
converted into a corner point.
¾¾ Minus (-): This sign is displayed when the Pen tool is moved over a corner point. On clicking, the corner point
is deleted.
¾¾ Plus (+): This sign is displayed when the Pen tool is moved over a path. On clicking, a new point is added to
the path.
¾¾ On keeping the Ctrl key pressed, the Pen tool acts like a Subselection tool. When it is converted to a
Subselection tool, it switches to a hollow arrow icon with a filled black box over lines, or a hollow white box
over points.
On adjusting a path either with the Pen tool or the Subselection tool, the default is a filled circle; whereas, unselected
points appear as hollow squares. The unselected points display a single tangent handle that is bound toward the
selected point. The selected point displays two tangent handles.
Refer to Figure 1.22. To draw and adjust a straight-line segment with the Pen tool, begin by selecting the Pen tool.
Then, click to place the first point of your line on the stage. Select the end point for the line. Continue clicking to
create subsequent points and define individual line segments. Each subsequent click creates a corner point on the line,
indicating the length of individual line segments.
You can also draw and adjust a curved line segment using the Pen tool. To do so, click to create the first anchor point.
Then, click to define the next anchor point. Next, without releasing the mouse after defining the second anchor point,
drag the Pen tool in the direction you want the curve to appear. When the preview of the line resembles the output,
release the mouse and move to click and place the next point in the segment. Repeat this process to create subsequent
curve points for the curved segments.
To make changes to the curve, use the Subselection tool. Click and move the cursor over a handle on the line or at the
end of the line. Drag to reposition and reshape the line or curve.
Using the Selection tool, you can create a selection rectangle for selecting parts of an object or by dragging over a
portion of it. On defining a selection, a dotted pattern appears over it indicating the selection. The properties of the
selection, like the stroke weight and stroke style, fill color, pixel dimensions, and the X and Y coordinates appear in
the Property Inspector window.
¾¾ Drag-select: To select a line or shape, in addition to clicking it, you can also drag a marquee around the line
to select it, keeping the Selection tool active. This action is referred to as drag-select. Refer to Figure 1.24.
¾¾ Selecting multiple objects: You can add additional items to the current selection by keeping the Shift key
pressed as you drag-select. Dragging a group of elements onto the stage with the Shift key pressed, constrains
the movement range of the elements to 45 degrees. This is helpful when you want to move an object up or down
while keeping it on the same axis or baseline.
■■ The Lasso tool
Using this tool, you can select part of an object by drawing freehand over the desired area. This tool comes handy
when you have to select multiple objects or have objects placed close together. To make a selection using this tool,
click the Lasso tool on the Tools panel. Then, draw around the shapes you want to select. Complete the selection
by clicking the point where you started. Refer to Figure 1.25.
On selecting the Lasso tool, the following options appear at the bottom of the Tools panel, to refine your selection:
¾¾ Polygon mode
¾¾ Magic Wand mode
¾¾ Magic Wand properties
Refer to Figure 1.26 and Table 1.2 for a description of each available option.
The Subselection tool comes with Tangent Angles and Anchor Points that
help change the shape of any object.
Selecting an object using this tool, makes the outline of the selected object
very prominent and also displays a series of nodes (green squares) on the
outline. The outline of the object, also known as paths, comprises lines and
dots that define it. Refer to Figure 1.27. You can also deselect objects in
either of the following ways:
¾¾ Pressing the Esc key
¾¾ From the Edit menu, select the Deselect All command
¾¾ Press the Ctrl+Shift+A keys
¾¾ Clicking anywhere outside the selected items
Before you can reshape an object, ensure that the object to be worked on is not selected. To reshape an object, you
can either use the Selection tool or the Subselection tool. In either case, ensure that the object is deselected before
the tool is active.
To reshape an object using the Selection tool, click the tool from the Tools panel. Then, click at the end of a shape and
drag the shape to modify it. You can pull the curve to any position. To reshape an object using the Subselection tool,
click and drag the nodes that appear around the selected object. Refer to Figure 1.28.
The Free Transform tool is available under the Selection tool in the Tools panel. Using this tool, you can resize,
rotate, squish, or stretch objects with ease. You can perform most of these tasks using this tool and it is easier to
access and use as compared to the other Transform tools. Refer to Figure 1.29.
Click here to know more about the Transform tool in Flash CS6.
Using the Transform panel, you can enter precise values to transform an object. It includes the following buttons:
¾¾ Copy and apply transform button: This button is used to duplicate the selected item that has all the
transformations. On selecting the button, a duplicate object is created that is placed exactly on top of the
original. To view both the objects separately, click and drag the duplicate to a different position on the document
window.
¾¾ Reset button: This button reverts a transformed symbol to its default settings. This can also be done by clicking
the Transform command from the Modify menu and choosing Remove Transform from the submenu.
The Transform mode and other additional effects are available in the Transform submenu that is housed in the
Modify menu.
For detailed step-by-step procedure, refer to demo Creating and Reshaping Objects from:
eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Drawing and Reshaping
Objects>> Duplicating Objects
1. In the object drawing mode, when two shapes are drawn overlapping each other, they merge automatically.
True False
2. I nspite of the radius controls being in the locked state, different radii can be specified to different corners of the
rectangle primitive.
True False
3. The Selection tool is used to select part of an object by drawing freehand over the desired area.
True False
In Flash, it is easy to rename layers in the Timeline. You can easily rename a layer by typing new labels directly on the
layer name list. To rename a layer, double-click the name of the layer. Then, type a new name in the space provided
and press the Enter key.
On selecting a layer in the Timeline, a Pencil icon appears beside the name of the layer. This icon indicates that the
layer can be edited; in other words, you can draw or make other changes to the layer. Refer to Figure 1.32.
Figure 1.32: Layers - Pencil Icon
■■ Hide Layer button
You can hide the contents of a layer by clicking the Hide Layer button. It appears like a small dot to the right of
the Pencil icon and below the Eye icon. On selecting the Hide Layer button, the dot turns to a red x and a red line
appears through the Pencil icon indicating that the layer is hidden and cannot be edited. You can unhide the layer
by clicking the red x. Refer to Figure 1.33.
The Lock Layer button is used to lock the selected layer. This button appears like a dot to the left of the colored box
and below the Lock icon. Clicking this button locks the layer to prevent any changes. On clicking the Lock Layer
button, the dot turns into a little lock icon and a line appears through the pencil. Locking layers is a very important
feature in Flash. It prevents accidental moving or deletion of objects on a layer. Clicking the Lock icon, unlocks the
layer. Refer to Figure 1.34.
Figure 1.34: Layers - Lock icon
■■ Outline icon
The colored box to the right of the Lock icon is used to display contents of a layer in an outline. On clicking the
colored box, the fills in the layers are displayed as outlines. This option proves useful when there are more than one
objects placed on a layer and the contents of layer underneath have to be displayed. Refer to Figure 1.35.
On the top of the Layers area are three icons, namely, an Eye, a Lock, and an outline of a Square. Refer to Figure
1.36. Each of these icon performs a specific function. The Eye icon hides all layers on the stage. Clicking this icon
again unhides all the layers. The Lock icon is used to lock all the layers on stage. Clicking this icon again unlocks
the layers. The Square icon is used to hide the fills of the objects on stage. Clicking this icon again redisplays the
fills.
Figure 1.36: Icons above the Layers area
Clicking the New Folder button below the timeline, creates a new folder. Folders that are newly created are named in a
sequence. This happens by default. To rename a folder, double-click the folder name and type a new name. To remove
a layer from a folder, click the layer and drag it from within the folder to the desired location anywhere outside the folder.
For detailed step-by-step procedure, refer to demo Working with Layers from:
eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Working with Layers>> Layer
Properties
1.5 Summary
In this session, Working with Flash CS6, you learned that:
¾¾ A file in Flash is referred to as a document that has the .fla extension. Flash documents are not movie files. To
publish it as a movie file, Flash documents should be saved with the .swf extension.
¾¾ Setting the document properties at the beginning of the project helps in deciding on the look and feel of the
project.
¾¾ The Flash workspace comprises various elements that can be moved on the stage.
¾¾ Panels are windows that allow you view, organize, and change related options and elements in a document.
¾¾ Grouping panels improves the organization and workflow. Using the Panel tab, you can either group or ungroup,
or dock or undock panel windows.
¾¾ It is possible to customize the manner in which you want to work in Flash by changing the general default
settings as well as the settings for ActionScript, Auto Format, Clipboard, Drawing, Text, Warnings, PSD file
Importer, and AI File Importer.
¾¾ Merge drawing and object drawing are the two modes used to create shapes. The Tools panel in Flash includes
a variety of easy to use geometric vector shapes.
¾¾ The Tools panel in Flash includes a variety of simple geometric vector shapes that are easy to use. These tools
can be clicked and dragged on the stage to create shapes.
¾¾ The intersection point of two strokes is referred to as a Join. Miter, Round, and Bevel are the three settings
available in the Join menu. These settings can be used to create different join styles on drawings or shapes that
have intersecting lines.
¾¾ The Selection tool is used to select parts of an object by dragging over a portion of it.
¾¾ Layers are like transparent sheets of acetate stacked on top of each other. Layers assist you in making quick
changes by enabling you to organize your content in a document.
¾¾ Every document created in Flash contains at least one layer. Whatever you create gets placed in the default
layer automatically.
¾¾ A new layer that is created always has a single blank frame on which the content can be placed. By default, new
layers are named by the order in which they are created.
¾¾ Organizing layers includes putting them into folders, changing the order of the layers or folders, and moving
them from one folder to the other. You can organize the workflow by arranging folders and layers in a tree
structure.
1.6 Exercise
1. It is possible to revert to the default settings in Flash using the __________ option.
Make default
Frame rate
Match
Ruler units
Options
Window
Tools
Edit
Symbol
Join
Miter
Snapping
4. Objects that allow users to make changes to the properties of a shape at any point in time are referred to as
____________.
Primitive objects
Timelines
Tools panel
5. What does the pencil icon beside the layer name signify?
Users can modify the existing fills or strokes in Flash, using any of the following methods:
¾¾ By applying new attributes using either the Paint Bucket tool for fills or Ink Bottle tool
for strokes
¾¾ By selecting the fill or stroke on the stage and choosing new attributes from the appropriate
panel
In addition to the listed methods, fills or strokes that contain a gradient can be modified by using
the Gradient Transform tool.
The Tools panel comprises a Colors section that can be used to apply colors to fills and
strokes. The color section has two color buttons, namely, the Stroke color button and the Fill Figure 2.1:
color button. A color palette appears on clicking either of the buttons. In addition to the color Tools panel
showing two
palette, users can also use the Color dialog box for more color options. Refer to Figures 2.1
color buttons
and 2.2.
The Eyedropper tool allows you to select colors from any object on the stage. For example, if you want to select a
color from a photograph that you have imported, the Eyedropper tool is a good option for choosing colors that can
be used on another object as a fill.
From the Tools panel, select the Eyedropper tool. The pointer changes to an eyedropper. Position the pointer over
the stroke or fill of a shape to select a color. On selecting a color, the icon changes to that of a Paint Bucket tool or
the Ink Bottle tool so that the selected color can be applied on the desired object. On clicking the Eyedropper tool
over a stroke, it changes to an Ink Bottle. On clicking the Eyedropper tool over a fill, the tool changes to a Paint
Bucket. Refer to Figure 2.3.
Figure 2.3: Tools panel showing the Eyedropper tool, Paint Bucket tool, and the Ink Bottle tool
The following buttons are available at the bottom of the Colors section of the Tools panel. These buttons can be
used to set colors.
¾¾ Black and white : This button is used to set the fill color to white and stroke color to black.
¾¾ No color : This button is used to remove the color from the selected object.
¾¾ Swap colors : This button is used to swap (exchange) the fill and stroke colors.
2.1.2 Applying Colors
Following are the various ways of applying colors in Flash:
¾¾ Using the Colors section of the Tools panel
¾¾ Using the Paint Bucket tool to apply Fill colors
¾¾ Using the Ink Bottle tool to apply Outline/Stroke colors
¾¾ Using the Properties panel to apply colors
■■ Using the Colors section of the Tools panel
The Fill Color button or Stroke Color button can be used to apply the selected fill or stroke color on the chosen
object.
■■ Using the Paint Bucket tool to apply fill colors
The Paint Bucket tool stores the fill color that has been set in the Property Inspector window or in the Tools panel.
It is used to apply a fill to objects with a closed stroke. Clicking a shape with the Paint Bucket tool, changes the fill
of the specific object. The following options are available in the Option toolbar of the Paint Bucket tool.
¾¾ Gap size - This option is primarily used to fill shapes with gaps. Choosing any of the close options fills a shape
that has gaps. Incase if gaps have to be filled manually before filling the shape, it can be done by clicking the
Don’t Close Gaps option.
¾¾ Lock fill - This option is used to lock a gradient or bitmap fill such that it appears as if the gradient extends over
the entire stage through discrete objects. Objects painted with the fill appear as masks that reveal the underlying
gradient or bitmap. To apply color using the Paint Bucket tool, begin by selecting the color from the Fill Color
button on the Tools panel. Then, click the Paint Bucket tool on the Tools panel. The pointer changes to a small
Paint Bucket. Click inside a shape on the stage. As you click, you will notice that the new fill color is applied.
■■ Using the Ink Bottle tool to apply Outline/Stroke colors
The working of the Ink Bottle tool is very similar to that of the Paint Bucket tool. The difference being, the Ink
Bottle tool is used to apply stroke colors; whereas, the Paint Bucket tool is used to apply fill colors. To use this
tool, select the desired color and then click the object whose stroke color has to be changed. You need not click the
outline, you can click anywhere on the object to change the stroke color.
■■ Using the Properties panel to apply colors
Using the Properties panel, it is possible to change the color of the outline, fill, and other properties of the object. On
selecting a color from the color palette, the selected color will reflect on the selection. It is also possible to change
the style and thickness of the outline of the selected objects. Refer to Figure 2.4.
To create custom colors, from the Window menu, open the Color panel. Select the RGB or HSB option. Set values
between 0 and 255 for the RGB option and percentage between 0 and 100 for the HSB options. Enter an Alpha value
between 0 and 100. When done, click the Options button and then click Add Swatch.
In Flash, users also have the option of changing the number of colors and direction of the Gradient fill.
Overflow modes are additional features available in Flash CS6. These features provide additional controls over the
linear and radial gradients when used with the Flash player.
Like the fills, gradients can also be applied to strokes. This can be done by selecting the stroke before applying
the gradient.
It is possible to apply gradients from the available gradient fills (presets). To apply a gradient, begin by selecting the
object and then click the Fill Color button. A palette of color swatches appear with a list of preset gradient options
at the bottom of the palette. Refer to Figure 2.5.
You can add up to 15 colors to a gradient, control the location of the gradient focal point, and also apply other
parameters. A gradient works very similar to a fill or a stroke. It can be saved as a swatch using the Color panel
Options button and added to other shapes with the Paint Bucket tool.
■■ Changing gradient types
Using the Color panel, the type of gradient can be changed as shown in Figure 2.6. To do so, in the Color panel,
click the Color Type drop-down arrow. Then, as per the requirement, click Linear Gradient or Radial Gradient. You
can select the gradient display style from any of the Flow buttons. The styles available are as follows:
¾¾ Extend color
¾¾ Reflect color
¾¾ Repeat color
Figure 2.6: Difference between Linear gradient fill and Radial gradient fill
■■ Creating gradients
To create gradients, begin by selecting the fill or stroke of the desired shape on stage. Then, click the Color Type
drop-down list in the Color panel to select the fill style. After selecting the fill style, select the gradient display style.
To do so, click any of the Flow buttons. Click in the Gradient bar to create a color proxy. The color proxy is indicated
by a little box with a triangle on the top. Now, to add color to a gradient, click one of the color proxy indicators to
select it. Then, click a new color from the Color Picker box. On placing the mouse pointer above the Color Picker
box, you will observe that the mouse pointer changes to a circle. Finally, drag the color proxy indicator along the
Gradient bar to adjust the color placement.
The Gradient Transform tool is available under the Free Transform tool. It is used to modify the gradient applied to
an object. With the help of the tool you can move, rotate, or scale the gradient and change the position of the focal
point. Refer to Figure 2.7.
You can use the tool for gradient fills as well as bitmap fills. You will see a bounding box around the object. On the
bounding box you will observe various handles to edit the gradient. The use of the handles is explained as follows:
¾¾ Center Point: This handle appears like a four-way arrow that is used to move across the different colors of the
gradient.
¾¾ Focal Point: This handle appears with the Radial gradient. It appears like a small triangle and is used to move
the focal point of the gradient.
¾¾ Width: This handle is used to increase or decrease the width of the gradient. A square with a double-headed
arrow represents this handle.
¾¾ Size: This handle is used to increase or decrease the size of the gradient. The rollover icon for this handle is a
circle with an arrow inside it.
¾¾ Rotation: This handle is used to rotate the gradient. The rollover icon for this handle are four arrows in the
shape of a circle.
Figure 2.7: Gradient transform tool
■■ Fill Lock
As the number of shapes increases in your movie, it can become tedious to manage each object separately. On
applying gradient fills on several objects, users can choose to span a gradient across these objects. They can also
apply a separate gradient on each object. The Fill Lock feature controls the application of the fill. This feature locks
the position of the fill in relation to the position of the shapes. On applying the same gradient on multiple shapes with
the Fill Lock feature turned off, the fill is applied to each shape independently. Refer to Figure 2.8.
It is also possible to lock gradients. To do so, select the objects you want to fill. Then, select a gradient. Click the Paint
Bucket tool and then, click the selected shapes. During the process, ensure that the Fill Lock is not selected.
From the Window menu, click Extensions. From the submenu that appears, click Kuler. To browse for themes,
click the Browse tab. In the Search box, enter the name of a theme, a tag, or a creator, and then press Enter. A
browse list appears. To narrow down the list, click the pop-ups, and then select the filter options of your choice based
on the ratings. To browse the desired theme, click the View previous set of themes or View next set of themes
button. From the list that appears, select a theme in the panel.
After deciding on a theme, the next step is to add it to the Swatches panel. To add the selected theme, click the Add
Selected Theme To Swatches button.
■■ Create panel tools
There are several options available under the Create tab of the Kuler panel. Begin by clicking the Create tab and
then click the Select Rule list arrow. Then, select a harmony rule or choose Custom. On choosing the harmony
rule, you can create a theme with complimentary colors. This is because the harmony rule uses base colors as the
basis for generating the colors in the color group. On the contrary, selecting Custom creates a theme that uses
free-form adjustments.
After selecting the rule, you can manipulate colors in the color wheel. As you adjust the colors, you will observe that
the selected rule is applied to the color group. You can also adjust the color brightness by dragging the slider beside
the color wheel.
To define a base color, drag the base color marker (the double-ringed color marker that appears largest) around the
wheel. You can also set the base color by adjusting the color sliders at the bottom of the dialog box. Select any of
the four colors in the color group as the base color. Then, select the color’s swatch and click the bull’s-eye button
below the color group. Set the host application’s foreground/background color or stroke/fill color as the base color.
Then, click one of the first two buttons below the color group.
Incase if you want to remove a color, you can do so by selecting the desired color swatch and clicking the Remove
Color button. This button appears below the color group. To add a new color, select an empty color swatch and click
the Add Color button. Double-click the desired swatch to set it as the active color. Refer to Figure 2.10.
Figure 2.10: Kuler panel - Create tab
■■ Creating or editing a theme
In Flash, it is possible to create your own theme or edit an existing theme. To create a theme, click the Create tab.
The Create panel appears.
To edit a theme, click the Browse tab. Then, select the theme that you want to edit. Click Edit Theme in the Create
Panel button at the bottom of the panel. This opens the Create panel where you can edit themes.
After editing themes, you can either save the themes, or add it to the Swatches panel. Alternatively, you can also
upload it to Kuler. To save a theme, click Save Theme. Enter a name for the theme in the space provided. Then,
click Save. To add themes to the Swatches panel, click the Add This Theme to Swatches button. To upload a
theme to the Kuler panel, click the Upload Theme to Kuler button.
eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Using the Kuler Panel>>
Creating or editing a theme
2. The Free Transform tool is available under the Gradient Transform tool.
True False
To ungroup objects, begin by selecting objects that have to be ungrouped. Then, from the Modify menu, click Ungroup.
Alternatively, you can press the Ctrl+Shift+G keys on the keyboard. Incase if you wish to edit objects without ungrouping
them, you can do so by double-clicking the individual objects.
On selecting an object within a group, it is highlighted with a dotted pattern; whereas, on selecting a group it
is highlighted with bounding boxes.
To align objects, begin by selecting the objects. Then, from the Modify menu, click Align. Alternatively, you can press
the Ctrl+K keys. In the Align panel that appears, click an alignment option. You will observe that objects are aligned.
Following are some of the options under the Combine Objects submenu:
¾¾ Union: This option combines the selected objects, converting them into a single object.
¾¾ Intersect: This option retains the common portion of the selected objects, removing the remaining part.
¾¾ Punch: One object removes the portion of the underlying overlapping object. The punching depends on the
order of the objects.
¾¾ Crop: The top object crops the portion of the underlying object.
2.4.4 Using Rulers
Rulers are used to measure the width and height of Flash elements. They also help you decide the placement of objects
on the stage by placing guides on screen.
Rulers are placed at the top and left side of the work area. You can view rulers by selecting the Ruler command from
the View menu. Alternatively, you can press the Ctrl+Alt+Shift+R keys.
The rulers can display various units of measurement like inches, millimeters, centimeters, or points. By default, the units
are measured in pixels. At any point in time, it is possible to change the unit of measurement. To do so, from the Modify
menu, click Document. Then, from the Ruler Units list arrow, select a unit of measure. Click OK.
Guides and grids are visible only in the Flash development environment. They are not exported in a Flash
movie.
The display, behavior, and characteristics of guides and grids can be altered to fit your needs.
■■ Grids
Grids are a series of crisscrossed lines that aid in aligning objects to each other on the stage.
To show or hide the grid, from the View menu, select the Grid command. Then, select Show Grid. Alternatively,
you can press the Ctrl+’ keys. To change the settings, from the View menu, select the Grid command. Then, select
Edit Grid. Alternatively, press the Ctrl+Alt+G keys. Using the Color box, you can select the color for the grid lines.
Refer to Figure 2.13.
Guides are dragged from the ruler. You can drag horizontal and vertical guides from the horizontal and vertical rulers
respectively. Once you drag the guides, you can either hide or show them as per your requirement. To show or hide
the guides, from the View menu, select Guides. Then, select Show Guides. Alternatively, you can press the Ctrl+;
keys.
At any point in time, you can lock guides at a specific position. To do so, from the View menu, select Guides. Then,
click Lock Guides. Alternatively, you can press the Ctrl+Alt+; keys.
It is also possible to change the color of the guides. To do so, from the View menu, select Guides. Then, click Edit
Guides. Alternatively, you can press the Ctrl+Alt+Shift+G keys. Refer to Figure 2.14.
In the Guides dialog box, you can select a guide color from the Color list.
¾¾ To show or hide guides, select or deselect the Show Guides check box.
¾¾ To enable or disable snapping, select or deselect the Snap To Guides check box.
¾¾ To enable or disable the movement of guides, select or deselect the Lock Guides check box.
¾¾ To define a level of sensitivity for the guides, click the Snap Accuracy list arrow. You can select from Must Be
Close, Normal, and Can Be Distant.
¾¾ Selecting Clear All removes all the guides from the scene.
¾¾ Clicking Save Default sets the current guides as the default guides.
2.4.6 Snapping
Snapping is a feature that guides the movements of the objects on stage. It helps in aligning elements accurately and
in relation with each other. The snapping controls can be turned on or off from the Snapping submenu from the View
menu or from the Edit Snapping dialog box. To access the Edit Snapping dialog box, from the View menu choose
Snapping. Then, choose Edit Snapping.
The snapping settings can be controlled in the Edit Snapping dialog box, either in the Basic view or in the Advanced
view. The Basic view, displays only the top five check boxes; whereas, the Advanced view, expands the dialog box to
include additional snap align settings, as depicted in Figure 2.15.
Description of the options available in the Edit Snapping dialog box are as follows:
¾¾ Snap align settings: It is possible to enter a value for the distance an object that has to be before it snaps to
boundaries of the stage movie (in pixels).
¾¾ Object spacing: You can enter a value for the horizontal and vertical edge tolerance (in pixels).
¾¾ Center alignment: You can align the objects, either by using the Horizontal center alignment or Vertical center
alignment.
¾¾ Save Default: This option makes the snap align setting as default for future use.
The available snapping modes are as follows:
¾¾ Snap Align
¾¾ Snap to Objects
¾¾ Snap to Grid
¾¾ Snap to Guides
¾¾ Snap to Pixels
Refer to Figure 2.16.
A large file size can be an issue; hence, it is best to reduce the size of your bitmap file before you can import it in Flash.
For example, if the size of the image in your final movie is defined as 160 x 160 pixels, then it is best to resize the image
to the desired size and then import it in Flash. This will help in deriving at higher quality images with smaller files.
Following are the two methods in which you can import files in Flash:
¾¾ Import to stage: In this method, the bitmap is stored in the Library and a copy of the same is placed on the
stage.
¾¾ Import to library: In this method, the bitmap is stored in the Library.
To import a bitmap on stage, from the File menu, select Import. From the submenu that appears, click Import to Stage.
In the dialog box that appears, select the desired file from the respective folder. Then, click Import. Refer to Figure 2.17.
When you edit a bitmap in its native program and re-save or update it to the hard drive, Flash automatically updates
the bitmap. You can also update an image automatically, if the location of the image has been changed. In addition to
replacing or updating the changes, you can also import another image to replace the bitmap in the Library.
Using the Bitmap Properties dialog box, you can manually update or replace an image. To access this dialog box,
from the Library panel, right-click the bitmap that you want to update or replace and then click Properties. The Bitmap
Properties dialog appears as shown in
Figure 2.18.
For detailed step-by-step procedure, refer to Figure 2.18: Bitmap Properties dialog box
demo Importing Bitmap from:
eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Getting Images in Flash>>
Updating Imported Bitmaps
The default preferences of the PSD file that is imported can be modified. To do so, from the Edit menu, select
Preferences. In the Preferences panel that appears, select the PSD File Importer on the left side. The associated
options appear on the right side. Refer to Figure 2.20.
On importing an Illustrator artwork as an AI, EPS, or PDF file, Flash preserves the same attributes as for the Illustrator
artwork. In addition, if Illustrator files contain layers, they can be imported using any of the following ways:
¾¾ Convert Illustrator layers to Flash layers
¾¾ Convert Illustrator layers to Flash frames
¾¾ Convert all Illustrator layers to a single Flash layer
Illustrator and Flash support pasted artwork in either of the following ways:
¾¾ On selecting all the top-level layers in the Illustrator artwork and pasting them into Flash, the layer properties
are preserved.
¾¾ Non-RGB Illustrator colors (CMYK, grayscale, and custom) convert to RGB in Flash. RGB colors paste as
expected.
¾¾ When you import or paste Illustrator artwork, you can use various options to preserve effects (such as drop
shadow on text) as Flash filters.
¾¾ Flash preserves Illustrator masks.
True False
The Library panel arranges the contents of the imported AI file in an alphabetical order. This happens
automatically without affecting the hierarchical grouping and folder structure.
You can change the default preferences of an AI file. To do so, from the Edit menu, select Preferences. Then, select
AI File Importer located on the left side. The associated options appear on the right side. Refer to Figure 2.22.
For a detailed step-by-step procedure, refer to demo Importing Illustrator Artwork from:
eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Getting Images in Flash>>
Importing Illustrator Artwork
2.5.5 Tracing Bitmap
The Trace Bitmap command converts a bitmap into a vector graphic with editable, discrete areas of color. You manipulate
the image as a vector graphic. This helps in reducing the file size. When you convert a bitmap to a vector graphic, the
vector graphic is no longer linked to the bitmap symbol in the Library panel. If the imported bitmap contains complex
shapes and many colors, the converted vector graphic might have a larger file size than the original bitmap. To find a
balance between the file size and image quality, try a variety of settings in the Trace Bitmap dialog box. Refer to Figure
2.23.
2.6 Summary
In this session, Working with Colors and Images, you learned that:
¾¾ Colors help in bringing out the important aspects of an animation.
¾¾ Colors can be selected either by using the Tools panel or by using the Eyedropper tool.
¾¾ Colors can be applied either by using the Colors section of the Tools panel or by using the Paint Bucket tool.
They can also be applied using the Ink Bottle or the Properties panel.
¾¾ Gradients are multicolored fills that help create an illusion of lighting, in turn making your objects look more
realistic.
¾¾ Radial and linear are the two types of gradients. It is also possible to customize gradients in Flash.
¾¾ The Kuler panel is an extension to Flash with a lot of additional features that proves handy while creating colors
and themes that match your requirements.
¾¾ Organizing objects save the file from unintentional changes.
¾¾ Rulers help you measure the width and height of Flash elements. Guides and grids help in aligning the elements.
¾¾ While importing images, it is possible to retain the layers of Photoshop files. The images can be imported either
as a flattened layer or with editable layer styles.
2.7 Exercise
1. Radial fills are applied in a straight line; whereas linear fills are applied in a circular fashion.
True
False
2. A cross hair appears against your selection indicating that the ___________.
Fill command
Overflow modes
Gradient panel
Four-way arrow
Double-ended arrow
5. On importing Illustrator files in Flash, the masks associated with the imported files are preserved.
True
False
S e s s io n 3
Working with Text
Learning Outcomes
In this session, you will learn to:
¾¾ Work with different types of text in Flash
3.1 Overview
Following two types of text can be created in Flash:
¾¾ Classic: This text format provides standard capabilities that are available in the previous versions of Flash.
¾¾ Text Layout Framework (TLF): This text format comes with advanced text capabilities that can be used in
Flash Player 10 and ActionScript 3.0 or later.
To create classic static text, from the Tools panel, select the Text tool. In the Properties panel, select Classic Text from
the Text Engine drop-down list. From the Text Type drop-down list, select any one type of classic text, namely Static,
Dynamic, or Input. Then, click on the stage to create a text box. You can either click on stage to create a single line text
box or drag the cursor on stage to create a text box of the desired dimension. You can now enter text in the defined text
box. Refer to Figure 3.1.
It is possible to create horizontal text with a left-to-right flow or static vertical text with either a right-to-left or left-to-right
flow.
When creating classic text, users can place text on a single line that expands as you type, or in a fixed-width field (for
horizontal text), or fixed-height field (for vertical text) that expands and wraps words automatically. All classic text fields
support Unicode.
Click here to know more about creating Classic text.
To create TLF text, click the Text tool from the Tools panel. From the Properties panel, click the Text Engine drop-
down list and select TLF Text. Then, select the type of text from the Text Type drop-down list. Read only, Selectable,
or Editable are the three types of TLF text available for use. Click on the stage to create a text box and begin entering
text. Refer to Figure 3.2.
On selecting the TLF text box, a black bounding box with square handles appears around it. You can resize the text box
by clicking and dragging the handles to the desired shape. On resizing the text box, you will observe that the text within
the box wraps to accommodate itself to its new size.
While converting text from Classic to TLF or vice versa, avoid converting it back and forth more than once. This
will lead to less discrepancies in the settings.
While converting between TLF and Classic text, Flash converts text types as follows:
¾¾ TLF Read Only is converted to Classic Static
¾¾ TLF Selectable is converted to Classic Static
¾¾ TLF Editable is converted to Classic Input
¾¾ Color: This option lets you set a color for the text by
clicking the Color box.
¾¾ Tracking (TLF text only): This option lets you set the
space between characters and words on a single line.
Changes made using this option affect the entire line.
¾¾ Auto Kern: This option applies kerning information to the
built-in fonts of Latin characters. For Asian characters,
this option can be applied to characters that have kerning Figure 3.5: Leading
information built into them.
¾¾ Highlight (TLF text only): This option lets you highlight text.
¾¾ Anti-Alias: This option adjusts the pixels at the edge of a shape by helping them blend with the background.
This feature makes text appear smoother and integrated. Flash includes Flash Type, a text rendering feature
that improves anti-aliasing and readability of fonts. This feature is enabled whenever Flash Player7 or higher is
the selected player and anti-aliasing is set to custom or readability. Refer to Figure 3.6.
Figure 3.6: Anti-alias
Rotation (TLF Text Only): This option helps rotate individual characters. The following values are available for rotation:
¾¾ 0o: This value forces all characters to have no rotation.
¾¾ 270o: This value is available only for Roman text and Vertical orientation.
¾¾ Auto: This value specifies a 90 degrees counter clockwise rotation for full width and wide characters only.
¾¾ Superscript: Reduces the size of the characters and moves it slightly above the normal line of type.
¾¾ Subscript: Reduces the size of the characters and moves it slightly below the normal line of type.
¾¾ Underline (TLF Text only): Places a horizontal line below the characters.
¾¾ Strikethrough (TLF Text only): Places a horizontal line through the center of the characters.
¾¾ Selectable (Classic text only): This option enables selection of static text, either horizontal or dynamic, by
viewers using the application.
¾¾ Render Text as HTML (Classic text
only): This option preserves rich text
formatting that includes fonts and
hyperlinks.
¾¾ Show border around text (Classic
text only): On selecting this option a
black border and a white background
appears around the text field.
Although the text boxes are linked, each text box retains its own properties. You can unthread a text box at any point in
time.
To link text, create a TLF text box and begin typing in the box that appears. Alternatively, you can paste text from the
Clipboard until it fills the entire text box. Click the Overflow icon on the selected text box. The pointer changes to the
Loaded Text cursor. To create a new text box for the overflow text, click a blank area or drag to create a text box. You
will notice that the overflow text from the first text box threads to the second text box. Refer to Figure 3.8.
You can unlink text by double-clicking the In-port or the Out-port icon. Alternatively, you can delete either of the text
boxes. On deleting the text, you will observe that the text in the deleted text box is moved back to the remaining text
box thread.
Quick Test 3.1
1. Classic, Static, and Dynamic are the three text types available in Flash.
True False
2. The anti-alias option applies kerning information to built-in fonts of Latin characters.
True False
3. The Overload icon resembles appears as a red minus sign at the bottom of the text box.
True False
This option defines the behavior of the text box in response to the exceeding text within a text box. Single line,
Multiline, Multiline no wrap, and Password are the options available in the Behavior option. On choosing the
Password option, characters appear as dots instead of letters. This is for security sake. Moreover, this option is
available only for editable text; it does not work with Read Only or Selectable type of text.
■■ Max Chars
Specifies the alignment of text within a text box. Alignment settings include:
¾¾ Align top: Aligns text down from the top of the container.
¾¾ Align center: Aligns text to the center of the container.
¾¾ Align bottom: Vertically aligns lines of text up from the bottom of the container.
¾¾ Justify: Evenly distributes lines of text vertically between the top and bottom of the container.
¾¾ Column Count: Defines the number of columns of text that can be placed within area text containers. The
default value for this setting is 1 and the maximum value that can be set is 50.
¾¾ Column Gutters: Specifies the gutter or spacing between each column in the selected container. Here, the
default value is 20 and the maximum value is 1000.
¾¾ Padding: Specifies the width of all the four margins of the container.
¾¾ Border Color: Defines the stroke color of the sides of the container. By default, the stroke is defined as no
border.
¾¾ Border Width: Specifies the width of the stroke applied to the sides of the container. This is enabled only when
a border color is chosen. The maximum value of the width is 200.
¾¾ Background Color: Specifies the color of the background behind the text. By default, no color is applied to the
background.
¾¾ 1st Line Offset: Specifies the alignment of the first line of text with the top of the text container. For example,
you can define the placement of the first line of text in relation to the top of the container. The 1st Line Offset
has the following options:
●● pt: Specifies the distance in points between the baseline of the first line of text and the top inset of the frame.
It enables a field for specifying the point distance.
●● Auto: Aligns the top of the line, based on the tallest glyph, with the top of the container.
●● Ascent: The distance between the top inset of the text container and the baseline of the first line of text is
the height of the tallest glyph in the font (typically the “d” character in Roman fonts).
●● Line Height: Line height or leading is the distance between the top inset of the text container and the
baseline of the first line of text.
●● Direction: Specifies the direction of text within a container, left-to-right or right-to-left. On applying this
option at the paragraph level, direction controls the left-to-right or right-to-left text; indents and punctuations
are used by the paragraph. On applying this option at the container level, it controls the column direction.
●● Locale: Sets the Locale property at the flow level. The Direction and Locale options are available when the
Show Right-to-Left option is selected from the Options menu of the Properties panel.
To link containers:
2. Click the In port or the Out port of the selected text container. The pointer changes to a loaded text icon indicating
that the containers can be linked.
3. To link to an existing text container, click the target text container to link it.
4. To link to a new text container, click on the stage. A new container with same size and shape of the original container
is created. The containers are now linked and text can flow between them.
5. Alternatively, to create a container with different dimensions, drag the mouse cursor on the stage. It is also possible
to add a new container between two linked containers.
To unlink containers:
2. Double-click the In-port or Out-port that has to be unlinked. The text reflows in the first of the two containers.
The In-port and Out-port positions on the text container depends on the direction of the flow of the container.
It also depends on the vertical or horizontal settings of the container. For example, the In port is on the upper
left and the Out port is on the lower right if the text flow is Left-to-Right and horizontal. On the contrary, the In
port is on the upper left and the Out port is on the lower right.
On linking two text containers, the second text container acquires the direction of flow and locale of the first
container. Inspite of unlinking, these settings exist in the second container.
2. Set the Direction of the UIScrollBar component to Horizontal in the Component Parameters section of the Property
Inspector.
3. Drag the UIScrollBar component instance to the top or bottom of the text container.
The UIScrollBar component snaps to the top or bottom of the text container.
3.4 Changing Advanced Character Options
Advanced options for TLF text are available in the Properties panel. You can change the case of the text, specify a
baseline for multi-language text or baseline shift (such as superscript or subscript), apply line breaks, and select the
users’ language and region. Similar to a feature in Adobe Photoshop, you can apply blending modes and color effects
to a text box in front of another element, such as a graphic, to create a new look from the mix of color pixels. Refer to
Table 3.1 to view the options available in the Advanced Character section of the Properties panel.
Options Description
Link This option is used to create a text hyperlink.
Target This is used with the Link option to specify the window
into which the URL loads into. The following values are
associated with this option:
¾¾ Self: Specifies the current frame in the current
window.
¾¾ Blank: Specifies a new window.
¾¾ Parent: Specifies the parent of the current frame.
¾¾ Top: Specifies the top-level frame in the current
window.
¾¾ Custom: Specifies a value for the browser
window or frame that will be open when the SWF
file is playing.
Case Used to change the case of the text - uppercase or
lowercase.
Digit Case Adopts the settings specified by the font designer.
Digit Width Alters the text to proportional or tabular widths.
Dominant Baseline Alters the multi-language text to a common baseline.
Alignment Baseline Alters the baseline alignment for multiple language text.
Ligatures Alters the running together of letters. For example, Th.
Break Defines the use of line breaks.
Baseline Shift Specifies the shift in baseline in points or percentages.
Superscript or Subscript can be chosen for standard shifts.
Locale Defines the language and region of the user.
Table 3.1: Options available in the Advanced Character section of the Properties panel
While working with Asian text, you can use the Advanced
Paragraph section to select options for Mojikumi, Kinsoku
Shori Type, and Leading model. Refer to Figure 3.12.
●● Auto: Justification is applied based on the locale selected in the Character and Flow section of the Text
Property inspector. This is the default setting.
●● East Asian: This option uses the East Asian justification rules.
¾¾ Kinsoku Shori type
This model is used to specify values for handling Japanese kinsoku characters that appears in the middle of a
line and not at the beginning or end of a line. The following values are available in the Kinsoku Shori type:
●● Auto: This is the default setting and can be resolved based on the locale selected in the container and flow
section of the Text Property inspector.
●● Prioritize Least Adjustment: Bases justification on either expanding or compressing the line, whichever
gives a result closest to the desired width.
●● Push In Kinsoku: Bases justification on compressing kinsoku at the end of the line. Kinsoku expands if no
kinsoku occurs or if that end-of-line space is insufficient.
●● Roman Up
●● Ideographic Top Up
●● Ideographic Center Up
●● Auto
Click here to know more about the values available in the Leading Model.
In addition to the mentioned points, you can change the orientation of Classic text to display it horizontally, vertically, or
horizontally left-to-right as shown in Figure 3.13.
Another way of orienting text is by using the Rotate button in the Character section of the Properties panel. This button
can be used to rotate text inside vertical text boxes. Refer to Figure 3.14.
For detailed step-by-step procedure, refer to demo Text Orientation Classic from:
eResources 4 Me>> My Varsity>> Module Name>> Show Me How>> Changing Advanced Character Options>>
Changing Text Orientation
eResources 4 Me>> My Varsity>> Module Name>> Show Me How>> Changing Advanced Character Options>> Using
Break Apart
True False
2. The Break Apart command is available under the Modify menu.
True False
3.5.1 Workflow for Authoring Multilanguage Text with the Strings Panel
Using the Strings panel, users can create and update multilingual content and specify content for text fields that span
multiple languages. It is also possible to have Flash Professional automatically determine the content that should
appear in a certain language based on the language of the computer running Flash Player.
1. Any text to enter in another language must be in a dynamic or input text field.
2. A column for the language is added to the Strings panel. When you save, test, or publish the application, a folder
with an XML file is created for each language.
4. A folder is created for each language you select, and within each language folder is an XML file for that language.
5. Author in your native language and let the translators make the translation. They can use translation software
directly in the XML files or in the FLA file.
6. When you receive the translations from your translators, import the translated XML files back into the FLA file.
It is best to select languages that are available in the menu or from any other Unicode-supported language.
1. From the Window menu, click Other Panels. From the submenu that appears, click Strings and then click Settings.
2. In the Languages box, select the desired language and then click Add. Incase if the languages are not displayed
in the Languages box, type a language code in the format, xx and click Add. The language code is from ISO 639-1.
4. Select a default language from the default runtime language menu. This language appears on systems that do not
have one of the active languages you selected.
5. T
o load an XML file for the languages from a different URL at runtime, type the URL in the URL text field and click
OK. A column for each selected language appears in the Strings panel. The columns appear in alphabetical order.
6. S
ave the FLA file. Notice that a folder for each chosen language has been created in the same folder indicated in the
SWF publish path. If no SWF publish path has been selected, it is created in the folder where the FLA file resides.
Within each language file an XML file is created that is used to load translated text.
1. From the Window menu, select Other Panels, and then click Strings. From the sub menu that appears, click
Settings.
2. From the Active Languages field, select the language to be removed and click Remove.
3. Repeat the steps to remove the unwanted languages. Once done, click OK. Notice, the column for each removed
language no longer appears in the Strings panel.
When you remove a language from the Strings panel, the language XML file is not deleted from the local file
system. This lets you add the language back into the Strings panel by using the previous XML file, and prevents
accidental deletion. To completely remove the language, you must delete or replace the language XML file.
1. From the Window menu, click Other Panels, and then click Strings.
2. Click the Text tool to select it. Create an input or dynamic text field.
3. Keeping the Text tool selected, type a unique ID in the ID field of the Strings panel.
4. Click the Settings button and select a language or languages from the list in the Settings dialog box. The selected
languages should include the default language in which you plan to publish your work.
5. Click Apply.
If a static text field is selected on the Stage, the Stage text selection section on the Strings panel displays the
message “Static text cannot have an ID associated with it.” If a non-text item is selected or multiple items are
selected, the message “Current selection cannot have an ID associated with it” appears.
Steps to add a string ID to a Strings panel without assigning it to a text field are as follows:
1. From the Window menu, click Other Panels, and then click Strings.
2. Click the Settings button and select a language or languages from the list in the Settings dialog box. The selected
languages should include the default language in which you plan to publish your work.
1. Select the Text tool and create an input or dynamic text field.
2. Type the name of an existing ID in the ID section of the Strings panel. Then click Apply.
Press Shift+Enter to apply the ID to the text field, or Enter if the focus is on the ID field.
On changing the language on the stage, any new text typed or previously entered text strings also appear in the
changed language.
This feature affects only text input on the stage, not text entered in the Actions panel. This feature is available
for all supported Windows operating systems and Mac OS X.
3.6 Summary
In this session, Working with Text, you learned that:
¾¾ Classic text and Text Layout Framework (TLF) are the two types of text available in Flash.
¾¾ Classic text is further divided into static, dynamic, and input.
¾¾ Flash gives the option of converting classic text into TLF format and vice versa without losing out on the details.
¾¾ Using the Property Inspector, it is possible to format text in Flash.
¾¾ In addition to text formatting, it is also possible to format paragraphs for their alignments, margins, indents, and
spacing.
¾¾ Excess text within a text box is denoted using the Overload icon that is accomodated by creating a text thread
link to new text box or an existing text box. The In-port and Out-port icons are used to unlink the text, if required.
¾¾ The Container and Flow sections available in the Property panel of the TLF text box can be used to create text
columns similar to those seen in newspapers. Using this feature, users can specify the number of columns, the
gutter and padding size between columns, maximum number of characters, alignment of text, and the border
and fill colors of the columns.
¾¾ Text linking feature is available only for TLF text and does not apply to Classic text blocks. Text containers can
be threaded from frame to frame, and inside symbols, as long as the threaded containers are all within the same
timeline.
¾¾ The UIScrollBar component is used to make a TLF text container scrollable.
¾¾ A paragraph model comprises a combination of Leading Basis and Leading Direction. Leading Basis determines
the baselines of two consecutive lines that are intended to be at a specific distance from each other. On the
contrary, Leading Direction determines the direction in which the line height is measured.
¾¾ The Strings panel in Flash helps users create and update multilingual content. Upto 100 languages can appear
on the stage and in the Strings panel for translation.
3.7 Exercise
1. The three types of TLF text available for use are Font style, Selectable, and Editable.
True
False
TLF Selectable
Classic input
Classic Static
3. The ____________ option lets users control the space between characters.
Leading
Letter spacing
Auto-Kern
Tracking
4. On clicking the Overflow icon, the pointer changes to a Loaded Text cursor.
True
False
5. With Flash Professional, users can use ____________ and standard Western keyboards to enter Asian characters
on the stage.
In Flash, a symbol is a reusable element that can be stored in the Flash Library and an instance is a copy of that symbol.
These symbols can be repeatedly used in any movie by inserting an instance of the symbol in the frame in which the
user wants it to appear.
A symbol can be an object you draw with Flash drawing tools, or a movie clip. Inserting a copy of the symbol in a project
indicates that an instance has been inserted. Since the instance references the original symbol, it does not affect the
size of the file.
To create a new symbol, select the New Symbol command from the Insert menu. Enter a name for the symbol.
Select a symbol type from the Type drop-down list and click OK. Refer to Figure 4.1.
After giving a name to the symbol, Flash switches to the symbol edit mode, where you can use the drawing tools to
create a new symbol. Refer to Figure 4.2.
The name of the symbol appears above the stage area. You can save the symbol and exit the symbol edit mode by
clicking the Scene Name link that appears to the left of the name of the symbol.
■■ Creating an existing object to a symbol
To convert an object into a symbol, begin by selecting the object on the stage. Then, from the Modify menu, click
Convert to Symbol. Type a name for the symbol in the space provided. Then, select a symbol type from the Type
drop-down list and click OK.
The Properties panel also has the looping section that helps control the graphic/movie clip playback. The options
available in this section are as follows:
¾¾ Loop: This is the default setting for graphic symbols. If the graphic symbol extends beyond its original length
along a timeline, then the symbol restarts. Graphic symbol looping is dependent on the main timeline. You have
to match the number of frames on the main timeline with the number of frames that you want to play in the
graphic symbol timeline.
¾¾ Play once: This option does not play the graphic symbol more than once.
¾¾ Single frame: This option holds the graphic symbol on one frame such that it behaves like a static graphic. A
specific frame can be selected within the graphic symbol timeline to display as the static graphic. However, the
appearance of the graphic symbol is the same regardless of how far it extends along a timeline.
¾¾ Applying blend modes to movie clips: Flash Pro blend modes are used to create composite images.
Compositing is the process of varying the transparency or color interaction of two or more overlapping images.
Using blend modes it is possible to add a dimension of control to the opacity of objects and images. Users
can create highlights or shadows that bring out the details from an underlying image. They can also colorize a
desaturated image.
The Blend panel is available in the Properties panel and can be applied to a movie clip or button symbol
instances. Blends are rendering tools that blend an image with underlying base images to create an image that
is a mix of the two. The blended image will interact with any underlying images that it overlaps - even if they are
not on the same layer. Refer to Figure 4.5.
2. Loop is the default setting for graphic symbols that does not play more than once.
True False
To make changes to a symbol, you need to first enter into the symbol editing mode. This way you can view and make
changes to the symbol’s timeline. Symbols can be edited in either of the following ways:
¾¾ Using the Edit in Place command: This option can be exercised using the Edit in Place command from the
Edit menu. On selecting this option, the object that has to be edited is prominent and the space around it, along
with the other objects is dimmed out. This distinguishes the object to be edited from the others. Moreover, the
name of the symbol appears at the top left, beside the name of the scene, on the Information bar. Refer to
Figure 4.6.
For detailed step-by-step procedure, refer to demo Editing Symbols and Swapping from:
eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Swapping Symbols
Filter presets are available in the Filters section of the Property Inspector.
Presets are available under the Filters menu. Refer to Figure 4.10.
An object can have more than one filter. Each time a new filter is added to
an object, it is appended to the Property Inspector. Moreover, it is also
possible to delete a previously applied filter. Frequently used filters can be
accessed from the filter settings library.
To add a filter, click the Add Filter button. Select a filter from the list of
available filters. Experiment with the settings for the desired look.
To remove a filter, select the filter to be removed and click the Remove
Filter button.
Figure 4.10: Add filter menu
It is also possible to delete or rename any presets.
2. From the Filters panel, select the filter to copy and click the Clipboard button.
3. Click Copy Selected from the pop-up menu. Incase if all the filters have to be chosen, select Copy All.
4. Select the object to which the filter has to be applied. Click the Clipboard button and choose Paste from the pop-up
menu.
Users can toggle between the enable state of the other filters in the list by clicking the enable icon in the Filter
list while keeping the Alt key pressed. On clicking the disable icon while keeping the Alt key pressed, the
selected filter is enabled, and all other filters in the list are disabled.
3. Select the filter preset to apply from the list of available presets at the bottom of the preset menu.
On applying a filter preset to an object, Flash Pro replaces the currently applied filters with the filters used in
the preset.
Refer to Table 4.2 to view a description of the filters available in the Properties panel.
Filters Description
Drop Shadow Creates a shadow of the selected object. Users can not only apply color but also change
the direction and distance of the shadow.
Blur This filter softens the details and edges of an object. This filter can also be used to blur
the object when it is too close or too far from the camera.
Bevel This filter gives a raised effect to the selected object.
Glow This filter applies a glow to the edges of the selected object. This filter can be applied
to the moon in an evening scene.
Gradient glow This filter creates a gradient glow. More than one color can be used to create this effect.
Gradient bevel This filter allows you to use color gradients. The options available are similar to that of
the gradient glow filter.
Adjust color This filter is used to change the color, brightness, contrast, and saturation.
Table 4.2: Filters available in the Properties panel and their description
2. You can rename a filter preset using the Add Filter button.
True False
4.6 Understanding the Flash Library
A Library, as the name suggests, is the place where assets used in a movie is stored. An asset could be anything -
objects, symbols, instances, movie clips, and similar elements. Assets within a Library can be used across several Flash
files. It is also possible to view the Library items of multiple Flash files at the same time using a single Library panel.
To open a Library panel, from the Window menu, select Library. Alternatively, you can press the Ctrl+L keys. Refer
to Figure 4.11.
4.7 Creating Patterns with the Spray Brush and Deco Tool
In Flash, you can auto-create patterns based on the settings that you enter before you use them using the Spray Brush
tool and the Deco tool. These tools use symbols in place of fill and stroke colors. These tools make it very easy to create
patterns. You can do so by simply clicking on the stage and Flash distributes instances of the selected symbol across
the stage. It also arranges the symbols based on your specifications.
You can access the Spray Brush tool from the Tools panel. It shares space with the Brush tool. You can select a fill
color as the default color and also set other options in the Properties panel. Incase if you want to use a movie clip or
graphic symbol as a spray particle then, click the Edit button and click and drag on the stage where you want the pattern
to appear.
Refer to Table 4.3 to view a description of the options available in the Spray Brush tool.
For detailed step-by-step procedure, refer to demo Spray Brush Tool from:
eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Creating Patterns with the Spray
Brush and Deco Tool>> Spray Brush tool
Using the Vine effect, you can fill the stage, symbols, objects, or any closed area with a vine pattern. You can also use
your own artwork (symbols) for the leaves and flowers. Refer to Figure 4.14.
Using the Symmetry effect, you can arrange symbols symmetrically around a central point. These symbols can be
controlled with a set of handles. You can also create circular elements, such as a planet. The default symbol for the
Symmetry effect is a 25 x 25 pixel black rectangle with no stroke. Refer to Figure 4.16.
eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Creating Patterns with the Spray
Brush and Deco tool>> Using the Deco tool
4.8 3D Spaces
In Flash, you can add 3D perspective effects to a movie clip by moving and rotating it in 3D space on the stage. When
you move or rotate a movie clip by the z-axis, it becomes a 3D movie clip. In 3D terminology, moving an object in 3D
space is called translation and rotating an object in 3D space is called transformation. Once you have applied either of
these effects to a movie clip, Flash considers it to be a 3D movie clip and a colored axes indicator appears overlaid onto
the movie clip whenever it is selected. Global and local are the two different 3D spaces in Flash. Global 3D space is the
stage space; whereas, local 3D space refers to the movie clip space. However, the default mode is global.
Moving an object in Local 3D space refers to moving the object relative to its parent movie clip. You can toggle between
the two modes - global and local - using the 3D Translation tool. To do so, click the Global toggle button in the Options
section of the Tools panel keeping the 3D Translation tool selected. Alternatively, you can use the D key to toggle
between the two modes while dragging with the 3D Translation tool.
The 3D Translation and Rotation tools appear together in the Tools panel. To select the currently inactive 3D tool, you
can click and hold the active 3D tool icon in the Tools panel. By default, selected objects that have 3D translation applied
appear with a 3D axis overlay on the stage. You can turn off this overlay in the General section of Flash Preferences.
■■ Moving a single object in 3D space
To move a single object in 3D space, begin by selecting the 3D Translation tool from the Tools panel. Then, set the
mode to either Local or Global and then drag the arrow tips in the direction of the arrow (x and y-axis) or the black
arrow either upward or downward. (x- and y-axis) in the direction of the arrow or the black dot (z-axis) up or down.
You can also move the object by entering values of the x, y, and z-axis in the 3D Position and View section of the
Properties panel. Refer to Figure 4.21.
Global is the default mode for the 3D Rotation tool. Rotating an object in global 3D space is the same as moving it
relative to the stage. Rotating an object in local 3D space is the same as moving it relative to its parent movie clip if it
has one. To toggle the 3D Rotation tool between global and local modes, click the Global toggle button in the Options
section of the Tools panel while the 3D Rotation tool is selected. Alternatively, you can toggle between the two modes
by pressing the D key while dragging with the 3D Rotation tool.
By default, the selected objects that have the 3D rotation applied, appear with a 3D axis overlay on the stage. You can
turn off this overlay from the General section of Flash Preferences.
■■ Rotate an object in 3D space
To rotate an object in 3D space, begin by selecting the 3D Rotation tool from the Tools panel. Set the mode to local
or global and then drag one of the four axis controls to rotate around that axis. You can also rotate the object by
entering values of X, Y, and Z-axis in the 3D Position and View section of the Properties panel. Refer to Figure 4.22.
In order to set a Perspective Angle, begin by selecting a movie clip instance that has the 3D rotation or translation
applied to it. Then, in the Properties panel, enter a value in the Perspective Angle field. Alternatively, you can also
drag the hot text to alter the values.
Like the Perspective Angle, to view or set the Vanishing Point in the Properties panel, a 3D movie clip must be selected
on stage. Changes to the Vanishing Point are visible on the stage immediately. Refer to Figure 4.24.
4.10 Exercise
1. A graphic created in Photoshop and imported in Flash, is referred to as a symbol in Flash.
True
False
2. Clickable graphics in Websites that are linked to other places in the site of the Internet are referred to as _____.
Buttons
Movie clips
Timelines
Symbols
3. The process of varying the transparency or color interaction of two or more overlapping objects is referred to as
________.
Blending
Looping
Compositing
Instancing
4. Blended images interact with the underlying images that it overlaps __________.
5. On swapping symbols, the effects are preserved and are applied and referenced to the new chosen symbol.
True
False
6. Filters that can be saved with specific settings and can be used on a later date are known as ______.
Filter instances
Filter symbols
Filter presets
Filter replicas
Context
Application
Window
Tools
8. Using the __________ effect, it is possible to arrange the symbols symmetrically around a central point.
Grid
Symmetry
Vine
Lightning
9. Rotating an object in local 3D space is different from moving it relative to its parent movie clip, if any.
True
False
S e s s io n 5
Frame-by-Frame Animation and Shape Tweening
Learning Outcomes
In this session, you will learn to:
¾¾ Work with frames in the timeline
¾¾ Create frame-by-frame animation
¾¾ Use onion skinning
¾¾ Apply shape tweening
Timeline, as the name suggests, represents the timing of the animation. Hence, it is of utmost importance in animations.
On playing your animation, the contents of your frame are displayed from left to right, across the timeline.
The timeline comprises three little rectangles, each representing one frame in your animation. The number of frames in
an animation appears at the top of the timeline. Refer to Figure 5.1.
Using timelines you can modify and edit frames, assign special attributes, or change the type of frames. You can also
control the speed at which the animation plays, create keyframes, static frames, or blank frames.
Layers, frames, and the playhead are the major components of a timeline. Layers are listed on the left side of the
timeline. Frames in each layer appear as a row to the right of the layer name.
The timeline header indicates the frame numbers. The playhead – the red line on the timeline, indicates the current
frame that is displayed on the stage. The playhead moves from left to right through the timeline as a document plays
on the stage.
The selected frame number, current frame rate, and elapsed time to the current frame appear at the bottom of the
timeline. This is known as the timeline status.
The timeline displays the location, type, and motion paths in an animation.
Controls in the layers section of the timeline lets users hide, show, lock, or unlock layers, as well as display layer
contents as outlines. It is possible to drag timeline frames to a new location on the same layer or to a different layer.
Timelines can be resized to change the number of visible layers and frames. Using the scroll bar, users can view
additional layers of the Timeline.
The following actions can be performed to change the appearance of the Timeline:
¾¾ Moving a Timeline: To move a timeline when it is docked, drag the title bar at the upper-left corner of the
timeline.
¾¾ Docking a Timeline:
●● To dock a timeline to the application window, drag the title bar to the top or bottom of the document window.
●● To dock a timeline to other panels, keep the Control key pressed while dragging the timeline title bar to the
desired location. A blue bar appears indicating the position where the Timeline will dock.
¾¾ Altering the length of the name fields: To lengthen or shorten the layer name fields in the timeline panel, drag
the bar separating the layer names and the frames portion of the timeline.
■■ Change the display of frames in the timeline
The display of frames in the timeline can be modified to suit the users’ requirements. This can be done by selecting
the options available under the Frame View pop-up menu.
Users can change the width and height of the frame cells. They can also turn the tinting on or off by selecting Tinted
Frames. Refer to Figure 5.2.
Refer to Table 5.1 to view a description of the options available in the Frame View pop-up menu.
This option comes handy to view the way in which elements move
in their frames in an animation. However, previews are usually
smaller as compared to the Preview option.
Table 5.1: Frame View pop-up menu options and their description
■■ Change the layer height in the timeline
The height of the layer in a timeline can be modified in any of the following ways:
¾¾ Double-click the icon to the left of the layer name in the timeline.
¾¾ Right-click the layer name and select Properties from the shortcut menu.
¾¾ Select the layer in the timeline. From the Modify menu, point to Timeline, and then click Layer Properties. In
the Layer Properties dialog box that appears, select an option for the layer height and click OK.
2. Keeping the frame selected, enter a name for the label in the Label section of the Property Inspector and press
Enter. Refer to Figure 5.3.
In frame-by-frame animation, the commonly used frame rate is between 12 fps and 24 fps; increasing the frame rate
results in smoother animations. It is possible to change the frame rate after you have authored a file. It is also possible
to reset the timing of the animation, insert frames, or remove frames. It is also possible to change the duration of the
tweens of an animation. However, it makes sense to streamline a final frame rate before you start designing and testing
complex animation sequences.
You will now learn how to create a blank keyframe. To do so, right-click the frame and select Insert Blank Keyframe
from the contextual menu. Alternatively, from the Insert menu, select Timeline. Then, select Blank keyframe from the
Application menu. In addition to the listed methods, you can also press the F7 key.
■■ Inserting frame
The number of frames in a movie and the frame rate determines the length of a movie. Increasing the number of
frames increases the duration of the movie.
To insert frames, right-click the selected frame or frames in the timeline and select Insert Frame from the context
menu. Alternatively, you can select Timeline from the Insert menu. From the submenu that appears, select Frame.
To convert a keyframe to a frame, begin by selecting a keyframe. Then, from the Modify menu, select Timeline. From
the submenu that appears, select Clear Keyframe. Alternatively, you can right-click a keyframe in the Timeline and
select Clear Keyframe from the context menu.
To convert a frame into a blank keyframe, begin by selecting a frame or a keyframe. Then, from the Modify menu, select
Timeline. From the submenu that appears, select Convert to Blank Keyframes. Alternatively, you can right-click a
keyframe in the Timeline and click Clear Frames from the context menu. In addition, you can also select Timeline from
the Edit menu. From the submenu that appears, click Clear Frames.
It is possible to perform most tasks in either mode. However, you can switch between modes depending on the task to
be performed. To select the desired mode, from the Edit menu, select Preferences. In the dialog box that appears, from
the General category, select the Span Based Selection check box. This will enable the span-based selection mode.
Deselecting the check box disables the selection and activates the frame-based selection.
On placing the playhead on a frame, the content of that frame is displayed on the stage. On selecting a keyframe in the
timeline, all the content on that keyframe is selected. Similarly, on selecting content on the stage, the corresponding
keyframe is selected. In this manner, it is possible to edit the content in a keyframe or the position of the keyframe in
the timeline.
■■ Copy and paste keyframes
To copy and paste keyframes, begin by selecting the desired keyframe. Alternatively, you can drag to select a
range of keyframes. After selecting a range of keyframes, from the Edit menu, select Timeline. Then, select Copy
Frames. The selected frames are copied.
To paste frames, click the specific frame where you want to paste the frames. Then, from the Edit menu, select
Timeline. From the submenu, select Paste Frames.
Alternatively, you can keep the Alt key pressed and drag the keyframe to the location where you want to paste it.
■■ Move a keyframe or frame sequence and its contents
You can move a keyframe or frame sequence along with its contents by dragging the keyframe or the sequence to
its desired location.
■■ Change the length of a static frame sequence
You can change the length of a static frame sequence by keeping the Ctrl key pressed and dragging the beginning
or ending frame of the span either to the left or to the right.
To clear keyframes, begin by selecting the keyframe. You can also click and drag to select a range of keyframes. Then,
from the Modify menu, select Timeline. From the submenu that appears, select Clear keyframe. You will notice that
Flash converts the keyframe back into a regular frame. Refer to Figure 5.7.
Figure 5.7: Clear frames
To remove frames, begin by selecting the keyframe. You can also click and drag to select a range of keyframes. Then,
from the Edit menu, select Timeline. From the submenu that appears, select Remove Frames. You will observe that
the selected frame(s) are removed and the length of the animation movie is shortened. Refer to Figure 5.8.
2. The Document Settings dialog box can be accessed from the Modify menu.
True False
3. To convert a frame into a blank keyframe, right-click a keyframe in the Timeline and click Convert to Keyframes.
True False
Today, with the use of computers, a similar effect is achieved using the onion skinning technique. In this technique,
animators make the frames translucent and project them on top of each other to attain a continuous animation. Onion
skinning is a technique used for creating animated cartoons and editing movies to see several frames at once. On using
this technique, the animator or editor can make decisions on how to create or change an image based on the previous
image in the sequence. Refer to Figure 5.9.
To activate the onion skin, click the Onion Skin mode in the Status bar. The onion skin markers appear in the area
above the frame numbers and the selected range of frames appear dimmed. The frames before and after the active
frames appear in varying degrees of shading on the stage; they appear lighter as they move further away from the active
frame. Refer to Figure 5.10.
Figure 5.10: Onion skin mode
Onion skin markers come with handles that define the beginning and end of the onion skin. These handles appear
as brackets with small dots and can be dragged to adjust the number of frames. To adjust the frames using the
handles, begin by clicking the Onion Skin mode button on the Status bar. If necessary, click the small dot on either
end of the onion skin markers and then drag to include or exclude any consecutive frames in the onion skin.
■■ To set onion skin markers in Modify Onion Markers window
To set the onion skin markers in the Modify Onion Markers window, begin by clicking the Modify Onion Markers
button. The Modify Onion Markers popup window appears with various options. Refer to Table 5.3 to view a
description of the options in the Modify Onion Markers window.
Options Descriptions
Always Show Markers This option keeps the Onion Skin Markers visible in and out of Onion Skin
mode.
Anchor Onion This option maintains the selected frames even if you move the playhead.
Onion 2 This option displays two frames before and after the current frame.
Onion 5 This option shows five frames before and after the current frame.
Onion All This option includes the entire duration of the timeline in the markers.
Table 5.3: Modify Onion Markers options and their descriptions
The Edit Multiple Frames mode is useful when you want to make changes to an entire animation or to a series of
frames at once. On enabling this feature, you will see brackets similar to those in the Onion Skin mode. On dragging
these brackets you can select the range of frames that you want to edit.
This feature works best when you want to make changes to your animation at a macro level. For example, if you want to
resize an animation or change its position, you can do so by selecting an entire frame span or layer instead of moving
or resizing content on each frame separately.
To make changes to an entire animation, begin by clicking the Edit Multiple Frames button in the Status bar. Then,
click and drag the markers to include all the frames you want to select. You will notice that all the content in the selected
frames appear on stage.
Next, click the Selection tool on the Tools panel. Then, drag a selection box around the content on the stage. You can
make changes to the location, scale, effects, and other properties of the selected frame(s).
To do so, begin by creating an object on the first frame. This will be your first keyframe. Then, change the attributes of
the object in the other frames. On playing the frames consecutively, you will observe that the minute changes mimic the
movements. You will also observe that each keyframe describes an altered position or transform effect.
To see your Flash movie in its final state, you can export your Flash document into a Flash movie (.swf file). The final
Flash movie displays all the elements that are not viewable in the Flash Development environment. These elements
include animations contained in movieclip symbols and ActionScript functionality. In order to preview the basic animations
from their own timeline, you can use the controller to preview them. You can also test your animation in Flash player. To
do so, from the Control menu, select Test Movie. From the submenu that appears, select Test. Alternatively, you can
press the Ctrl+Enter keys.
The Test command tests the movie based on the current test option. Flash uses the document type, as the default type,
until you change it. Refer to Figure 5.14. In the Flash Professional test option, Flash exports the entire timeline and any
other scenes you have created into a SWF file that plays in the Flash player.
Figure 5.14: Preview of an animation in Flash player
Scrubbing is the technique of moving the playhead in the Timeline to view your animation.
For detailed step-by-step procedure, refer to demo Frame by Frame Animation from:
eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Previewing the Animation
An object whose shape has to be transformed should be editable. This can be done by selecting the object with the
Selection tool. Shape tweening is a good option when you want to transform the shape of an object gradually and it
works best with simple shapes. On applying shape tween, Flash draws the inbetweens, such that the object appears to
morph between the two states. Following are some points to be noted while applying shape tween:
¾¾ It is best to avoid shapes with negative spaces or contours in them. Keep the shapes simple.
¾¾ Experiment with shapes you want to use to determine the results.
¾¾ Use shape hints that help in determining which points on the beginning shape should correspond to the specific
points on the end shape.
You can either import vector shapes from another source or create a shape using any of the Drawing tools. You can also
apply a shape tween to a grouped artwork or a symbol. To do so, break apart the group or enter in the Symbol Editing
mode and apply the shape tween to any editable shape in the symbol’s timeline.
■■ Adding and removing keyframes from a Shape tween
Keyframes can be added or removed from a shape tween in the similar manner as that of a motion tween. However,
there is one crucial difference in the process. Unlike a motion tweened framespan, where you can add keyframes
by dragging an object, in shape tweening, it is not possible to add keyframes by selecting and dragging it. To add
additional locations or change shapes, you must first add a keyframe and then edit the shape. This can be done
by selecting the Keyframe command from the Timeline submenu of the Insert menu. On adding a keyframe, the
shape at that point in the keyframe can be edited.
5.7.2 Adjusting Shape Tween Properties
Shape tween properties can be modified using options available in the Properties panel. You can modify the easing
options, and blending preferences. You can also smoothen the tweened shapes using the Distributive option and
preserve corners and straight lines using the Angular option.
While using shape hints, you can begin by specifying the beginning shape hint followed by the corresponding end shape
hint. In this manner, Flash determines which part of the shape in the first keyframe will transform into which part in the
end keyframe. Shape hints contain letters from a to z that correspond to the starting and ending shapes. You can use
up to 26 shape hints. Shape hints are yellow in a starting keyframe, green in an ending keyframe, and red when not on
a curve.
Enabling shape hints need not derive accurate results. However, this feature gives you great control over the
tweening process of complex shapes.
The following guidelines will help derive best results while tweening shapes:
¾¾ For complex shapes, it is best to create intermediate shapes and tween them instead of just defining a starting
and ending shape.
¾¾ Make sure that shape hints are logical. For example, if you are using three shape hints for a triangle, they must
be in the same order on the original triangle and on the triangle to be tweened. The order cannot be abc in the
first keyframe and acb in the second.
¾¾ Shape hints work best if you place them in counterclockwise order beginning at the top-left corner of the shape.
Perform the following steps to create shapes using shape hints:
¾¾ Begin by selecting a shape on the starting keyframe. Then, from the Modify menu, choose Shape. From the
application menu that appears, click Add Shape Hint.
¾¾ Using the Selection tool, specify a point on your starting shape and move the first hint (a). Position it on an area
of the shape that you want to match up with an area on the final shape.
¾¾ Then, position this hint to define the area of the final shape that should match up with the area specified on the
starting shape.
¾¾ Preview the new in-between shapes by dragging the playhead on the timeline. Continue to add or reposition
hints until Flash renders the in-between shapes correctly.
¾¾ To remove an individual hint, drag it off the stage with the Selection tool.
For detailed step-by-step procedure, refer to demo shape tween from:
eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Shape Tweening>> Using
Shape Hints
5.8 Summary
In this session, Frame-by-Frame Animation and Shape Tweening, you learned that:
¾¾ Timeline represents the timing of the animation and forms a vital part of any animation.
¾¾ Layers, frames, and the playhead are the major components of the timeline.
¾¾ A timeline can be moved or docked. The length of the timeline can also be altered.
¾¾ Labeling frames help in organizing content. Labels can be applied only to keyframes.
¾¾ The project frame rate affects the playback of all animations. The frame rate of any animation appears in the
Document Settings dialog box.
¾¾ Frame-by-frame animation is the most basic form of animation that originated in the 2D form of sketching. With
the advent of technology, it was later implemented in digital animation. This kind of artwork is best suited for
complex animations that require subtle changes.
¾¾ In onion skinning, animators make the frames translucent and project them on top of each other to attain a
continuous animation. This technique is used for creating animated cartoons and editing movies to see several
movies at a glance.
¾¾ To see your Flash movie in its final state, you can export your Flash document into a Flash movie (.swf file). The
final Flash movie displays all the elements that are not viewable in the Flash Development environment. These
elements include animations contained in movieclip symbols and ActionScript functionality. The Test command
tests the movie based on the current test option.
¾¾ Shape tweening is used to transform the shape of an object into another object. While applying shape tween,
it is best to avoid shapes with negative spaces or contours in them. Use shape hints that help in determining
which points on the beginning shape should correspond to the specific points on the end shape.
5.9 Exercise
1. Timeline represents the _________ of an animation.
Spacing
Position
Timing
Content
4. Identify the statement that does NOT hold true for onion skinning.
It is possible to adjust the number or frames using the onion skin markers.
The Onion 2 option displays two frames before and after the current frame.
Shape hints
Shape tween
Motion tween
Scrubbing
S e s s io n 6
Motion Tweening and Classic Tweening
Learning Outcomes
In this session, you will learn to:
¾¾ Explain motion tween and its associated terms
¾¾ Create motion tweens
¾¾ Work in the Motion Editor panel
¾¾ Apply color effects and filters
¾¾ Work with property keyframes, edit the path of a motion tween, and work with motion presets
¾¾ Apply easing to animations
¾¾ Explain classic tween
6.1 Introduction
The frame-by-frame animation technique makes use of a lot of frames even in the most simplest of animation. This
technique, when used in combination with tweening, helps create animations with ease. Tweening defines the start and
end points of an animation, while Flash creates the inbetweens.
Refer to Table 6.1 to view differences between classic tween and motion tween.
Click here to know more about the differences between motion tweens and classic tweens.
You will now understand the concept better with the help of this example. Consider placing a movie clip on the left side
of the stage in frame 1 of the timeline. Then, move that movie clip to the right side of the stage till frame 24. On creating
a tween, Flash calculates all the positions of the movie clip on the stage in between the specified positions. You end
up with an animation of the movie clip moving from the left side of the stage to the right side, from frame 1 to frame
24. Motion tweening is used to create smooth motion and transformation effects, such as scale, position, rotation, and
skew. These effects can also be applied to movie clips, graphics, buttons, and text fields. In addition to applying motion
effects, you can also use the advanced color effects in Flash to apply changes to color, alpha, and brightness. In this
type of animation, the file size of the animation is smaller as compared to other types of animations. Refer to Figure 6.1
for an example of motion tweening.
Figure 6.1: Motion tweening
Applying tweening effects to the instances in any animation, does not affect the original symbol placed in the
Library.
■■ Tween span
A group of frames in a timeline in which an object on stage can have more than one property changed over time is
referred to as a tween span. It appears as a group of frames, on a single layer, over a blue background. They can
be selected as a single object and can be dragged from one location to another on the timeline. You can also move
tween spans to another layer. A single object on a stage can be animated in each tween span. This object is referred
to as the target object of the tween span. Refer to Figure 6.2.
A frame within a tween span where you specify more than one property value for the tween target object is referred
to as a property keyframe. Each property you define has its own property keyframe. On defining more than one
property in a single frame, the property keyframes for each of those properties reside in that frame. The properties
of the tween span and its keyframe can be viewed in the Motion Editor panel. You can also define the types of
property keyframes to display in the timeline from the tween span context menu. Going back to the earlier example
of tweening a movie clip from frame 1 to frame 24, you will observe that frames 1 and 24 are property keyframes.
On selecting a tweened space, a tweened object, or a motion path, the Motion Editor panel displays tween property
values in categories and a grid with a graph for each property. Each keyframe for a specific property appears as a
control point on the graph. Control points are of two types – smooth points and corner points.
When the control points are smooth, Bezier handles appear that can be adjusted. Some properties in the Motion
Editor are associated with each other, such as Scale X and Scale Y. You can use the Link icon to constrain values
to match each other.
You can also add a property keyframe to a property curve. To do so, begin by placing the playhead in the desired
frame. Then, click the Add Keyframe button or the Remove Keyframe button for the property in the Motion
Editor panel. Alternatively, you can keep the Ctrl key pressed on the keyboard while you click in the position where
you want to add the property keyframe. In addition, you can also right-click the property curve and choose Add
Keyframe. Refer to Figure 6.3.
You can remove a property keyframe from a property curve at any time. To do so, click the control point for the property
keyframe while keeping the Ctrl key pressed on your keyboard. Alternatively, you can right-click the control point and
select Remove Keyframe.
You can also toggle a control point between the corner point mode and smooth point mode. To do so, click the control
point while keeping the Alt key pressed on the keyboard.
When a control point is in the smooth point mode, its Bezier handles are exposed and the property curve passes through
the point as a smooth curve.
When a control point is a corner point, the property curve forms an angle when it passes through the control point. Bezier
handles are not exposed for corner points. Refer to Figure 6.4.
To set the point to smooth point mode, you can right-click the control point and choose Smooth Point, Smooth Right,
or Smooth Left.
To set the point to corner point mode, choose Corner Point. To move a property keyframe to a different frame, drag its
control point. You cannot drag a property keyframe past the keyframes that follow or precede it. To toggle a property
keyframe for the spatial properties X, Y, and Z between roving and non-roving, right-click the property keyframe in the
Motion Editor panel.
You can also turn off roving for an individual property keyframe in the Motion Editor panel by dragging the roving
keyframe to a vertical frame divider.
To link associated pairs of X and Y properties, click the Link X and Link Y property values button for either one of the
properties you want to link. You will observe that when the properties are linked, their values are constrained such that
the ratio between them is preserved when you enter a value for either of the linked properties. Examples of associated X
and Y properties include the Scale X and Scale Y properties and the Blur X and Blur Y properties of the Drop Shadow
filter.
You can alter the property keyframes on the stage either by modifying values in the Properties panel or through the
Motion Editor panel. On modifying values, ensure there is only one object available when applying the tween, else the
results will be unpredictable. Tweened frames must reside on the same layer in the Timeline. After adding a tween to a
layer, Flash changes it to a tween layer, which you can no longer draw on. A tween layer can contain tween spans, static
frames, and actions.
Click here to view videos and articles that demonstrate the use of the Motion Editor.
■■ Creating a motion tween
To create a motion tween, begin by selecting a symbol instance or a text field to tween on the stage. Then, from the
Insert menu choose Motion Tween. Alternatively, you can right-click the selection on the stage and choose Create
Motion tween from the context menu. Next, define the length of the animation by dragging either ends of the tween
span. Incase if you want to specify another position for the object, then place the playhead in another frame within
the tween span and drag the object on the stage to another position. You will now add motion to the tween. To do
so, click a frame within the tween span and move the object on the stage. You can tween the 3D rotation or position
by using the 3D Rotation or 3D Translation tool.
■■ Adjusting motion tween properties
Changes can be made to motion tweens in the Properties panel or in the Motion Editor. When a tweened span is
selected, a number of options are enabled that you use to add complexity to your motion path. You can set motion
tween properties to deal with position and size, set rotation direction and frequency, apply color and display blending
effects, or control the easing in or out of the motion. Refer to Figure 6.5.
Options Descriptions
Ease This option is used to set the speed in and out.
Rotation This option sets the direction and frequency of the rotation
of the object. You can keep your object parallel to the
guide relative to its center point by selecting the Orient
To Path check box.
Path Sets the X and Y position, and the selection width and
height.
Table 6.2: Options available in the Properties panel on selecting a tween span
Refer to Table 6.3 to view the options available in the Properties panel on selecting a tween object.
Options Descriptions
Position and Size Sets the X and Y position, and the selection width and
height.
3D Position and View Sets the 3D X, Y, and Z positions, 3D perspective selection
width and height, perspective angle, and vanishing points.
Color Effect Sets the color style effect: Brightness, Tint, Alpha, or
Advanced.
Display Sets the display blending effect, which includes Darken,
Overlay, and Invert.
Table 6.3: Options available in the Properties panel on selecting a tween object
To change the display of the Motion Editor, begin by selecting an object on the stage. Then, from the Window
menu choose Motion Editor. Refer to Figure 6.7.
You can change the display of the motion editor by changing any of the following options:
¾¾ Display Properties: You can change the properties by clicking the triangle beside the property category.
¾¾ Expand/Collapse Property view: Using this option you can toggle between the property names.
¾¾ Viewable Frames: Using this option you can set the number of frame of a tween shown in the Motion Editor.
¾¾ Graph Size: Using this option, you can define the size of the graph.
¾¾ Expanded Graph Size: Using this option, you can set the expanded property view size of the graph.
¾¾ Add Eases Options: Adds an ease option to menus in the Motion Editor. Click the Add button on the Eases
category, and then select an ease option.
■■ Setting the motion tween properties in the Motion Editor
¾¾ The following options are available to set the motion tween:
●● Basic Motion: This section groups the X, Y, and Z (rotation) values for the target object. A target object is
always accompanied by the X, Y, and Z values. Since these properties are related, their property keyframes
have to match up.
●● Transformation: This section groups the Skew and Scale properties for the X and Y axis of the target
object. Any differences in size or skew between the target object in the initial keyframe and the last property
keyframe of a tween span can be interpolated at different rates.
●● Color Effect: Color changes can be controlled from one property keyframe to another in a tween by editing
the tween curve. Color effects can be added to a target symbol either by using the submenu in the Motion
Editor or by using the settings in the Properties panel.
●● Filters: On applying filters to create changes in an item’s appearance in the span of a tween, the pattern
of change can be adjusted with custom easing. Filters can be added to a target symbol from the submenu
either using the Motion Editor panel or using the Properties panel.
More than one effect or filter can be applied to an object to create a different effect. You also have the option of changing
or removing the applied color effect if it does not meet your requirement.
■■ Adding color effects and filters to a motion tween
To add color effects and filters to a motion tween, begin by selecting an object on the stage with a tween applied.
Then, in the Motion Editor panel, click the triangle to expand the Color Effect or Filters category.
¾¾ To apply color effects, click the Add button on the Color Effect category. Then, from the list of options, you can
choose from Alpha, Brightness, Tint, and Advanced Color. Refer to Figure 6.8.
¾¾ Editing the shape of a motion path with the Selection and Subselection tools. Refer to Figures 6.10 and 6.11.
Click here to know more about editing the path of a motion tween.
You can apply easing either in the Property Inspector window or in the Motion Editor. On applying easing in the
Property panel, it affects all the properties that are included in a tween. However, on applying easing in the Motion
Editor, it can affect a single property, a group of properties, or all properties of a tween. Refer to Figure 6.15.
Using the Motion Presets panel, you can not only create and save your own custom motion presets but also import and
export them and later share them with other tweens. These presets that are imported or exported are stored as XML
files.
■■ Applying a motion tween
To apply a motion tween preset, begin by selecting a tweenable object on the stage. Then from the Window menu,
select Motion Presets to open the Motion Presets panel. On selecting a preset from the panel, a preview of the
same appears on the top of the panel in the Preview pane. You can apply the preset by clicking Apply. On the other
hand, incase if you do not want to apply the preset and close the preview pane, you can simply click outside the
Motion Presets panel. Refer to Figure 6.16.
Incase if you are applying a preset to a non-tweenable object, a dialog box appears confirming if you want to convert it
to a symbol. On doing so, the motion is set to start at the current position of the object on the stage. To apply the preset
so that the motion ends at the current position of the object on stage, click Apply, while you keep the Shift key pressed.
■■ Saving a tween as a custom motion preset
Select the tween span, or object, or motion path on the stage along with the custom tween that you want to save as
a preset. In the Motion Presets panel, click the Save Selection As Preset (icon) button. You will be prompted to
enter a name for the preset. Enter a name for the preset in the space provided and click OK. The new preset appears
in the Motion Presets panel under Custom Presets and will be saved as an XML file in the Motion Presets folder.
■■ Importing a motion preset
Motion presets are stored as XML files that can be imported and stored in the Motion Presets panel. To do so, from
the Motion Presets panel menu, click Import. In the Open dialog box that appears, navigate to the XML file that
has to be imported and click Open. Flash CS6 opens the XML file and adds it to the Motion Presets panel.
■■ Exporting a motion preset
Select the preset to be exported from the Motion Presets panel. Then, click Export. In the Save As dialog box that
appears, enter a name for the XML file and choose a location. Then, click Save.
■■ Deleting a motion preset
It is possible to remove presets from the Motion Presets panel. On removing a preset, Flash CS6 deletes its XML
file from the disk. It is possible to delete a preset either by clicking Remove from the Motion Presets panel menu
or by clicking the Remove Item button from the panel.
eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Motion Tween Presets>>
Deleting a motion preset
2. Each property that a user defines has its own property keyframe.
True False
3. Roving controls the shape of the tween curves of most of the individual properties.
True False
However, classic tween provides better control in some aspects as compared to Motion tween. This makes it the
preferred choice among animators.
It is advisable to create keyframes only at points where changes are expected to occur. This is because Flash documents
save the shapes in each keyframe.
Keyframes are indicated in the Timeline. A solid circle represents a keyframe with content on it; whereas, an empty circle
before the frame represents an empty keyframe. Succeeding frames added to the same layer have the same content
as the keyframe.
In a classic tween, it is possible to view tweened frames but they cannot be edited directly.
It is possible to edit tweened frames, either by changing one of the defining keyframes or by inserting a new keyframe
between the beginning and ending keyframes. Dragging items from the Library panel onto the stage adds the items to
the current keyframe.
Onion skinning is another technique that can be used to display and edit more than one frame at a time.
■■ Creating a classic tween animation
To create a classic tween animation, begin by defining keyframes and objects on the beginning and ending keyframes.
eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Understanding Classic
Tween>> Creating a classic tween animation
6.3.2 Creating a Motion Guide Layer
A motion guide layer controls the movement of objects in an animation. It is not possible to drag a motion tween layer or
inverse kinematics pose layer onto a guide layer. To create a motion guide layer, drag a normal layer onto a guide layer.
This converts the guide layer and links the normal layer to the new motion guide layer.
It is best to place all guide layers at the bottom of the layer order inorder to avoid an accidental conversion of a guide
layer.
6.3.3 Creating Classic Tween Animation Along a Path
It is possible to draw paths using motion guide layers along which tweened instances, groups, or text blocks can be
animated. It is also possible to link multiple layers to a motion guide layer to have multiple objects follow the same path.
A normal layer that is linked to a motion guide layer becomes a guided layer.
The rate of change of the object is represented by the slope of the curve. When there is no curve (the curve is horizontal),
the velocity is zero; when the curve is vertical, an instantaneous rate of change occurs.
6.4 Summary
In this session, Motion tweening and Classic Tweening, you learned that:
¾¾ Classic tweening and motion tweening are the two types of animations in Flash. Classic tween makes use of
more than one instance of an object; whereas, motion tween makes use of only one instance of an object to
create tweens.
¾¾ Motion tweening is created by defining a value for an object property in one frame and specifying another value
for the same object in another frame.
¾¾ Tween span is a group of frames in a Timeline in which an object on stage can have more than one property
changed over time.
¾¾ A frame within a tween span where you specify more than one property value for the tween target object is
referred to as a property keyframe.
¾¾ Motion tween animation uses a single instance over the entire span along with property keyframes that you
define with property values to modify the tween.
¾¾ The Motion Editor panel displays the tween properties and their property keyframes. It is possible to edit the
properties using this panel.
¾¾ Timeline effects add life to any animation. Effects can be added by using filters in the Motion Editor panel.
¾¾ Easing is a technique that helps create realistic animations by manipulating the speed of the animation, either
at the beginning or at the end. This technique modifies the way Flash calculates property values in between
property keyframes in a tween.
¾¾ Readymade motion tweens that can be applied to an object on stage are referred to as motion presets. Each
preset is associated with a specific number of frames and only one preset per object can be applied on the
stage.
¾¾ Classic tween is the age-old way of creating animations in Flash. This type of animation is more complicated
and less flexible as compared to motion tween.
¾¾ Motion guide layers are used to control the movements of objects in a classic tween animation.
6.5 Exercise
1. A group of frames on a single layer with more than one property changed over time is referred to as ___________.
Property keyframe
Tween span
Classic tween
Timeline
Motion Editor
Bezier controls
Transformation effect
True
False
4. Each motion preset is associated with a specific number of frames that can be adjusted later using the ___________
panel.
Motion presets
Motion Editor
Motion tween
Custom presets
5. D
ragging a normal layer onto a guide layer converts the normal layer and links the guide layer to a new motion guide
layer.
True
False
Session 7
Working with Audio and Video
Learning Outcomes
In this session, you will learn to:
¾¾ Import videos using the Import Video Wizard
¾¾ Describe the various components used to import videos
¾¾ Work with sound
Ways Description
Progressive download from a This is the most commonly used method for using videos in Flash. In this method,
Web server video files are external to Flash and the size of SWF file is comparatively small.
Stream video using Adobe Adobe Flash Media Server not only secures the video content but also gives a
Flash Media server smooth streaming playback experience. Video files are external to the main file.
Embed video directly inside a This method is commonly used for short video clips as the sizes of the Flash files
Flash file are very large.
Table 7.1: Ways to use videos in Flash
Click here to know more about the ways videos are used in Flash.
Refer to Table 7.2 that shows the ways to import videos using the Import Video dialog box.
Options Description
Load external video with This option imports video and creates an instance of the FLVPlayback component.
Playback component This component is used to control the video playback. When the resultant SWF file
is ready to be uploaded on the Web server or the Flash Media Server, the video file
also has to be uploaded to the specific server and the FLVPlayback component
should be configured with the location of the video file.
Embed FLV or F4V in SWF and This option embeds the FLV or F4V in the Timeline where the individual video frames
play in Timeline can be viewed. Thus, the embedded file becomes a part of the Flash document.
Import as mobile device video In this option, a video is bundled into a Flash lite document. This video is then
bundled in SWF deployed to a mobile device.
Table 7.2: Ways to import videos using the Import Video dialog box
To import videos, first select a video clip that has to be imported, followed by choosing a skin for its display. This video
clip can be selected either from the location in the computer or from the list of videos that are already uploaded to the
Web server or Flash Media Server. Then, select the Load external video with playback component to import video
that is located on the computer. Otherwise, select either the Already deployed to a Web server option, or the Flash
Video Streaming Service option, or the Stream from Flash Media Server option, and then enter the URL of the video
clip in the space provided.
During the import process, the user will be prompted to choose a skin for the video clip. At this stage, either the None
option can be chosen, which indicates that no skin is to be applied, or any of the predefined FLVPlayback component
skin can be chosen. Additionally, a custom skin can also be created, and its URL can be entered on the Web server.
Refer to Figure 7.2.
Figure 7.3: Steps to import videos using the Import Video Wizard
Irrespective of how a video is imported on Stage, Flash stores a copy of it in the active document Library. However, it is
advisable to import video files first into the Library so as to have better control on its import and its placing on the Stage.
Once imported into the Library, it can be dragged and dropped on the Stage with ease.
It is also advisable to convert the video into a movie clip and then drag it on the Stage. This gives better control
of both the Timelines — namely, the Timeline on Stage and the Timeline of the movie clip.
eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Working with Videos>> Import
Video Wizard
Flash Player 7 supports the Sorenson™ Spark™ video codec encoded FLV files. Whereas, Flash Player 8 supports FLV
files encoded with Sorenson Spark or On2 VP6 encoder in Flash Professional 8. The On2 VP6 video codec supports
an alpha channel.
Flash Player 9 and its later versions support files derived from the standard MPEG-4 container format. These include
F4V, MP4, M4A, MOV, MP4V, 3GP, and 3G2, if they contain H.264 video or HE-AAC v2 encoded audio, or both. The
H.264 streams better quality video at lower bit rates when compared to the same encoding profile in Sorenson or On2.
HE-AAC v2 is an extension of AAC, a standard audio format defined in the MPEG-4 video standard. It uses Spectral
Band Replication (SBR) and Parametric Stereo (PS) techniques to increase coding efficiency at lower bit rates.
Options Description
Align It specifies the FLV file alignment in the player.
Autoplay It is selected or deselected for automatically playing the FLV file.
Cue points It specifies a string with cue points for the video.
isLive It is selected or deselected if the FLV file is streaming live.
Preview It creates a preview for authoring purposes.
ScaleMode It scales the video using options such as, maintainAspectRatio, noScale, or exactFit.
Skin It selects a skin for the FLV video player.
SkinAutoHide It is selected or deselected for automatically hiding or showing the video skin.
SkinBackgroundAlpha It specifies a background alpha channel for the skin.
SkinBackgroundColor It specifies a background color for the skin.
Source It specifies the path to the video source file.
Volume It specifies a volume setting for the video.
Table 7.3: Options in the Properties panel with description
Placing the video inside a movie clip gives more control over the content. This is because the video’s Timeline
plays independently from the main Timeline. The main Timeline need not be extended by frames to accommodate
the video, which otherwise makes working with the FLA file difficult.
In order to create a customized video player that dynamically loads FLV or F4V files from an external source, place the
video inside a movie clip symbol. When an FLV or F4V file is loaded, adjust the movie clip’s dimensions to match with
the actual video file’s dimension, and scale the video by scaling the movie clip.
To import an FLV or F4V file into the Library, anyone of the following can be opted:
¾¾ Select File, then click Import, and then select Import To Library.
¾¾ Select any existing video clip from the Library Panel, and select Properties from the Library Panel menu.
Click Import option. Locate the file to import, and click Open.
The following actions can be performed using the Video Properties dialog box:
¾¾ View information about an imported video clip
¾¾ Change the video clip’s name
¾¾ Update video clip if it is modified with an external editor
¾¾ Import an FLV or F4V file to replace the selected clip
¾¾ Export a video clip as an FLV or F4V file
First, select the video on the Stage. Then, from the Properties panel, click to expand the Cue Point section. Under
this section, the following actions can be performed:
¾¾ Adding of an ActionScript cue point by clicking the Add (+) button.
¾¾ Deleting an existing ActionScript cue point by clicking the Delete (-) button.
¾¾ Specifying the time by increasing or decreasing the timecode, either by dragging the mouse cursor or by
entering a value in the space provided.
¾¾ Importing and exporting an ActionScript cue point list in the XML format using the Import ActionScript Cue
Point button and Export ActionScript Cue Point button. While importing cue points, a dialog box displays the
number of ActionScript cue points imported and while exporting, it exports all the Navigation and Event cue
points that are embedded in the video along with all the ActionScript cue points that have been added.
In addition to this, parameters of a cue point can be added and renamed from the Parameters section of the
Properties panel. To add a parameter, select the ActionScript cue point and click the Add (+) button at the bottom
of the Parameters section. To rename a parameter, click in the Name field and enter a new name for the parameter.
Refer to Figure 7.5.
Figure 7.5: Properties panel
A movie can be exported as a FLV file from Flash or a video editing program using the FLV Export plug-in and then the
FLVPlayback component in Flash can be used to play it back. In order to include closed captioning, which is the World
Wide Web Consortium (W3C) standard XML format Timed Text, the FLVPlayback Captioning component can be used.
Refer to Figure 7.6.
1. From the Window menu, click Components to open the Components panel. Under the Video section, drag the
FLVPlayback component on the Stage and then select the component. Refer to Figure 7.7.
Figure 7.7: FLVPlayback components dragged on Stage from the Components panel
2. Next, open the FLV video file that has to be used. To do so, from the Properties panel, click the Edit Source button.
The Content Path dialog box appears. Click the Browse Folder icon. Then, navigate to select the FLV video file
and click Open. Refer to Figure 7.8.
Figure 7.8: Content Path dialog box and the Edit Source button
3. The Match source dimensions check box will be activated once the FLV video file is selected. Select the check
box to use the same video size as the file. Click OK. Any further changes to the properties of the video file, can be
made using the Properties panel. Once done, the movie can be tested by pressing the Ctrl+Enter keys.
For detailed step-by-step procedure, refer to demo FLVPlayback Component from:
eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Working with Videos>>
FLVPlayback Component
2. Another alternative to importing external FLV files in Flash Player is to dynamically play them using the
____________.
FLVPlayback Component Import Video Wizard FLVPlayback Captioning Parameters
A well-designed sound can add a whole new depth to an animation. However, as sound files are big and take more time
to download, options need to be selected depending upon the final mode of delivery. If the animation has to be played on
a Website, Flash offers different options for managing the download time. However, while adjusting the Sound option,
a generalized assumption of the audience and their devices need to be taken into consideration.
Sounds can be compressed effectively as graphics and animation files. Macromedia recommends an optimal setting
of 22 KHz with mono sounds in Flash. If mono is used, the file is cut to half the size as only a single sound channel is
used instead of two.
If QuickTime® 4 or later versions are installed on the system, following additional sound file formats have to be installed:
¾¾ AIFF (Windows or Macintosh)
¾¾ Sound Designer® II (Macintosh only)
¾¾ Sound Only QuickTime Movies (Windows or Macintosh)
¾¾ Sun AU (Windows or Macintosh)
¾¾ System 7 Sounds (Macintosh only)
¾¾ WAV (Windows or Macintosh)
7.2.2 Importing Sound Clips into the Library and Setting Properties
To import sounds in Flash, from the File menu, select Import. From the sub-menu that appears, select the Import
to Stage command or Import to Library command. When sounds are imported, they are placed in the Library. Each
sound can be heard immediately by selecting sound in the Library and pressing the Play button in the preview window.
Moreover, multiple instances of sound clip can be dragged on the Stage without affecting the file size. Refer to Figure
7.9.
Figure 7.9: Library panel displaying the sound in the Preview mode
■■ Sound properties
After importing a sound, the sound statistics can be checked and also the compression settings can be set.
Compression is always a choice between sound quality and file size. High quality sound can increase the file size to
a great extent. Hence, every effort should be made to compress the sound. Refer to Figure 7.10.
Figure 7.10: Properties panel displaying the sound properties
3. After the new sound layer is selected, drag the sound from the Library panel onto the Stage. This adds the current
layer.
4. In the Timeline, select the first frame that contains the sound file.
5. Select Window and in that click Properties, and click the arrow in the lower-right corner to expand the Property
inspector.
6. In the Property inspector, select the sound file from the Sound pop-up menu.
7. Select an effect option from the Effects pop-up menu. Refer to Figure 7.12.
Effects Description
None It applies no effects to the sound file. Select this option to remove previously
applied effects.
Left Channel/Right Channel It plays sound in the left or right channel only.
Fade Left To Right/Fade Right To Left It shifts the sound from one channel to the other.
Fade In It gradually increases the volume of a sound over its duration.
Fade Out It gradually decreases the volume of a sound over its duration.
Custom It creates custom in and out points of sound using the Edit Envelope.
Table 7.4: Effects available in the Effect drop-down menu
8. Select any one of the synchronization options from the Sync pop-up menu.
9. Enter a value for Repeat, which will specify the number of times the sound should loop, or select Loop to repeat
the sound continuously.
10. To test the sound, drag the playhead over the frames containing the sound or use commands in the Controller or
the Control menu.
Click here to know more about the synchronization options available in the Sync pop-up menu.
7.2.4 Remove a Sound from the Timeline
In the Timeline layer containing the sound, select a frame that contains the sound. In the Property inspector, move to
the Sound section and select None from the Name menu. This makes Flash delete the sound from the Timeline layer.
Any animation can be made lively with a sound clip. Like graphics, sound file instances can be inserted into frames on
the Timeline and used throughout the movie. Sounds are represented by waveforms in Flash frames. Flash organizes
movie by allowing to place sounds in another layer. This makes it easier to find sound files quickly and edit them as
needed. Flash also allows multiple sound layers in a movie.
When a sound clip is dragged from the library on the Stage, there is no visual representation of the sound.
Instead, a waveform image of vertical lines representing the digital sampling of the sound appears in the
Timeline.
2. To synchronize this sound with that of event in the scene, a beginning keyframe should be created for the sound.
This sound should match to the keyframe of the event in the scene to which sound has to be triggered. Then, select
any of the synchronization options.
3. Create a keyframe in the sound layer’s Timeline at the frame where the sound has to be ended. A representation of
the sound file appears in the Timeline.
4. Select Window and in that click Properties, and click the arrow in the lower-right corner to expand the Property
inspector.
5. In the Property inspector, select the same sound from the Sound pop-up menu.
6. From the Property inspector, select Stop from the Sync pop-up menu. When the SWF file is played, the sound
stops playing when it reaches the ending keyframe.
2. Click the Edit button on the right side of the Property inspector, the Edit Envelope dialog box appears. Refer to
Figure 7.13.
Figure 7.13: Edit Envelope dialog box
To find and replace sound clips, from the Edit menu, select Find and Replace. Alternatively, press the Ctrl+F keys. In
the dialog box that appears, select Sound from the For drop-down list. Then, select the desired files to find and replace
in the Name drop-down list. Refer to Figure 7.14.
Figure 7.14: Find and Replace tab
For detailed step-by-step procedure, refer to demo Working with Sound from:
eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Working with Sound>> Finding
and Replacing a Sound
7.3 Summary
In this session, Working with Audio and Video, you learned that:
¾¾ Flash supports most of the video file formats, including QuickTime, Windows Media, and MPEG clips.
¾¾ The Import Video Wizard helps through the process of importing video files into Flash. Videos can be imported
in the following three ways:
7.4 Exercise
1. The Import Video Wizard comes with different skins and for applying it, the ___________ component is used.
Streaming
Playback
Skinning
Properties
2. If mono sound is used, the file is cut to half the size as only a single sound channel is used instead of two.
True
False
3. Bit rate is always a choice between sound quality and file size.
True
False
4. ___________ type of sound must be downloaded completely before it begins to play, and it continues to play until
stopped.
Event
Stream
Start
End
5. _____________ option measures the video using options, such as, maintainAspectRatio, noScale, or exactFit.
Scale
Volume
Preview
ScaleMode
Session 8
Exporting and Publishing
Learning Outcomes
In this session, you will learn to:
¾¾ Export images, audio, and videos
¾¾ Work with the Publish command
¾¾ Explain the formats in which animated files can be published
After creating animations in the Flash interface, images, image sequences, and movie clips of the final file can be exported
or published in more than one format. Publishing a Flash movie is the last step towards completing an animation. On a
macro level, exporting in Flash is broadly classified into the following two categories:
¾¾ Export Image: To access this option, from the File menu, choose Export. From the sub-menu that appears,
click Export Image.
¾¾ Export Movie: To access this option, from the File menu, choose Export. From the sub-menu that appears,
click Export Movie.
A new compression algorithm, Lempel–Ziv–Markov chain algorithm (LZMA), is also available for SWFs that target Flash
Player 11 or its later versions. This new compression can be upto 40 percent more efficient, particularly for files that
contain a lot of ActionScript or vector graphics. Following are the steps to access it:
2. In the Advanced section of the dialog box, select the Compress movie option and choose LZMA from the menu.
A sprite sheet is a bitmap image file that contains several smaller graphics arranged in a tiled grid format. When a single
file has to be loaded, these small graphics can be complied into a single file by Flash Professional and other applications.
Thus, by using sprite sheets, the Graphics Processing Unit (GPU) does not have to load all graphic components on the
primary memory but only load a single file. This enhances the performance of the GPU.
A series of image files can be exported from an individual movie clip, button, or graphic symbol in the Library or on the
Stage. During export, Flash Pro creates a separate image file for each frame in the symbol. If exported from the Stage,
any transforms, such as scaling or skewing that has been applied to the symbol instance, are preserved in the output
image.
1. Select one or more symbols in the Library or symbol instances on the Stage. This selection can include bitmaps
also.
3. From the Generate Sprite Sheet dialog box, select Options, and then click Export.
Click www.youtube.com/watch?v=UDdKMV_rvbs to view a demonstration on Creating Sprite Sheets in Flash CS6.
When an FXG file is created, vector graphics get stored directly within the file. The elements for which no corresponding
tag exists in FXG are exported as bitmap graphics and then referenced in the FXG file. Such elements include some
types of bitmaps, filters, blend modes, gradients, masks, and 3D.
When a file containing vector and bitmap images is exported using FXG export, a separate folder simultaneously gets
created along with the FXG file. This folder is named as <filename.assets> and contains the bitmap images associated
with the FXG file.
5. Enter a name for the exported file. Then, select a location, click Save, and click OK.
1. Select File, then click Export, and then click Export Movie.
3. Click Export.
For detailed step-by-step procedure, refer to demo Exporting Image and Video from:
eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Exporting Video and Sound >>
Exporting as WAV audio
2. _________ option in Export Bitmap dialog box applies anti-aliasing effect to the exported bitmap.
Smooth Resolution Bit depth Color Depth
8.3 Publishing Movies
The Publish Settings can be adjusted to minimize the file size of an animation. This is because a large file size
increases the download time and cause the animations to play incorrectly. The Publish command creates a Flash SWF
file and an HTML document that inserts a Flash movie into a browser window. Flash also enables publishing of FLA
file in alternative file formats including GIF, JPEG, PNG, and QuickTime. Publish Settings can also be used to choose
the delivery mode of the animation, which can be a standalone projector file, a QuickTime movie, an image file, or an
embedded file in a Web page. Settings can also be specified at one place. From the File menu, select Publish Settings
to open the Publish Settings dialog box. The Formats tab appears selected by default. Refer to Figure 8.2.
Formats Description
GIF GIF files allow exporting of drawings and simple animations for use in Web pages. Standard GIF
files are compressed bitmaps. Animated GIFs can also be created.
JPEG JPEG files can display many more colors than GIF files and therefore, produce more realistic
photos and complex drawings. JPEG graphics are compressed to reduce the file size. However,
they decompress when downloaded, using more memory. Flash exports the first frame in the
movie as a JPEG, unless a different keyframe is marked by placing the playback head on the
keyframe.
Formats Description
PNG PNG files can display more colors than GIF files, and support transparency. They offer some
advantages of both GIFs and JPEGs, but not all browsers support them completely.
QuickTime This format is used for digitized movies. QuickTime movies are played using the QuickTime
player. Flash provides importing, exporting, and publishing of QuickTime movies.
C r e a t i n g A projector can be used for a Flash movie for placing on a CD-ROM. A Windows or a Mac
Projectors version from either platform can be created. However, if a Mac version is created in Windows, a
file translator such as BinHex is needed so that the Mac Finder recognizes it as an application.
Table 8.3: Formats for publishing animated files
Figure 8.3: Publish Settings dialog box with the Flash tab active
Click here to know more about the Publish Settings for Flash dialog box options.
The HTML parameters determine various settings, such as the placement of the Flash movie window, background color,
and the size of the movie. It sets attributes for the object and embed tags. However, such settings can be changed in
the HTML tab of the Publish Settings dialog box. Changing these settings will override the options that have been in
the movie. Refer to Figure 8.4.
Figure 8.4: Publish Settings dialog box with the HTML tab selected
Click here to know more about the Publish Settings for HTML dialog box options.
A Mobile Content Simulator acts as a tool for testing content created with Adobe AIR in an imitated Android or iOS
environment. This allows simulating hardware keys, Accelerometer, Multi-touch, and Geo-location. With the Mobile
Content Simulator, from the Control option, the Test Movie command can be used to test the Flash file in the AIR
Debug Launcher for Mobile, which in turn launches the Simulator.
With Flash Professional CS6 Update 12.0.2, AIR applications can be deployed on iOS directly, bypassing the use of
iTunes. This feature reduces the downloading time required to publish an AIR application for iOS and thereby improves
the performance significantly.
Click here to know more about the Adobe® AIR® for Android.
It is advisable to install iTunes on those machines that have Flash Professional CS6 installed in them.
To enable direct deployment on iOS device, the following steps can be implemented:
1. Ensure that iTunes is installed on the machine on which Flash Professional CS6 is installed.
2. In Flash Professional CS6, on the Properties panel, click the button beside the Target drop-down to bring up the
AIR for iOS Settings dialog box.
3. On the Deployment tab, select Install Application On The Connected iOS Device option.
4. Click Publish.
The mobile device used can impose certain compatibility restrictions on ActionScript commands and sound
formats that are supported.
eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Publishing Movies>> Publishing
and previewing
8.4 Summary
In this session, Exporting and Publishing, you learned that:
¾¾ Publishing a Flash movie is the last step towards completing an animation. On a macro level, exporting in Flash
is broadly classified into the following two categories — namely, Export Image and Export Movie.
¾¾ The various formats in which images and image sequence can be published are Flash Movie, Enhanced
Metafile, Windows Metafile, EPS 3.0, Adobe Illustrator, AutoCAD DXF, Bitmap, JPEG, GIF, and PNG.
¾¾ The Flash Professional CS6 release has introduced a new feature called as Sprite Sheet Generator. By using
this, the GPU does not have to load all graphic components on the primary memory but only load a single file.
This enhances the performance of the GPU.
¾¾ The FXG format is a graphic interchange file format, which works with the Flash Platform. FXG files can be
used in tools, such as Adobe Flash Builder and Adobe Flash Catalyst to develop rich Web experiences and
applications.
¾¾ Apart from SWF and GIF, Windows AVI and QuickTime are the formats in which files can be exported using the
Export Movie command.
¾¾ With Flash Pro, videos can be imported or exported with encoded audio. The two options for exporting Flash
Pro documents as QuickTime are QuickTime export and Publish as QuickTime.
¾¾ By using the Sound Format option, only the sound file of the current document is exported to a single WAV file.
¾¾ The formats in which animated files can be published are JPEG, GIF, PNG, QuickTime and Creating Projectors.
¾¾ By using the Publish Settings dialog box, animated files can be published into Flash, HTML, and for mobile
devices. Direct is a new window mode, which enables hardware accelerated content using Stage3D. However,
the Stage3D requires Flash Player 11 or later to function.
¾¾ This file can be previewed and published after the file format types and specifications for each file has been
entered in the Publish Settings dialog box.
8.5 Exercise
1. The __________ for Android and iOS allows Flash Pro users to create interactive content for mobile devices.
Adobe AIR
Adobe Illustrator
2. ____________ acts as a tool for testing content created with Adobe AIR in an imitated Android or iOS environment.
Test Movie
AVI
MP3
MOV
GIF
4. QuickTime export option assists in combining the interactive features of Flash Pro with the multimedia and video
features offered by QuickTime in a single QuickTime 4 movie.
True
False
5. By using sprite sheets, the GPU does not have to load all graphic components on the primary memory but only has
to load a single file.
True
False
Session 9
Introduction to ActionScript 3.0 and Programming
Concept
Learning Outcomes
In this session, you will learn to:
¾¾ Understand the basic concept of ActionScript 3.0 (AS3) programming
¾¾ Describe the uses of Conditionals, Loops, and Operators in AS3 programming
¾¾ Understand the use of static method and static variable
¾¾ Identify different kinds of functions
¾¾ Describe the use of Array in AS3 programming
¾¾ Distinguish between Web scripting, interactivity, and AS3 programming
AS3 is not required for content that run in Adobe Flash Player 9, but it opens the door to performance improvement
available with the ActionScript Virtual Machine 2.0 (AVM2), a new virtual machine. However, ActionScript Virtual Machine
(AVM1) executes ActionScript 1.0 and ActionScript 2.0 code and is supported by Flash Player 9.
AS3 includes new features of the core language and an improved Flash Player API that provides increased control of
low-level objects.
Thus, it is very important to understand what a computer program is and how it works. Refer to Figure 9.1.
In real-life, all programming is done using a combination of approaches. In Object-Oriented Programming (OOP),
the problem is sub-divided by identifying domain objects, which is a top-down step, refining those objects and then
recombining into a final program, which is a bottom-up step.
There are several differences between top-down approach and bottom-up OOP approach. Refer to Table 9.1.
AS2 programs cannot be compiled for output in AS3, unlike many compilers that support previous versions
and new ones as well.
Owing to this compatibility issue, AS2 and prior codes cannot be executed in AS3. ActionScript is designed to make the
creation of highly complex applications with large data easy. An SWF file written in ActionScript 1.0 or 2.0 can be loaded
by AS3 code, but it cannot access SWF file’s variables and functions.
One major drawback about AS3 is that more steps are required to code for a simple application.
Click here to know more about the Flash Client Runtime Environments.
9.1.7 Compilation
ActionScript program needs to be converted into a binary format that Flash runtime can understand. This is known as
ActionScript bytecode or ABC. ActionScript bytecode cannot be executed by Flash runtimes and needs to be wrapped
in a binary file known as SWF file, which stores the bytecode in Flash file format or SWF. The process of converting an
ActionScript program into a bytecode is called as compiling a program and the process of generating SWF file is known
as compiling the SWF file or publishing the SWF file.
A software module known as a compiler is required to compile AS3 programs and SWF files. A compiler that compiles
ActionScript code is known as an ActionScript compiler. A compiler that generates SWF files is known as an SWF
compiler. Any SWF compiler that claims full support for the Flash file format includes an ActionScript compiler.
There are two levels of compilation that takes place in ActionScript code. In the first level, the developer compiles the
code from readable format by the Flash runtime. In the second level, the ActionScript bytecode is automatically compiled
by the Flash runtime to a format understood by the hardware running the program. The second level is called just-in-time
compilation or JIT because it takes place just before the particular bytecode is being complied and is required by the
program.
There are four types of variables: local variables, instance variables, dynamic variables, and static variables. Refer to
Figure 9.2.
Figure 9.2: Types of variables
In a computer program, the memory location where the data is stored is called a variable. The smallest variable is one
bit, and the largest is up to millions of bytes. Current processors stores data of 4 or 8 bytes at one time (32 and 64 bit
CPSs). Hence, the big variables take longer to read or write. The size of the variable depends on its type. Following are
the types:
¾¾ String: This is a textual value, similar to a name of the text.
¾¾ Numeric: There are three specific data types for numeric data:
●● Number: This is any number, which includes values with or without a fraction.
●● uint: This is an unsigned integer, which means a whole number that cannot be negative.
¾¾ Boolean: This data type has only two values: true or false or 1 and 0. No other values are considered valid.
¾¾ Null: This type of data contains only one value called as null, which is also the default value for the String data
type of all classes defining complex data types, such as Object class.
¾¾ Void: This data type has only one value, which is undefined. In the earlier versions of ActionScript, undefined
was the default value for instances of the Object class, but in AS3, the default value is null.
ActionScript stores primitive values internally as immutable objects. Storing immutable objects means,
that passing by reference is effectively the same as passing by value. This reduces the memory usage and
increases execution speed, as references are usually smaller than the values themselves.
●● Date: This data provides information about a single moment in time, which is a date and time.
●● XML: This data is a revised XML object based on the E4X (Standard ECMA-357).
●● Object: This type is defined by the Object class, which also serves as the Base class for all class
definitions in ActionScript.
●● Array: This contains a list of data. Though AS3 is a strongly typed language, the contents of an Array may
be of any type and values must be cast back to their original type after being retrieved.
9.1.9 Classes and Objects
Assume an example of making a car from scratch. The entire process needs to be listed. A person would not just go to a
metal shop for welding. He would rather start by drawing several blueprints for each part of the car, describing a specific
part conceptually and matching the actual part of a car, such as seats, brakes, wheels, steering wheel, and so on. Each
of these parts would have to be manufactured individually and assembled in accordance with the blueprint.
In a similar way, classes are the blueprints on which objects are based. Incarnations or instances of classes are objects.
Each class describes both the characteristics and behavior of a particular type of object.
Class definitions contain constants and variables, which have the data values and methods. These are functions that
hold the behavior to the class. Either primitive values or other objects are stored. Primitive values are numbers, strings,
or Boolean values.
It is important for programmers, with previous ActionScript experience, to note that the Object data type is not a default
data type, despite the fact that all the other classes derive from it.
As per AS3, the following lines of code are equivalent because the variable is of Object type:
var someObj:Object;
var someObj;
In AS3, the concept of untyped variables has been introduced that can be selected in the following two ways:
var someObj:*;
var someObj;
An untyped variable is different as compared to a variable of type Object as it can hold the special value undefined,
whereas a variable of type Object cannot hold.
Classes can be defined using the class keyword by declaring class properties in the following three ways:
¾¾ By using the const keyword to define the constants
¾¾ By using the var keyword and properties to define the variables
¾¾ By using the get and set attributes in a method declaration, the setter properties can be defined
An important group of classes is the native classes that are directly built into ActionScript.
An instance of a class can be created using the new operator. For example, an instance of the Date class called
myBirthday is created as follows:
var myBirthday:Date = new Date();
An object is an instance of a class. As seen earlier, every object has states and behaviors. For example, a human being
has states such as color and name, and behaviors, such as habits, eating, walking, and so on. Similarly, a software
object’s state is stored in fields and behavior, which is shown through methods.
A running ActionScript program is a group of interoperating objects that are based on a set of classes that represent
tangible and intangible concepts in a program. Objects are made from the classes in a program and tell them what has
to be done. Thus, the behavior of the objects is determined by what the object does.
Thus, a program that is built with classes and objects is known as Object-Oriented Programming (OOP). Refer to Table
9.2.
Class Description
String It represents textual data, which is a string of characters.
Boolean It represents the logical states, true and false.
Number It represents floating - point numbers, which are numbers with a fractional value.
int It represents integer numbers, which are numbers with no fractional value.
uint It represents positive integer numbers.
Array It represents an ordered list.
Class Description
Error It represents a program error, which is a problem in the code.
Date It represents a specific point in time.
Math It contains common mathematical values and operations.
RegExp It defines tools for searching and replacing text.
Function It represents a reusable set of instructions that can be executed, or called, repeatedly.
Object It defines the basic features of every object in ActionScript.
Table 9.2: Aspects that complete the design of a character
I – src
I - VirtualOffice.as
To avoid the naming convention with the built-in classes name, use Packages.
9.1.11 Packages
Packages help in bundling class definitions together to facilitate code sharing and reduce naming conflicts. Packages
also allow organizing class files. As the name suggests, packages is a group of classes. Each package is limited to a
physical region of a program called package name.
In AS3, the packages are implemented with namespaces. Namespaces help in controlling the visibility of identifiers,
such as property and method names, and can be applied to code whether it resides inside or outside a package. At the
time of declaring a package, create a special type of namespace, which is known at the compile time. Namespaces
allow managing of the visibility of individual properties and methods.
One can use a package definition directive to create a new package. All the program instructions in ActionScript are
known as Directives.
A definition that creates something in a program defines or declares thing. Definitions are also known as declarations.
Following is the general form of package definition directive:
package packageName {
The keyword to start all package definitions is package that tells ActionScript to create a package. The desired package
name is represented by packageName and the class source code within a package takes the name of the package.
This is followed by marking the beginning and end of the package contents using curly brackets like {and}.
To insert the source code between the curly brackets with the packageName, use the following:
package packageName {
For example, a class named Solitaire in a package named game becomes game.Solitaire. The package name
is written first followed by the class name with a period (.) character. This helps in identifying names between different
parts of a program or between the classes and ActionScripts’ built-in classes.
Here, notice that in the package name, the domain name is reversed. Now, use packages in the virtual office program
by using the package name office, without any leading domain name.
To define the office package, add the following code to the file VirtualOffice.as:
package office {
After having added a package to the file VirtualOffice.as, change the file location on the file system to match the
package. The Adobe’s ActionScript compiler imposes a requirement that when a source contains a class or a definition
in a package, it must be stored in a folder structure that matches the package name.
Thus, a new folder named office is created in the program’s file structure and VirtualOffice.as moves into it. Now,
the file structure of the program’s source files becomes, as follows:
virtualoffice
I – src
I – office
I - VirtualOffice.as
After having the package definition, add the VirtualOffice class to it.
The keyword class is followed by a class name identifier that refers to a name. All the first words must begin with
a capital letter as in VirtualOffice.
Block statement is the curly brackets following identifier. In the preceding class definition, which is also known as the
class block or class body, contains directives describing the characteristics and behavior of the class and its instances.
For example, the class definition of VirtualOffice will be placed in the packaged body, in the file VirtualOffice.as:
package office {
class VirtualOffice
}}
Since the preceding VirtualOffice class definition resides in a package named office, the complete name of the
class is office.VirtualOffice. The shorter class name is VirtualOffice.
Create another class in the program, for example VirtualWorkforce class and create objects that represent the
workforce in the office.
Just like VirtualOffice, place the source code for the VirtualWorkforce class in the office package in its file
named VirtualWorkforce.as saved in the office folder. The code from the VirtualWorkforce.as file is as
follows:
package Office {
class VirtualWorkforce {
}}
There are two classes in the game namely, VirtualOffice, which is the main class and VirtualWorkforce, which
represents the employees in the game. The classes reside in the package office, and are stored in the plain-text files
named VirtualOffice.as and VirtualWorkforce.as.
■■ Access control modifiers for classes
An access modifier helps to modify classes that can instantiate a particular class or access one of its properties.
Access modifiers in AS3 are of four types:
¾¾ public
¾¾ private
¾¾ protected
¾¾ internal
A class in a package is used by code that also resides in that package. This is by default. It is important to define
a class outside the package with the public attribute, wherein the class attributes direct how the class and its
instances can be used in a program.
In a class definition, the attributes are listed before the keyboard in the following way:
attribute class ClassIdentifier {
Click here to know about the access control modifiers for classes.
■■ Code comments in ActionScript
Code comments are notes that can be read only by a programmer and ignored by the compiler. Code comments
in ActionScript are in two varieties: Single line starts with two slashes (//), and multiline starts with the character
sequence /*, and ends with the character sequence */.
¾¾ Following is the single line comment:
// Only programmers are here
Only programmers
are here
*/
The current code for the office game is as follows:
// Contents of the file VirtualOffice.as
package office {
package office {
}}
The next step in the development of a program is constructing method of the main class, VirtualOffice.
A function definition is used within a class block to create a constructor method, as shown in the following code:
class SomeGroup {
function SomeGroup ( ) {
The keyword function begins the constructor method following the code. This is followed by the constructor method
name, which is same as the class name. Next, a pair of parenthesis containing a list of constructor parameters follows.
Following the parameters list are the curly brackets ({}) that are a block statement, similar to the one in the package
and class definitions. The block statement of the constructor method is known as a constructor body that contains the
directives that initialize instances. Refer to the following example:
class SomeGroup {
The directives in the constructor body are executed whenever a new instance is created in a sequence order starting
from top to bottom. This is also called as executing the constructor or running the constructor. ActionScript provides
a default constructor that performs no initialization on new instances of the class when a class does not define a
constructor function. It is therefore necessary to include an empty constructor as this provides an indication that the
class design does not require a constructor and can be done by adding a comment. Refer to the following example:
class SomeGroup {
function SomeGroup ( ) {
} }
The constructor method of an application’s main class is the program point of entry.
The following code is an example of adding a constructor method to the VirtualOffice class:
package office {
This application now has a point of entry. On starting the application, the Flash runtime creates a VirtualOffice
instance that executes the VirtualOffice constructor method in the process. The first thing to do is to create a
VirtualWorkforce object, which means adding an employee to the office.
In the following example, the code is used to make an object from the VirtualWorkforce class:
new VirtualWorkforce
Similarly, multiple independent objects can be made from the same class, as shown in the following example that
creates two VirtualWorkforce objects:
new VirtualWorkforce
new VirtualWorkforce
A value supplied to a constructor parameter when an object is instantiated is known as constructor argument.
}}
As mentioned in the earlier code, the workforceName instance variable set through a VirtualWorkforce instance
from within the VirtualOffice is defined in the VirtualWorkforce class. Therefore, the workforceName instance
variable is accessible to code in the VirtualOffice class. This means that when a class makes its instance variables
accessible to code in other classes, it allows those classes to amend the characteristics of its instances.
■■ Access control modifiers for instance variables
An instance variable’s access control modifier controls that variable’s accessibility in a program. Access control
modifiers are used to limit access. Refer to Table 9.3 that lists some access control modifiers.
In this code, methodName is the name of the method whose code should be executed, and object is a reference to
the specific instance that will theoretically perform the task represented by the particular method. Calling a method of
an object is done by using a call expression to execute the code in an instance method’s body. Similarly, it also means
calling a method through an object, or calling an object’s method. The term invoke is also used to mean call.
Methods are functions that are a part of a class definition bound to that instance, the moment it is created. They help in
implementing functionality that affects individual instances of a class. A method cannot be used apart from the instance
to which it is attached. Methods that are declared without the static keyword are called instance methods. Refer to
the following example:
package Office {public class VirtualOffice {
// variable workforce
Instance member or members refer to a class’s instance methods and instance variables.
Quick Test 9.1
1. The process of creating an object is called as ___________ the object.
Executing Implementing Initiating Instantiating
2. Methods that are declared without the static keyword are called dynamic methods.
True False
The if statement contains two blocks of code and a test expression that indicate which block should execute. The
following code is used to create an if statement:
if (testExpression) {
codeBlock1
} else {
codeBlock2}
ActionScript executes codeBlock1 or codeBlock2, depending on the value of testExpression. If the Boolean value
is True of the value of testExpression, then the first block is executed and if the Boolean value is False of the value
of testExpression, then the second block is executed.
ActionScript converts testExpression to a Boolean object if the value of testExpression is not a Boolean value
and uses the result of that conversion to decide which block to execute.
For example, in the if statement, the testExpression has the Boolean value as True, so the value of the variable ‘a’
is set to “Mango”, not “Orange”. Refer to the following example:
var greeting;
if (true) {
greeting = “Mango”;
} else {
greeting = “Orange”;
}
Sometimes if statement is used without else. In this case the example will be as follows:
var greeting;
if (true) {
greeting = “Mango”;
}
■■ Chaining if statements
Multiple if statements are chained together to make a decision between two or more courses of actions. Following
is a code for a condition with three possible outcomes:
if (testExpression) {
codeBlock1
} else if (testExpression2) {
codeBlock 2
} else {
codeBlock3
var greeting;
if (language == “english”) {
greeting = “Friend”;
greeting = “Dost”;
}
greeting = “Mitra”;
else
greeting = “Friend”;
■■ Switch-Case Statement
The switch statement helps in the execution of several code blocks based on the value of a single testExpression,
in the following form:
Switch (testExpression) {
case expression1:
codeBlock1
break;
case expression2:
codeBlock2
break;
default:
codeBlock3
All statements following the default label are executed if no case expression matches testExpression.
In the following code, ActionScript attempts to match testExpression with each of the supplied case expressions,
beginning from the top to bottom. The case expressions and statement label case are followed by a colon.
All the statements follow soon after the case labels are executed, if testExpression matches a case expression.
This includes those in any subsequent case blocks. However, they can be prevented from executing, by using the
break statement at the end of each block. On the other hand, the break statement can be omitted when more than
one condition is needed to activate the execution of the same block of code.
In the following code, codeBlock1 executes when testExpression matches either expression1 or expression2:
switch (testExpression) {
case expression1:
case expression2:
codeBlock1
break;
case expression3:
codeBlock2
break;
default:
codeBlock3
The following code shows how to implement multiple conditions using a switch statement, which is easier to read
and scan quickly:
var month;
switch (number) {
case “1”:
month = “January”;
break;
case “2”:
month = “February”;
break;
case “3”:
month = “March”;
break;
case “4”:
month = “April”;
break;
default:
For detailed step-by-step procedure, refer to demo Basics Programming Concept Conditionals from:
eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Conditionals, Loops, and
Operators>> Conditionals
9.2.2 Loops
A loop allows a statement block to be executed repeatedly and is also referred to as Counter Loops, as long as its
expression remains True. The different types of loops are as follows:
¾¾ while statement
A while statement is similar to the if statement where the main statement encloses a code block that is
executed only when a testExpression is True, as shown in the following code:
while (testExpression) {
codeBlock
¾¾ do-while statement
The body of a do-while loop is executed only once. This is done through the loop and the syntax for the do-
while statement is like an inverted while statement.
do {
codeBlock
} while (testExpression);
Example:
var address = “abrock.org”;
var i = 0;
do {
isValidAddress = true;
if (address.charAt(i) ==”@”) {
break;
i++;
trace(isValidAddress)
The do-while loop guarantees the execution of the block at least once, as the condition is checked only after
the code block is executed. Hence, the output generated through the address does not contain the character
“@” and the trace shows “true”.
¾¾ for statement
for loop is written with more compact syntax as given follows:
for (initialization; testExpression; update) {
codeBlock }
Example:
var i:int;
trace(i);
Output:
The code shown for loop checks whether a string contains the @ character. It is identical to the earlier while
loop that performs the same task, as follows:
var address = “ ab@rock.org”;
if (address.charAt(i) == “@”) {
isValidAddress = true;
break;
trace(isValidAddress)
Loops are used to process lists of loops. Refer to the following example:
var address = “ab@rock.org”;
var i = 0;
The while statement of the loop runs once for every character in the address. To be able to retrieve the numbers
of letters in a string, the string class’s instance variable length is used. Refer to the following example:
while (i < address.length) {
i++;
One of the characters in the address must be retrieved and compared to the string ‘@’ each time the loop body runs.
If the retrieved character is equal to ‘@’ then the isValidAddress is True. In order to retrieve a specific character
from a string, use the built-in String class’s instance method ‘charAt’, which is a short for ‘character at’, where
the character indices start at zero.
As per the example, the call expressions have the value ‘a’ because the character at index 0 is ‘a’.
address.charAt(0);
var i = 0;
if (address.charAt(i) = = “@”) {
isValidAddress = true;
i++;
var i = 0;
if (address.charAt(i) ==”@”) {
isValidAddress = true;
break;
i++;
trace(isValidAddress);
For detailed step-by-step procedure, refer to demo Basics Programming Concept Loops from:
eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Conditionals, Loops,
and Operators>> Loops
9.2.3 Operators
To perform calculations and to compare, modify, or combine variables, objects, properties, and expressions, special
symbols or words are used. These are called operators. Operands are values – variables, literals, or expressions used
as inputs by an operator. Operators can be of various types:
¾¾ Arithmetic operators
¾¾ Assignment and compound assignment operators
¾¾ Equality and comparison operators
¾¾ Logical operators
■■ Arithmetic operators
The additive and multiplicative operators (+, -, *, /) take two operands and perform appropriate calculations.
The modular operator returns the remainder after a division operation. Increment (++) and decrement (--) are unary
operators and therefore require only one operand. They either add (increment) or subtract (decrement) 1 from the
expression they are used on, and it can be used either as prefix or postfix operators. Refer to Table 9.4.
The assignment operator assigns the value of expression on the right to the expression on the left. Compound
assignment operators perform arithmetic on a variable and then store the result in that same variable. Refer to Table
9.5.
Operator Operation Performed
= This is assignment. It assigns the value of expression2 to the variable in expression1.
+= This is addition assignment. It assigns expression1 the value of expression1 + expression2.
-= This is subtraction assignment. It assigns expression1 the value of expression1 - expression2.
*= This is multiplication assignment. It assigns expression1 the value of expression1*
expression2.
/= This is division assignment. It assigns expression1 the value of expression1 /expression2.
%= This is modulo assignment. It assigns expression1 the value of expression1/expression2.
Table 9.5: List of Assignment and Compound assignment operators
■■ Equality operators
The equality operators take two operands, compare their values, and return a Boolean value. The relational operators
take two operands, compare their values, and return a Boolean value. Refer to Table 9.6.
Operators that take two operands and return a Boolean result are known as Logical operators, and they are used to
combine conditions. Refer to Table 9.7.
The operators that are used for creating Array and Objects literals, grouping expressions, calling functions,
instantiating class instances, and accessible properties are the primary operators.
A short hand method of applying the else conditional statement is called the conditional operator. There are some more
types of operators, such as Bitwise logical operators and Bitwise shift operators.
Static variables are used to keep track of information that relates logically to an entire class, as opposed to information
that varies from instance to instance.
Static variables are created using variable definitions within class definitions and must also include the static attribute
as shown in the following code:
class SomeClass {
Similar to instance variables, the static variables in a program use the access control modifiers to control the accessibility.
The access control modifiers that are available for static variable definitions are the same to those available for instance
variable definitions. Internal (package-wide access) is used when the modifier is not specified. Similarly, when a modifier
is specified, then it is positioned before the static attribute, as demonstrated in the following code:
class SomeClass {
Add static variables to the VirtualOffice class. There are two pieces of information in the VirtualOffice class:
the total resource and the maximum allocated Business Unit (BU).
The following example shows the total resource and maximum allocated BU definitions:
package office {
9.3.2 Constants
A constant is a value that once initialized, remains fixed for the rest of that program. A constant could be a static variable,
instance variable, or a local variable. A standard variable-definition syntax is used to create a constant with the keyword
const instead of var.
¾¾ To create a constant static variable, the following code is used within a class body:
static const IDENTIFIER =value
¾¾ To create a constant instance variable, the following code is used within a class body:
const IDENTIFIER =value
¾¾ To create a constant local variable, the following code is used within a class body:
const IDENTIFIER =value
identifier2 = value2,…
identifiern = valuen) {
Similar to instance methods, the accessibility of static methods in a program can be controlled by access control
modifiers. The access control modifiers existing for static methods definitions are same as those available for instance
method definitions.
Internal is used when no modifier is specified. Likewise, when a modifier is specified, then it is placed before the static
attribute. To invoke a static method, the following code is used:
SomeClass.methodName(value1, value2,...value‘n’)
In this code, SomeClass is the class within which the static method is defined, methodName is the name of the method,
and value1, value2, ...value ‘n’ is a list of zero or more method arguments.
9.4 Functions
Function is a set of instructions that carry out tasks that are independent of any class or object. Functions have the same
syntax and usage as instance methods and static methods. They are defined with the function keyword and are used
in standalone form.
Blocks of code that carry out specific tasks and can be reused in a program are called Functions. In AS3, the two types
of function are as follows:
¾¾ methods
¾¾ function closures
Depending on the context in which the function is defined, a function is called a method or a function closure. If a function
is defined as part of a class definition or attaches it to an instance of an object, it is called a method. If it is defined in any
other way, it is called a function closure.
Functions are of two types — namely, System defined or inbuilt function and User defined or external.
System defined or inbuilt functions are already defined in the system, so it need not be created again and can be used
directly. For example, ToString();, trace();, setInterval();, and so on.
//user code
}
In this code, identifier is the name of the function and param1, param2, and paramn is an optional list of the function’s
parameters.
In order to make the function accessible throughout the program, the access control modifier public precedes as follows:
package packageName {
Global functions are defined at the package-level within the unnamed package as they can be referenced globally
during a program, and does not need the import statement. As mentioned in the example, the following code defines
a global function, isLinux( ). Since the isLinux( ) function is defined within the unnamed package, it can be
accessed by any code in the same program.
package {
import flash.system.*;
}}
The isLinux( ) is used in the given Welcome class. Observe that isLinux( ) need not be imported before being
used.
package setup {
// Do something Linux-specific
}}}}
Functions that can be declared within other functions are called as nested functions, and it is available only within its
parent function, unless a reference is given to external code as shown in the following example:
// Define method x ( )
Public function x ( ) {
y( );
function y( ) {
The nested function can be invoked anywhere within the containing method. Access control modifiers, such as
public and internal, cannot be applied to nested functions.
// Ok to use f ( ) here
class A {
// Ok to use f ( ) here
public function A ( ) {
// Ok to use f( ) here
// Ok to use f ( ) here
function f ( ) {
}
Since the function is defined outside the package statement, it can be used anywhere within A.as, but cannot access
outside A.as. However, the f ( )’s definition does not include any access control modifier, such as public and internal.
function b ( ) {
}
9.4.5 Functions as Values
Every function in ActionScript is represented by an instance of the Function class that can be assigned to a variable,
passed to a function, or returned from a function like a value. The following code defines a function, p ( ) and then
assigns it to a variable q. The parentheses operator ( ) is omitted, if it were included, the code would assign p ( )’s
return value to q, as follows:
function p ( ) {
var q = p;
On assigning a variable to a function, it can be invoked through that variable using the standard parentheses operator,
( ).
In the following example the code invokes the function p( ) through the variable q:
p( );
As mentioned previously, param1, param2, …paramn is an optional list of parameters. The function can be assigned,
which is defined by a function literal outside the expression in which the literal occurs to a variable as follows:
var someVariable = function (param1, param2, …paramn) {
trouble ( );
A recursive function calls itself without conditions because if left unchecked, infinite recursion would trap a program in
an endless cycle of function execution. To avoid this, practical recursive functions calls themselves only when a given
condition is met.
if (n < 0) {
} else if (n <= 1) {
return 1;
} else {
return n * factorial(n-1);
// Usage:
factorial(3); // Returns: 6
if (n < 0) {
} else {
var result = 1;
result = result * i;
}return result;
}}
Examples 1 and 2 show two different ways to solve the same problem. As per the recursive approach, “The factorial
of 6 is 6, multiplied by the factorial of 5. The factorial of 5 is 5, multiplied by the factorial of 4...”, and so on. Whereas,
the nonrecursive approach loops over the numbers from 1 to n and multiplies all of them together into one big number.
Function recursion provides a simple solution by calling the same function repeatedly and moving on to a complex
problem. Repeated function calls are less competent than loop iterations. The nonrecursive approach to calculating
factorials is more efficient than the recursive approach.
For detailed step-by-step procedure, refer to demo Working with Functions from:
eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Functions>> Recursive functions
9.5 Arrays
Multiple values can be stored in a single data structure with the help of arrays. Arrays can also be multidimensional,
containing elements that are themselves arrays.
The examples show two separate strings that are followed by an array containing two strings as follows:
“bananas” // A single string
There are differences in the ways arrays are implemented across different languages as many languages do not allow
arrays to contain different types of data. An array can contain numbers or strings, but not both in the same array.
An array within an array is called a nested array or a two-dimensional array as given in the following example:
// Simple numeric elements
[6. 7, 8];
[2, 4, 5 + 9]
When more than one argument is supplied, or when a single non-numeric argument is supplied, then each argument
becomes one of the element values in the new array, as given in the following example:
new Array(“book”, “pencil”, “ruler”)
Example:
var names:Array = new Array(“Jerry”, “Sam”, “Dan”);
trace(names[0]); // output: Jerry
Example:
var names:Array = new Array(“Jerry “, “Sam”, “Kate”)
trace(names.length); // output: 3
Example:
var student:Array = new Array(35);// Note the single numeric argument
trace(student.length);// output: 35
9.5.7 Adding Elements to an Array
There are three Array class methods: push( ), unshift( ), and splice( ), or concat( ) that allow inserting of
elements in an array.
¾¾ push( ) method
In the push( ) method, one or more elements are appended to the end of an array, which simply means that
this method will have the highest index number if the last element inserted into the array is used.
Syntax:
theArray.push(item1, item2,...itemn);
Example:
// Create an array with two elements
// Add an element
¾¾ unshift( ) method
By using the unshift( ) method, which is always at index number 0, one or more elements can be inserted
at the beginning of an array.
Syntax:
theArray. unshift(item1, item2,...itemn);
Example:
menuItems.unshift(“site map”);
trace(menuItems); // output: site map, home, about us, products, services, contact
¾¾ splice( ) method
By using the splice( ) method any number of items can be inserted at a specified index in the array.
Syntax:
theArray.splice(startIndex, deleteCount, item1, item2,...itemn)
As mentioned in the syntax, the array is a reference to an Array object; startIndex is a number that specifies
the index at which element removal and optional insertion should commence (remember that the first element’s
index is 0); deleteCount is an optional argument that dictates how many elements should be removed
(including the element at startIndex). When deleteCount is omitted, every element including startIndex
and thereafter is removed. The optional item1, item2, itemn parameters are items to be added to the array
as elements starting at startIndex.
Example:
var menuItems:Array = [“site map”, “home”, “about us”, ”products”, ”services”, ”contact”];
menuItems.splice(0, 1, “feedback”);
¾¾ concat( ) method
Two or more arrays are combined by concat( ) method to form a single new array, which it returns. The
concat( )method has the following general form:
Syntax:
origArray.concat(elementList)
The concat( ) method appends the elements contained in elementList, one by one, to the end of origArray
and returns the result as a new array, leaving origArray untouched. Normally, the returned array is stored in
a variable. Here, simple two string items are to be added to the array as shown in the following example:
Example:
var menuItems:Array = [“home”, “about us”, “products”, “services”, “contact”];var
subMenuServices:Array=menuItems.concat(“Website Development”, “eLearning”);
trace(subMenuServices);
// output: home, about us, products, services, contact, Website Development, eLearning
9.5.8 Removing Elements from an Array
The three Array methods that allow to remove elements from an array are pop( ), shift( ), and splice( ).
¾¾ pop( ) method
The element at the highest index number is removed by the pop( ) method from the end of the array. The pop(
) method is the antithesis of push( ): it removes the last element of an array.
Syntax:
theArray.pop( )
Example:
var menuItems:Array = [“home”, “about us”, “products”, “services”, “contact”];
menuItems.pop( )
¾¾ shift( ) method
The shift ( ) method is used to remove the element from the beginning of the array as it always removes the
element at index number 0. However, the unshift ( ) method is used to add an element to the beginning of
an array.
Syntax:
theArray.shift( )
Example:
var menuItems:Array = [“home”, “about us”, “products”, “services”, “contact”];
menuItems.shift( )
¾¾ splice( ) method
The splice( ) function can both remove elements from and add elements to an array. To remove an arbitrary
number of elements starting at the index number as specified by the first argument sent to the method, use the
splice ( ) method, which is also used to insert elements.
To remove element syntax, refer to the following code:
Syntax:
theArray.splice(startIndex, deleteCount)
Example:
var menuItems:Array = [“site map”, “home”, “about us”, ”products”, ”services”, ”contact”];
menuItems.splice(0, 1)
Example:
var menuItems:Array = [“home”, “about us”, “products”, “services”, “contact”];
menuItems.toString( )
Next, the clothes are placed into a container array named spreadsheet as shown in the following example:
var spreadsheet:Array = [tshirt, shirt, jeans];
By multiplying the quantity and the price of each row and adding them all together, the total cost of the order can be
found. A two-dimensional array’s elements using two indexes (one in the rows and one for the column) can be accessed.
The expression (0) represents the first row’s two-column array. The spreadsheet [0] [1] can be used, which yields 3.99.
Following are the steps to calculate the total price of the items in the spreadsheet:
// Create a variable to store the total cost of the order.
// Now find the cost of the order. For each row, multiply the columns
For detailed step-by-step procedure, refer to demo Working with Arrays from:
eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Arrays>> Multidimensional
arrays
9.6 Summary
In this session, Introduction to ActionScript 3.0 and Programming Concept, you learned that:
¾¾ There are two kinds of programming techniques: top-down approach, and bottom-up approach.
¾¾ AS3 Execution: AS3 helps load SWF file written in AS1 or AS2.
¾¾ Classes and Objects: Classes are blueprints on which objects are based. Each class describes in code the
characteristics and behavior of an object.
¾¾ Building a Program: Design base forms the basis of development of a new ActionScript program that is broken
into logical set of classes.
¾¾ Packages: These help in bundling class definitions to facilitate code sharing and reduce naming conflicts.
¾¾ Access Control Modifiers: For classes, it helps to specify which classes can instantiate or access property.
¾¾ Code Comments: These are notes that a programmer can read and the compiler can ignore.
¾¾ Constructor methods are functions that share the same name as the class in which they are defined.
¾¾ Creating objects is a process of instantiating the object.
¾¾ AS3 data types are of two kinds — namely, Primitive and Complex.
¾¾ Variables and Values: An identifier or a name with a value is called a variable. The four types of variables are:
local, instance, dynamic, and static.
¾¾ ActionScript provides two Conditionals: the if statement, and the switch statement.
¾¾ Operators are special symbols that perform calculations. The four types of Operators are: Arithmetic, Assignment
and Compound, Equality and Comparison, and Logical.
¾¾ Functions are a set of instructions. The two types of Functions are methods and functional closure.
¾¾ Arrays act as a container for a set of items, for example, a list of songs.
¾¾ Adding elements to an array are done by three methods, namely — push( ), unshift( ), and splice( )
methods.
¾¾ Removing elements from an array can be done by three methods: pop( ), shift( ), and splice( ) methods.
¾¾ Multidimensional arrays are arrays themselves. They are also called as nested arrays.
9.7 Exercise
1. The process of converting an ActionScript program into a bytecode is called as _________.
Flash runtime
Compiling a program
Adobe AIR
OOP method
String
Date
MovieClip
XML
3. A special type of local variable that is created as a part of the constructor-method definition is called a
________________.
Constructor parameter
Constructor argument
Constructor body
Constructor function
4. Increment (++) and decrement (--) are unary operators and therefore require only one operand.
True
False
True
False
Session 10
Working with Built-in Classes (Text, Video, and Sound)
Learning Outcomes
In this session, you will learn to:
¾¾ Differentiate between the different types of text
¾¾ Identify different tasks that can be performed using text
¾¾ Explain the use of media class, such as video and sound
In AS 3.0, there are different built-in classes to perform text handling tasks. Some of them that can be performed using
classes are as follows:
¾¾ Modifying text field contents
¾¾ Using HTML in text fields
¾¾ Using images in text fields
¾¾ Selecting and manipulating text
¾¾ Capturing text input
¾¾ Restricting text input
¾¾ Applying formatting
¾¾ Cascading Style Sheets (CSS) styles to text
¾¾ Formatting text
An instance of a built-in TextField class is used to display text on the screen in Adobe Flash Player. The text can be
populated in the TextField from a text file or database. The text within a text field can appear as HTML content along
with images that are embedded in the rendered HTML format.
In addition, flash.text package classes can be used to establish an instance of a TextField to control the text’s
appearance. This is similar to the TextFormat and the StyleSheet classes. All the classes related to creating,
managing, and formatting text in ActionScript are in the flash.text package.
The properties defining the appearance of the text, such as size, color, and weight are present in the TextFormat
object or StyleSheet object.
Text can be formatted using a TextFormat object, which is then assigned to the text field. Using the StyleSheet
object, styles can be assigned to specific pieces of the text field content.
The properties of the TextFormat object are assigned to all the contents that are within a range of text or text field. For
example, one sentence can be in blue italic text and the other can be bold green text. StyleSheet can be applied to
the text field, if it contains HTML text.
■■ Common tasks for working with text
●● Opening the Actions panel and copying the code listing into the Script pane
Figure 10.1: Steps for manipulating a text field object without creating the object openly
¾¾ Example 2: This type defines a class in a code listing, which can be used as the document class for the SWF.
Refer to Figure 10.2. Here, a TextField instance is created by the example code, so it need not be created
separately.
Figure 10.2: Steps in defining a class in a code listing, which can be used as the document class for the SWF
Adobe Flex Builder and Flash authoring tools provide many options for displaying text that include text tools or
text-related components. However, the primary way to display text programmatically is through a TextField. The
TextField values include text strings or variables.
Strings help in working with many objects, such as TextField, StaticText, XML, ContextMenu, and
FileReference objects. Methods of the String class allow working with text strings.
By assigning a string to the flash.text.TextField.text property, dynamic text can be defined. A string can
be directly assigned to the flash.text.TextField.text property. Refer to the following code:
myTextField.text = “Hello Friend”;
Variables are the primary information storage of ActionScript that help to retrieve all the information. A value from
a variable defined in the script can also be assigned to a text property. The given example demonstrates how a
variable can be assigned to a text property:
package
import flash.display.Sprite;
import flash.text.*;
addChild(myTextBox);
myTextBox.text = myText;
A value from a remote variable can also be assigned to a text property. For loading text values from remote sources,
any one of the following three options can be used:
¾¾ flash.net.URLLoader and flash.net.URLRequest classes: This helps load variables for the text from a
local or remote location.
¾¾ FlashVars attribute: This contains values for text variables and is embedded in the HTML page hosting the
SWF file.
¾¾ flash.net.SharedObject class: This class manages the storage of values.
■■ Using HTML in TextFields
By using the flash.text.TextField class that has an htmlText property, the text string containing HTML tags
for formatting the content can be identified.
For example, for Flash Player, to display the text as HTML, the string value can be assigned to the htmlText
property, as given in the following example:
var myText:String = “<p>This is <b>some</b> content to <i>render</i> as
<u>HTML</u> text.</p>”;
myTextBox.htmlText = myText;
In the given example, text “This is some content to render as HTML text” is formatted in HTML and assigned to a
string variable. This string is then assigned to a text field to be displayed as its text value is formatted with HTML.
■■ Using images in TextFields
Another advantage of displaying content as HTML text is using images in the text fields. Any local or remote image
can be accessed by using the img tag and allowing it to appear within the associated text field.
The following example displays how to create a text field named ‘myTextBox’ and include a JPG image of an ear,
stored in the same directory as the SWF file:
package
import flash.display.Sprite;
import flash.text.*;
myTextBox.width = 200;
myTextBox.height = 200;
myTextBox.multiline = true;
myTextBox.wordWrap = true;
myTextBox.border = true;
addChild(myTextBox);
myTextBox.htmlText = myText;
The following scroll-related properties of the flash.text.TextField class can be used to manage vertically (V)
or horizontally (H) lengthy content. These properties help to respond to events, such as clicking or pressing:
¾¾ TextField.scrollV
¾¾ TextField.scrollH
¾¾ maxScrollV
¾¾ maxScrollH
The following example displays how a text field can be created with a set size containing more text so that it can be
displayed at one time. Here, the text scrolls vertically as the user clicks the TextField.
package
import flash.display.Sprite;
import flash.text.*;
import flash.events.MouseEvent;
{
private var myTextBox:TextField = new TextField();
private var myText:String = “Hello friend and welcome to the party. It’s really nice to
see you. Come and take your seat. Hope you will enjoy the evening. I have arranged some
fun games. Don’t forget to eat the cake and whole lot of snacks.”
myTextBox.text = myText;
myTextBox.width = 200;
myTextBox.height = 50;
myTextBox.multiline = true;
myTextBox.wordWrap = true;
myTextBox.background = true;
myTextBox.border = true;
format.font = “Verdana”;
format.color = 0xFF0000;
format.size = 10;
myTextBox.defaultTextFormat = format;
addChild(myTextBox);
myTextBox.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownScroll);
myTextBox.scrollV++;
By selecting dynamic or input text, the text selection properties and methods of the TextField class programmatically
selects dynamic or input text. Even if the content is unknown, it uses the index positions to set the range of text to
manipulate.
On choosing the selectable option on a static Textfield in the Flash authoring tool, a regular dynamic Textfield
can be exported and placed on the display list.
By using the setSelection() method, the text can be selected programmatically in a text field. By default, the
flash.text.TextField.selectable property is set to true. For example, when the user clicks the text field, a
specific text can be set within a text field which is to be selected. Refer to the following example:
var myTextField:TextField = new TextField();
myTextField.text = “No matter where you click this text field the TEXT IN
myTextField.autoSize = TextFieldAutoSize.LEFT;
addChild(myTextField);
addEventListener(MouseEvent.CLICK, selectText);
function selectText(event:MouseEvent):void
myTextField.setSelection(49, 65);
The technique for specifying certain actions that should be performed in response to particular events is known as
event handling. This system allows programmers to respond to user input and system events in a convenient way.
On selecting a text within a Textfield, the text is initially displayed, an event handler function has to be created
called as the Textfield, and it is then added to the display list.
In ActionScript 3.0, an event object represents each event that belongs to an instance of the Event class or one
of its sub-classes. An event object contains methods that assist manipulation of the event object and also stores
information about a specific event.
For detailed step-by-step procedure, refer to demo Working with Text Dynamic from:
eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Working with Text>>
Selecting and manipulating text
However, the properties of the TextField class, selectionBeginIndex and selectionEndIndex, cannot be
set programmatically, as they are ‘read-only’. However, these properties can be used by the user to capture text that is
selected. Moreover, the caretIndex property can be used by input text fields. The following example shows how the
code traces the index values of user-selected text:
myTextField.text = “Please select the TEXT IN ALL CAPS to see the index values for the
first and last letters.”;
myTextField.autoSize = TextFieldAutoSize.LEFT;
addChild(myTextField);
addEventListener(MouseEvent.MOUSE_UP, selectText);
function selectText(event:MouseEvent):void
}
By default, the property of a text field’s type is set to dynamic. However, user input can be collected and the
value can be saved for use in other parts of the application, if the type property is set to input using the
TextFieldType class.
Input text fields are useful for forms and any application that wants the user to define a text value for use, elsewhere
in the program.
In the given example, the code creates myTextBox, which is an input text field. The textInput event gets triggered
as soon as the user enters text in the field. An event handler, textInputCapture, assigns it as a variable and
captures the string of text entered. The new text created is basically another text field called myOutputBox, which
is displayed by Flash Player.
package
import flash.display.Sprite;
import flash.display.Stage;
import flash.text.*;
import flash.events.*;
private v
captureText();
myTextBox.type = TextFieldType.INPUT;
myTextBox.background = true;
addChild(myTextBox);
myTextBox.text = myText;
myTextBox.addEventListener(TextEvent.TEXT_INPUT, textInputCapture);}
createOutputBox(str);
myOutputBox.x = 200;
addChild(myOutputBox);
myOutputBox.text = str;
}
When the user enters text, the displayAsPassword property keeps the text hidden and displays the same as a series
of asterisks.
The Cut and Copy commands and other keyboard shortcuts do not function when the displayAsPassword is set to
true. This property can be assigned for the background and color as given in the following example:
myTextBox.type = TextFieldType.INPUT;
myTextBox.background = true;
myTextBox.displayAsPassword = true;
addChild(myTextBox);
Since the restrict property is complicated, the user needs to specify the characters that are allowed in an input text
field. Only specific letters, numbers, and characters can be allowed.
The following code allows the user to enter only uppercase letters (and not numbers or special characters) in the text
field:
myTextBox.restrict = “A-Z”;
For detailed step-by-step procedure, refer to demo Working with Text Input from:
eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Working with Text>> Restricting
text input
Text fields are either plain text or HTML – formatted text. The text property of the instance is stored in plain text and
the HTML text is stored in the htmlText property.
To define text styles and apply them to many different text fields, the CSS style declarations can be used, which can
be created in application code loaded at run time from an external CSS file.
The flash.text.StyleSheet class handles CSS styles and the StyleSheet class recognizes a limited set of
CSS properties. Following example shows how CSS can be created in code and applied by using a StyleSheet
object to HTML text:
var style:StyleSheet = new StyleSheet();
styleObj.fontSize = “bold”;
styleObj.color = “#FF0000”;
style.setStyle(“.darkRed”, styleObj);
tf.styleSheet = style;
addChild(tf);
As seen in the example, on creating a StyleSheet object, a simple object is created to hold a set of style declaration
properties. After this, the StyleSheet.setStyle() method is called to add the new style to the style sheet with
the name “.darkred”. By assigning the StyleSheet object to the text field object’s StyleSheet property,
the Style sheet formatting is applied. Next, the Style sheet needs to be applied to a text field object before the
htmlText property is set to enable the CSS styles to take effect. If an input text field is assigned a style sheet, the
text shows the style sheet properties but the user is not allowed to enter new text into it.
The following ActionScript APIs on a text field with an assigned Style sheet cannot be used:
¾¾ The TextField.replaceText() method
¾¾ The TextField.replaceSelectedText() method
¾¾ The TextField.defaultTextFormat property
¾¾ The TextField.setTextFormat() method
If a style sheet is assigned to a text field, and the TextField.styleSheet property is set to null, then the tags and
attributes will be added to the contents of TextField.text and TextField.htmlText properties to incorporate
the formatting from the previously assigned style sheet.
The original htmlText property can be preserved by saving it in a variable before setting the style sheet to null.
■■ Loading an external CSS file
Loading CSS information from an external file at run time is more powerful. The visual style of text in the application
can be changed without changing ActionScript 3.0 source code. This can be done after the application has been
deployed and without redeploying the applications SWF file.
A string that contains CSS data into style declarations in the StyleSheet object is converted by the StyleSheet.
parseCSS() method. The following example displays how to load the content of the CSS file with the name
example.css:
p {
font-size: 14;
h1 {
font-size: 20;
font-weight: bold;
.bluetext {
color: #0000CC;
The content of the CSS file with the name example.css is loaded in this way.
Following is the ActionScript code for a class that loads the example.css file and applies the styles to TextField
content:
package
import flash.display.Sprite;
import flash.events.Event;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.text.StyleSheet;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
var loader:URLLoader;
var field:TextField;
field.width = 300;
field.autoSize = TextFieldAutoSize.LEFT;
field.wordWrap = true;
addChild(field);
loader.addEventListener(Event.COMPLETE, onCSSFileLoaded);
loader.load(req);
field.styleSheet = sheet;
field.htmlText = exampleText;
The onCSSFileLoaded() method executes when the CSS data is loaded and calls the StyleSheet.parseCSS()
method to transfer the style declarations to the StyleSheet object.
■■ Applying formatting
The display of a text can be formatted programmatically by using any one of these properties such as TextField.
thickness, TextField.textColor, and TextField.textHeight. These properties can be set directly on
the text field instance.
Another way of formatting text is by using the htmlText property and the supported HTML tags, such as b (for
bold), i (for Italic), and u (for underline).
For consistency and control on the appearance of text throughout an application, use the TextFormat and
StyleSheet objects. Use the TextFormat object to apply on text fields containing plain text, and StyleSheet
objects to apply on text fields containing the htmlText property.
The TextFormat is used to set and apply a number of different text display properties to the entire contents of a
TextField object or to a range of text.
In the following example, one of the TextFormat object applies to an entire TextField object. Another
TextFormat object applies to a range of text within that TextField object. The text that is already displayed in
the text field is affected by the TextField.setTextFormat() method.
Thus, the application needs to call the TextField.setTextFormat() method again to reapply the formatting
if the content in the TextField changes. The TextField object’s default TextFormat property can be set to
specify the format to be used for user-entered text.
Notice the following example which shows how to assign text formats:
var tf:TextField = new TextField();
format1.color = 0xFF0000;
format2.font = “Courier”;
tf.setTextFormat(format1);
var startRange:uint = 6;
tf.setTextFormat(format2, startRange);
addChild(tf);
In the following example, the TextField.setTextFormat() is used on a range of characters to change overall
appearance of a portion of content of myTextField, on clicking the text field.
var myTextField:TextField = new TextField();
myTextField.text = “No matter where you click this text field the TEXT IN
myTextField.autoSize = TextFieldAutoSize.LEFT;
addChild(myTextField);
myformat.color = 0xFF0000;
myformat.size = 18;
myformat.underline = true;
function changeText(event:MouseEvent):void
}
10.1.6 Advanced Text Rendering
A variety of classes in the flash.text package are provided by ActionScript 3.0 that helps to control the properties of
displayed text. This includes anti-aliasing settings, embedded fonts, alpha channel control, and other specific settings.
■■ Embedding a font in Flash
The Flash authoring tool helps to embed fonts like TrueType fonts and Type 1 Postscript fonts. The following are the
ways to embed fonts in a Flash application:
¾¾ Setting the font and style properties of a TextField on the Stage and clicking the Embed Fonts check box
¾¾ Creating and referencing a font symbol
¾¾ Creating and using a run-time shared library containing embedded font symbols
■■ Controlling sharpness, thickness, and anti-aliasing
Flash Player determines the settings for text display controls like thickness, sharpness, and anti-aliasing as text
resizes, changes color, or is displayed on various backgrounds by default.
An important feature of Flash Player is to maintain control over the settings of very small or very large text,
or text on a variety of unique backgrounds. By using the flash.text.TextRenderer class and its associated
classes, like the CSMSettings class, the Flash Player settings can be overridden and these classes help give
total control over the rendering quality of embedded text.
The following example displays how to apply custom Continuous Stroke Modulation (CSM) properties and formatting
to displayed text, using an embedded font called myFont.
var format:TextFormat = new TextFormat();
format.color = 0x336699;
format.size = 48;
format.font = “myFont”;
myText.embedFonts = true;
myText.autoSize = TextFieldAutoSize.LEFT;
myText.antiAliasType = AntiAliasType.ADVANCED;
myText.defaultTextFormat = format;
myText.selectable = false;
myText.mouseEnabled = true;
myText.addEventListener(MouseEvent.CLICK, clickHandler);
function clickHandler(event:Event):void
TextRenderer.setAdvancedAntiAliasingTable(“myFont”, FontStyle.ITALIC,
TextColorType.DARK_COLOR, myAliasTable);
}
10.1.7 Working with Static Text
Static text can be created within the Flash authoring tool. It is useful only if the static text is short and does not intend
to change. It is similar to a graphic element drawn on the Stage like a square or a circle in the Flash authoring tool. It
can be programmatically instantiated by using the ActionScript. However, the ability to read the property values of static
text using the flash.text.StaticText class is supported by ActionScript 3.0. Moreover, to read the values out of the
static text, the flash.text.TextSnapshot class can be used.
To interact with a static text instance placed on the Stage, use the flash.text.StaticText class in the Actions
panel of the Flash authoring tool. It is also possible to work in ActionScript files that interact with an SWF file
containing static text, but it cannot be instantiated programmatically. It can be created in Flash CS3 authoring tool.
The items can be repeated in the display list and assigned a variable to create a reference to an existing static
TextField in ActionScript 3.0 as given in the following example:
for (var i = 0; i < this.numChildren; i++) {
} }
Properties of static TextField can be used in ActionScript 3.0 on having a reference to a static text field.
The following code is attached to a frame and assumes a variable named ‘myFieldLabel’ that is assigned to a
static text reference.
As given in the following example, a dynamic text field named myField is positioned relative to the x and y values
of ‘myFieldLabel’ and displays the value of ‘myFieldLabel’ again:
var myField:TextField = new TextField();
addChild(myField);
myField.x = myFieldLabel.x;
myField.autoSize = TextFieldAutoSize.LEFT;
To retrieve values or select parts of a static text instance, apply methods to that instance. For this use the flash.text.
TextSnapshot class to work with the textSnapshot property of a flash.display.DisplayObjectContainer.
In the following example, an existing static field is placed containing the text “TextSnapshot Example” on the
Stage. Add the following ActionScript to Frame 1 of the Timeline:
var mySnap:TextSnapshot = this.getTextSnapshot();
mySnap.setSelected(0, 4, true);
mySnap.setSelected(1, 2, false);
trace(myText);
In case, the text has to be used as a value in another part of an application, then use the TextSnapshot class for
getting the text out of static text fields in a loaded SWF.
For detailed step-by-step procedure, refer to demo Working with Text Static from:
eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Working with Text>> Using
the TextSnapshot Class
To load external video, load the file from a standard Web server for progressive download playback, or work with
streaming video such as Adobe’s Macromedia Flash Media Server. The following are the video-related tasks:
¾¾ Displaying and controlling video on the screen
¾¾ Loading external FLV files
¾¾ Handling metadata and cue point information in a video file
¾¾ Capturing and displaying video input from a user’s camera
The FLV file format contains encoded audio and video data for delivery when the Flash Player is used. FLV files are
created by importing video into the flash authoring tool and then exporting it as an FLV file. Also, by using the FLV
Export plug-in, FLV files can be exported from supported video-editing applications.
External FLV files provide some capabilities that are not available while using imported video, such as the following:
¾¾ Without slowing down playback, longer video clips can be used in Flash documents. By using cached memory
external FLV files play, in other words large files are stored in small pieces and accessed with less memory than
embedded video files.
¾¾ The Flash document has different frame rate than an external FLV file in which it plays. For example, the Flash
document frame rate can be set to 40 frames per second (fps) and the video frame rate to 31 fps. This setting
gives a better control of the video and ensures smooth video playback by allowing playing FLV files at different
frame rates without the need to alter existing Flash content.
¾¾ While the video is loading, the Flash document playback does not have to be interrupted with the external FLV
files as it can also be performed independently on the Flash document.
¾¾ With external FLV files, captioning video content is easier as the video’s metadata can be accessed using event
handlers.
The file extension has to be registered as well as Multipurpose Internet Mail Extensions (MIME) type with the
Web server. Even the Web server documentation has to be checked while loading FLV files from a Web server.
The MIME type for FLV files is video/x-flv.
The Video class in the flash.media package inherits from the flash.display.DisplayObject class. Hence, all
the display objects, functionality filters, and matrix transformation can be applied to the video instances.
This is the first step that allows playing of streaming FLV files from an HTTP address or a local drive by passing the
value null to the connect() method if not using a server such as Adobe’s Flash Media Server 2 or Adobe Flex.
var nc:NetConnection = new NetConnection();
nc.connect(null);
This is the second step that takes a NetConnection object as a parameter and specifies which FLV file has to be
loaded and then connects a NetStream object to the specified NetConnection instance and loads an FLV named
video.flv in the same directory as the SWF file.
var ns:NetStream = new NetStream(nc); ns.addEventListener(AsyncErrorEvent.ASYNC_ERROR,
asyncErrorHandler);
ns.play(“video.flv”);
function asyncErrorHandler(event:AsyncErrorEvent):void
// ignore error }
■■ Creating a new Video object and attaching the previously created NetStream object using
the Video class attachNetStream() method
This is the third step. As given in the following example, the video object can be added to the display list using the
addChild() method. Refer to the following example:
var vid:Video = new Video();
vid.attachNetStream(ns);
addChild(vid);
Flash Player will attempt to load the video.flv video file in the same directory as the SWF file, after entering the previous
code or by specifying the path in the volume internal/external.
When specific cue points are reached or specific metadata is received by the player, then actions can be triggered in the
application. Thus, the onCuePoint and onMetaData event handlers can be used to trigger such actions. Callback
methods for these handlers must be written or else the Flash Player may throw errors. In the following example, the code
plays an FLV file named video.flv in the same folder as in the SWF document:
var nc:NetConnection = new NetConnection();
nc.connect(null);
ns.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
ns.play(“video.flv”);
function asyncErrorHandler(event:AsyncErrorEvent):void{trace(event.text); }
vid.attachNetStream(ns);
addChild(vid);
A local FLV file named video.flv is loaded by the previous code and also listens for the asyncError (AsyncErrorEvent.
ASYNC_ERROR) to be dispatched. When an exception is thrown from native asynchronous code, then this event is
dispatched. Here, it is dispatched when an FLV contains metadata or cue point information, and the appropriate listeners
have not been defined. In case the video file’s metadata cue point information is not required, then the previous code
handles the asyncError event and ignores the error.
If asyncErrorHandler is ignored while loading an external video.flv it will show the error in metadata and
cue point.
If the FLV had metadata and several cue points, then the following information would be traced:
¾¾ Error #2095: flash.net.NetStream was unable to invoke callback onMetaData.
¾¾ Error #2095: flash.net.NetStream was unable to invoke callback onCuePoint.
¾¾ Error #2095: flash.net.NetStream was unable to invoke callback onCuePoint.
¾¾ Error #2095: flash.net.NetStream was unable to invoke callback onCuePoint.
Click here to know more about the Callback methods for onCuePoint and onMetaData.
Sound effect can be added to an audio feedback of an application user interface, a video game, and also for making a
program that analyzes MP3 files loaded over the Internet, with sound at the core of the application.
URLRequest object is accepted by the Sound() constructor as its first parameter and a new Sound object starts
loading the specified sound resource automatically, when a value for the first parameter is supplied.
While loading external sound files, different events during the sound loading process dispatch different objects.
The application tracks the loading progress and ensures that the sound is loaded completely before playing. Refer to
Table 10.1.
Event Description
open (Event.OPEN) It is dispatched before the sound loading operation begins.
progress (ProgressEvent.PROGRESS) It is dispatched when data is received from the file or stream,
periodically during the sound loading process.
id3 (Event.ID3) It is dispatched when ID3 data is available for an MP3 sound.
complete (Event.COMPLETE) It is dispatched when all of the sound resource’s data has been
loaded.
ioError (IOErrorEvent.IO_ERROR) It is dispatched when a sound file cannot be located or when the
loading process is interrupted before all sound data can be received.
Table 10.1: Different Events dispatched by sound objects
The following code displays how to play a sound after it has finished loading:
import flash.events.Event;
import flash.media.Sound;
import flash.net.URLRequest;
s.addEventListener(Event.COMPLETE, onSoundLoaded);
s.load(req);
function onSoundLoaded(event:Event):void
localSound.play();
}
First, a new sound object is created by the code without giving it an initial value for the URLRequest parameter. Then,
it listens for the Event.COMPLETE event from the sound object that is responsible for causing the onSoundLoaded()
method to execute on loading all the sound data.
Lastly, the Sound.load() method calls with a new URLRequest value for the sound file. When the sound loading is
complete, the onSoundLoaded() method executes. The event object is a reference to the sound object and on calling
the play() method, the sound starts the sound playback.
The volume values set in the SoundChannel object of the SoundMixer class, and the function of the amplitude of the
sound wave is the actual playback volume. To specify a different volume level for each of the left and right channels during
playback, the pan property of a SoundChannel object can be used whose value ranges from -1 to 1. -1 represents the
left channel that plays at top volume and the right channel remains silent. 1 represents the right channel that plays at top
volume while the left channel remains silent. The value 0 represents both channels that play at a balanced volume level.
A SoundTransform object with a volume value of 0.6 and a pan value of -1 (top left channel volume and no right
channel volume) is created in the following example:
var snd:Sound = new Sound(new URLRequest(“mySound.mp3”));
The volume and panning can be altered while a sound is playing by setting the pan or volume properties of a
SoundTransform object and then, applying that object as the SoundTransform property of a SoundChannel object.
The global volume and pan values for all sounds can also be set by using the SoundTransform property of the
SoundMixer class, as shown in the following example:
SoundMixer.soundTransform = new SoundTransform(1, -1);
In the following example, the panning of the sound is alternate from left channel to the right channel and back while the
sound plays:
import flash.events.Event;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundMixer;
import flash.net.URLRequest;
snd.load(req);
var panCounter:Number = 0;
var trans:SoundTransform;
addEventListener(Event.ENTER_FRAME, onEnterFrame)
function onEnterFrame(event:Event):void
trans.pan = Math.sin(panCounter);
panCounter += 0.05;
function onPlaybackComplete(event:Event):void
removeEventListener(Event.ENTER_FRAME, onEnterFrame);
By loading a sound file and later creating a new SoundTransform object with volume set to 1 (full volume) and pan
set to 0 (evenly balanced between left and right) the code can be started. Then, the snd.play()method is called by
passing the SoundTransform object as a parameter.
The onEnterFrame()method is repeatedly executed while the sound plays. The Math.sin() function is used to
generate a value between -1 and 1. This range corresponds to the acceptable values of SoundTransform.pan property.
A new value is set to the SoundTransform object’s pan property and then set to use the altered SoundTransform
object. The filename mySound.mp3 is replaced with the name of a local MP3 file to run the example. Thus, it enables to
hear the left channel volume that gets louder and at the same time the right channel volume gets softer, and vice versa.
The same effect can be achieved by setting the SoundTransform property of the SoundMixer class, but this can
affect the panning of all sounds that is currently playing.
A ByteArray object is returned by the sound data that contains 512 bytes of data and each byte contains a floating
point value between -1 and 1 that represent the amplitude of the points in the sound waveform being played. The values
are divided in two groups, each of 256 bytes. The first group is delivered for the left stereo channel and the second group
for the right stereo channel.
Fast Fourier Transform (FFT) is used to convert the waveform data into frequency spectrum data. The resulting frequency
spectrum values range from 0 to roughly 1.414 (the square root of 2).
If the FFTMode parameter is set to true, then the SoundMixer.computeSpectrum() method returns frequency
spectrum data and shows amplitude that is arranged by sound frequency from the lowest to highest frequency.
The following figure compares the data returned from the computeSpectrum() method irrespective of setting it to true
or false. A loud bass sound in the left channel and a drum hit sound in the right channel are used. Refer to Figure 10.3.
Data that has been resampled at a lower bit rate can be returned by the computeSpectrum() method resulting in
smoother waveform data or frequency data at the expense of detail. The rate at which the computeSpectrum()
method data is sampled is controlled by the stretchFactor parameter. This rate is halved if the stretchFactor
parameter is set to 0. If the sound data is sampled at a rate of 44.1 kHz, then it gets halved to 22.05 kHz and a value of 2
specifies a rate of 11.025 kHz. When a higher stretchFactor value is used, then the computeSpectrum() method
still returns 256 bytes per stereo channel.
There are a few limitations of the SoundMixer.computeSpectrum() method which are as follows:
¾¾ The SoundMixer.computeSpectrum() method will not return data from those sources, because the sound
data from a microphone or from Real Time Messaging Protocol (RTMP) streams do not pass through the global
SoundMixer object.
¾¾ Security restrictions will cause the SoundMixer.computeSpectrum() method to throw an error, if one or
more of the sounds being played come from sources outside the current content sandbox.
For detailed step-by-step procedure, refer to demo Working with Text Dynamic from:
eResources 4 Me>> My Varsity>> Module Name>> Show Me How Web Animation and Interactivity>> Show Me How>>
Working with Sound>> Accessing raw sound data
10.4 Summary
In this session, Working with Built-in Classes (Text, Video, and Sound), you learned that:
¾¾ The three types of text are: Dynamic text, Input text, and Static text.
¾¾ In AS 3.0, there are different built-in classes to perform text handling tasks.
¾¾ An instance of a built-in TextField class is used to display text on the screen in Adobe Flash Player. The
properties defining the appearance of the text, such as size, color, and weight are present in the TextFormat
object or StyleSheet object.
¾¾ Scroll-related properties of the flash.text.TextField class can be used to manage vertically (V) or
horizontally (H) lengthy content.
¾¾ When a user selects a text from a complete string or a paragraph, the selectionBeginIndex and
selectionEndIndex is captured programmatically.
¾¾ The flash.text.StyleSheet class handles CSS styles and the StyleSheet class recognizes a limited set
of CSS properties. It also has a restrict property and a displayAsPassword property that help users to
control text input.
¾¾ To interact with a static text instance placed on the Stage, use the flash.text.StaticText class in the
Actions panel of the Flash authoring tool.
¾¾ The flash.text.TextField class helps to identify the text string for formatting the content.
¾¾ The user input can be collected and the value can be saved for use in other parts of an application, if the type
property to input is set using the TextFieldType class.
¾¾ To read the values out of the static text, the flash.text.TextSnapshot class can be used.
¾¾ To interact with a static text instance placed on the Stage, use the flash.text.StaticText class.
¾¾ The TextSnapshot class is useful for getting the text out of static text fields in a loaded SWF.
¾¾ Working with video in ActionScript involves a combination of classes such as Video class, NetStream class,
and Camera class.
¾¾ By using Flash Player, the FLV file format contains encoded audio and video data for delivery.
¾¾ NetConnection and NetStream classes are used for loading.
¾¾ The onCuePoint and onMetaData event handlers to trigger actions.
¾¾ Sound effect can be added to an audio feedback of an application user interface, a video game, and also to
make a program that analyzes MP3 files loaded over the Internet.
¾¾ Both the left and the right stereo channels for a sound are controlled by an individual SoundChannel object.
¾¾ The SoundMixer.computeSpectrum() method allows an application to read the raw sound data for the
waveform that is currently being played.
10.5 Exercise
1. Which of these text loads content from the external source?
Input text
Dynamic text
Static text
Output text
Selecting the first keyframe in the Timeline, and open the Actions panel
SoundMixer
3. The SoundMixer.computeSpectrum() method allows an application to read the raw sound data for the waveform
that is currently being played.
True
False
4. Both the left and the right stereo channels for a sound are controlled by an individual ______ object.
computeSpectrum
SoundTransform
SoundChannel
SoundMixer
5. The TextSnapshot class is useful for getting the text out of dynamic text fields in a loaded MP3.
True
False
Session 11
Object-Oriented Programming with ActionScript 3.0
Learning Outcomes
In this session, you will learn to:
¾¾ Understand the Object-Oriented Programming concept
¾¾ Know more about classes and identify them
¾¾ Understand how to define interfaces and implement them in a class
¾¾ Learn about Inheritance and identify them
In 1999, Flash 4 was released that introduced variables, expressions, loops, if statements, and operators. Internally, this
came to be known as ‘ActionScript’ that uses the term ‘actions’ to describe a set of commands.
ActionScript 2.0 was introduced by Flash MX 2004 as a scripting programming language, which was appropriate for the
development of Flash applications. Scripting often saves time than animating and also enables a higher level of flexibility
when editing.
ActionScript 3.0 is a superset of the syntax and semantics of language, which is more widely known as JavaScript.
ActionScript 3.0 is primarily used for the development of Web sites and software targeting the Adobe Flash Player
platform, which is in turn used on Web pages in the form of embedded SWF files.
In addition, ActionScript 3.0 is suitable for use in some database applications and in basic robotics. Moreover, the
Object-Oriented Programming (OOP) support is optional in ActionScript 3.0, and it provides flexibility to programmers to
choose the best approach for complex projects of varying scope.
For example, different music information, such as artist name, track title, or album title along with actions related to that
information, such as ‘play all songs by this artist’ or ‘add track to playlist’ can be grouped into one element. All these items
together form a single item or object, for example, a ‘Music Track’ or an ‘Album’. This combination proves beneficial as
it helps keep a track of a single variable instead of multiple variables that organize these functionalities together and
also structure programs that are more real. Some of the important terms used while working with OOP are as follows:
¾¾ Class: The behavior of objects of a certain type and the definition of the structure is referred to as a class. For
example, a template or a blueprint for objects of that data type.
¾¾ Class hierarchy: This is the structure that specifies the class that inherits functionality from other classes.
¾¾ Attribute: A class element to which a characteristic is assigned in a class definition is called as attribute. These
are used to define the method or property available for code in a program. Private and public are examples
of attributes. The code that is called within the class is called as a private method, and the code that is called
from another class is called as a public method.
¾¾ Constructor method: The constructor method is called when a new instance of an object is created. The
constructor method is like a normal public method except that it shares the same name as the class and it
cannot return a value. It can have none, one, or many parameters.
¾¾ Data type: It is a particular variable that can be stored and has the same properties as a class.
¾¾ Dot operator: This refers to the period sign (.). In ActionScript, this sign refers to a child element of an object
similar to a method or property. For example, in the expression myObject.myProperty, the dot refers to
some value that is an element of the object named myObject.
¾¾ Enumeration: This refers to a set of related constant values that are grouped together as a single class.
¾¾ Inheritance: It implements parent-child relationship, where the child class can inherit the attributes and behavior
of the parent class (Base class).
¾¾ Namespace: This is a custom attribute that allows total control over codes.
11.1.2 Identifying Common OOP Tasks
Following are the common OOP tasks:
¾¾ Defining classes
¾¾ Creating properties, methods, and get and set accessor methods
¾¾ Controlling access to classes, properties, methods, and accessory
¾¾ Creating static properties and methods
¾¾ Creating enumeration-like structures
¾¾ Defining and using interfaces
¾¾ Working with inheritance, including overriding class elements
11.2 Classes
An abstract representation of an object is called a class. It stores information about the types of data that an object can
hold and the behaviors that an object can exhibit. When small scripts are written containing a few objects that interact
with one another, its usefulness is not apparent. As the scope of any program grows, the objects and its number are to
be managed.
The nested function can be invoked anywhere within the containing method. However, access-control
modifiers, such as public and internal cannot be applied to nested functions.
ActionScript 3.0 introduces the package statement that includes the package declaration.
// ActionScript 2.0
class flash.display.BitmapData {}
// ActionScript 3.0
package flash.display
}
In this example, the code creates a class named color that contains only one variable, named ‘visible’.
■■ Class attributes
Class definitions can be modified in ActionScript 3.0 by using any one of the following attributes:
¾¾ dynamic: Here, properties are allowed to be added to instances at run time.
¾¾ final: This cannot be extended by another class.
¾¾ internal: Here, references inside the current package are visible and is the default setting.
¾¾ public: Here, references everywhere are visible.
Except internal, each of these attributes must clearly include the attribute to get the associated behavior. For example,
adding properties to a class instance at run time will not be possible if the dynamic attribute is not included. An attribute
has to be assigned explicitly at the beginning of the class definition, as shown in the following code:
Dynamic class Shape { }
The class body enclosed by curly brackets is used to define the variables, constants, and methods of a class. Refer
to the following example:
Public final class Accessibility
Here, the example shows the declaration for the Accessibility class in the Adobe Flash
Player API.
A namespace inside a class body can also be defined. Notice the following example
carefully:
This example demonstrates how a namespace can be defined within a class body and used as an attribute of a
method in that class.
In ActionScript 3.0, statements can also be allowed along with definitions in a class body when the class definition
is first encountered and the associated class object is created. The following example includes a call to an external
function, hello(), and a trace statement that outputs a confirmation message when the class is defined. Thus,
the statements that are inside a class body, but outside a method definition, are executed exactly once. Refer to the
following example:
Function hello (): String
Trace (“hola”);
Hello ();
Class created
ActionScript 3.0 allows defining a static property and an instance property with the same name in the same class
body. Refer to the following example:
Class Static Test
// in your script
Here, the code declares a static variable named message and an instance variable of the same name.
In the example, the code creates a simple class named PrivateExample with one private variable, and then
attempts to access the private variable from outside the class.
An attempt to access a private property using the dot operator (myExample.privVar) in ActionScript 3.0, results
in a compile-time error if strict mode is used. When the property access operator (myExample[“privVar”]) is
used, the error is reported at run time.
Refer to Table 11.1 that shows the result of attempting to access a private property belonging to a sealed (not
dynamic) class.
However, attempting to access a private variable will not result in a run-time error when classes are declared with
the dynamic attribute. The variable is not visible, hence Flash Player returns the value undefined. If the dot operator
is used in strict mode, then a compile-time error occurs.
The example is the same as the earlier example, except that the PrivateExample class is declared as a dynamic
class. Instead of generating an error when a code, external to a class, attempts to access a private property, the
dynamic classes return the value undefined. Refer to Table 11.2 that shows an error which is generated only when
the dot operator is used to access a private property in strict mode.
Static properties are not inherited by sub-classes, but the properties are part of a sub-class’s scope chain. In other
words, this means that within the body of a sub-class, a static variable or method can be used without referring to
the class in which it was defined.
■■ User-defined namespace attributes
A custom namespace can be created for use as an attribute or as an alternative to the predefined access control
attributes. Only one namespace per definition can be used, and it cannot be used in combination with any of the
access control attributes, such as public, private, protected, and internal.
11.2.3 Variables
Variables can be declared with var or const keyboards. The variables that are declared with the var keyboard can
change their values a number of times while the script is executed. The variables that are declared with the const
keyword are called constants. Values can be assigned to them only once and it results in an error if a new value is
assigned to an initialized constant. There are two types of variables as follows:
■■ Static variables
By using a combination of the static keyword and var or const keywords, static variables can be declared. They
are useful for storing and sharing information that applies to an entire class of objects.
For example, to keep a tally of the number of times a class instance is allowed, a static variable is appropriate as
it can store a maximum number of class instances. A totalCount variable can be created to track the number of
class instantiations and a MAX_NUM constant to store the maximum number of instantiations. The totalCount and
MAX_NUM variables contain values that apply to the class as a whole and not to a particular instance. Refer to the
following example:
class StaticVars
}
The totalCount and MAX_NUM properties can be referred to the code that is external to the StaticVars class
and any of its sub-classes as given in the following code:
trace(StaticVars.totalCount); // output: 0
trace(StaticVars.MAX_NUM); // output: 16
In this example, the totalCount and MAX_NUM variables are static. Thus, static variables cannot be accessed
through an instance of the class as the code returns errors. Refer to the following example:
var myStaticVars:StaticVars = new StaticVars();
trace(myStaticVars.totalCount); // error
trace(myStaticVars.MAX_NUM); // error
The static and const keywords that are declared by the variables must be initialized while declaring the constant,
similar to how the StaticVars class does for MAX_NUM. A value cannot be assigned to MAX_NUM inside the
constructor or an instance method, thereby generating an error since it is not a valid way to initialize a static
constant. Refer to the following example:
// !! Error to initialize static constant this way
class StaticVars2
function initializeStatic():void
UNIQUESORT = 16;
} }
■■ Instance variables
Properties declared with the var and const keywords do not contain the static keyword and are included in
instance variables. Instance variables that are attached to class instances are used to store values specific to an
instance. For example, an Array class with an instance property named length helps to store the number of array
elements of a specific instance of the Array class. The var and const keywords cannot be overridden in a sub-
class.
11.2.4 Methods
Functions that are part of a class definition are called methods. A method is bound to an instance. Once it is created, it
cannot be used for instances other than the one for which it is attached.
By using the function keyword, methods can be defined and function statement can be used as follows:
public function sampleFunction():String {}
A variable can also be used to assign a function expression as shown in the following code:
public var sampleFunction:Function = function () {}
However, in most cases a function statement is used more often instead of a function expression for the following
reasons:
¾¾ Function statements are shorter, to the point, and readable.
¾¾ The override and final keywords are allowed by function statements.
¾¾ A strong bond is created by function statements between the identifier that include the function name and the
code within the method body. The connection between a variable and its function expression can be severed at
any time as the value of a variable can be changed with an assignment statement.
¾¾ Function expression is used to attach a function to the prototype object.
The different types of methods are:
¾¾ Constructor methods
¾¾ Static methods
¾¾ Instance methods
¾¾ get and set Accessor methods
¾¾ Bound methods
Click here to know more about different types of methods in detail.
An enumeration class is declared with the final attribute as the need to extend the class is not required. There exist only
static members in the class. As shown in the following code, the enumeration values can be accessed directly through
the class object:
var pj:PrintJob = new PrintJob();
if(pj.start())
if (pj.orientation == PrintJobOrientation.PORTRAIT)
}}
This example is used to store the set of values comprising landscape and portrait. Only variables of type String,
int, or uint are in the enumeration classes in the Flash Player API.
■■ Advantages of using enumerations instead of literal string or number values
If a string literal value is spelt wrongly, then the compiler does not generate an error as follows:
if (pj.orientation == “portrai”) // no compiler error
Another technique for creating enumerations is by creating a separate class with static properties for the enumeration.
The static properties contain an instance of the class instead of a string or integer value.
In the following example, the code creates an enumeration class for the days of the week:
public final class Day
Many developers use the improved type-checking that the technique provides. In the following example, the code
demonstrates a function that returns a day of the week:
function getDay():Day
var retDay:Day;
switch (date.day)
case 0:
retDay = Day.MONDAY;
break;
case 1:
retDay = Day.TUESDAY;
break;
case 2:
retDay = Day.WEDNESDAY;
break;
case 3:
retDay = Day.THURSDAY;
break;
case 4:
retDay = Day.FRIDAY;
break;
case 5:
retDay = Day.SATURDAY;
break;
case 6:
retDay = Day.SUNDAY;
break;
return retDay;
In this example, the code uses the enumeration type as a type annotation. An integer can be associated with
each day of the week, by enhancing the Day class. A string representation of the day can be returned by providing
a toString() method.
2. Internal attribute is the default attribute for code in a package, and it applies to any property.
True False
11.3 Interfaces
A collection of method declarations that allows unrelated objects to communicate with one another is called an interface.
In the following example, the Flash Player API defines the IEventDispatcher interface containing method declarations
that a class can use to handle event objects. A standard way is established by the IEventDispatcher interface for
objects to pass event objects to one another. Refer to the following example:
public interface IEventDispatcher
useCapture:Boolean=false, priority:int=0,
useWeakReference:Boolean = false):void;
useCapture:Boolean=false):void;
function dispatchEvent(event:Event):Boolean;
function hasEventListener(type:String):Boolean;
function willTrigger(type:String):Boolean; }
The definition of the IEventDispatcher interface is demonstrated in the code. In Flash Player API, the
EventDispatcher class implements the IEventDispatcher interface by defining all of the IEventDispatcher
interface methods and adding method bodies to each of the methods. The following code is an excerpt from the
EventDispatcher class definition:
public class EventDispatcher implements IEventDispatcher
function dispatchEvent(event:Event):Boolean
/* implementation statements */
... }
The IEventDispatcher interface serves as a protocol that EventDispatcher instances use to process event
objects and pass them to other objects that have implemented the IEventDispatcher interface.
11.3.1 Defining an Interface
An interface can contain only methods with no method bodies. By using the interface keyword, an interface can be
defined.
In the following example, the interface IExternalizable is part of the flash.utils package in the Flash Player API
that defines a protocol to serialize an object. In simple terms, it means to convert an object into a format that is suitable
for storage on a device or for transport across a network. Refer to the following example:
public interface IExternalizable
function writeExternal(output:IDataOutput):void;
function readExternal(input:IDataInput):void;
The public access control modifier is declared by the IExternalizable interface. Internal access control specifiers and
public access control specifiers modify the interface definitions. The method declarations inside an interface definition
cannot have any access control specifiers. The interface definitions need to be placed at the top level of a package but
not inside a class definition or inside another interface definition. They can also extend one or more interfaces.
In the following example, the interface IExample extends the IExternalizable interface:
public interface IExample extends IExternalizable
function extra():void;
Implementations must be included in any class that implements the IExample interface not just for the extra() method,
but also for the writeExternal() and readExternal() methods that are inherited from the IExternalizable
interface.
In the following example, IAlpha and IBeta, are the two interfaces that are defined along with a class alpha that
implements both:
interface IAlpha
function foo(str:String):String;}
interface IBeta
function bar():void;
The default parameter values have some flexibility. Function declarations with default parameter values can be
included in an interface definition.
In the following example, the code defines an interface containing a method with a default parameter value of 3:
interface IGamma
The Igamma interface is implemented by the following class definition using a different default parameter value:
class Gamma implements IGamma
}
The rules for implementing an interface are designed in a way ensuring data type compatibility. Identical parameter
names and default parameter values are not required to achieve that objective.
11.4 Inheritance
A code that allows programmers to develop new classes that are based on existing classes is called as inheritance.
■■ Advantages of inheritance
¾¾ The code can be reused from a Base class yet it leaves the existing code unmodified.
¾¾ No change is required in the way the classes interact with the Base class.
¾¾ The existing class is thoroughly tested and by using inheritance, the additional properties or methods can be
extended.
¾¾ By using the extend keyword, a class inheriting from another class can be indicated.
¾¾ Inheritance allows taking advantage of polymorphism in the code.
¾¾ Inheritance enables polymorphism by allowing sub-classes to inherit and redefine or override methods from the
Base class.
■■ Polymorphism
The ability to use a single method name for a method that behaves differently when applied to different data types
is termed as polymorphism.
For example, a Base class named Shape with two sub-classes named Circle and Square. The Shape class
defines a method named area(). This returns the area of the shape. The area() method can be called on objects
of type Circle and Square and delivers correct calculations if polymorphism is implemented. The following
example shows how the area() method is redefined by the Circle and Square classes:
class Shape
return NaN;
}}
} }
trace(sq.area()); // output:1
Since a data type is defined by each class, a special relationship is created between a Base class and a class that
extends it. All the properties of Base class are present in a sub-class. In simple terms, an instance of a sub-class
can always be substituted for an instance of the Base class as shown in the following example:
function draw(shapeToDraw:Shape) {}
draw(myCircle);
In this example, it is legal to pass an argument of type Circle because Circle extends Shape if a method defines
a parameter of type Shape.
In the following example, the Event class shows how some of the properties and methods are inherited by sub-classes
and how any sub-class can access these properties:
public class Event
Some unique properties are required by some types of events that are not available in the Event class. By using
sub-classes of the Event class, these events are defined enabling new properties to be added to the properties as
demonstrated in the following example:
public class MouseEvent extends Event
Here, the MouseEvent class shows the definition of properties that exist on the sub-class but not on the Base class.
■■ Access control specifiers and inheritance
This property is visible in code anywhere, if a property is declared with the public keyword. This means that the
public keyword places no restrictions on property inheritance.
The property is visible only in the class that defines it, if declared with private keyword. This means that it is not
inherited by any sub-classes. Thus, the property is visible not only within the class that defines it, but also to all sub-
classes when indicated by the protected keyword. The internal keyword can be used or any access control
specifier need not be used in order to limit the visibility of a property to the package in which it is defined. A property
marked as internal will be inherited only by a sub-class that resides in the same package.
The following example shows how each of the access control specifiers affect inheritance across package boundaries:
// Base.as in a folder named foo
package foo
package bar
import foo.Base;
public class Extender extends Base
return str;
import flash.display.MovieClip;
import bar.Extender;
Here, the code defines a main application class named AccessControl and two other classes named Base
and Extender. The str variable’s access control specifier needs to be changed to private, protected, or
internal to see how the other access control specifiers affect during compilation and execution of the preceding
example. The following line from the AccessControl class can be deleted as follows:
trace(myExt.testString); // error if str is not public
Properties cannot be overridden that are declared with the var or const keywords, but they can be inherited. Only
methods can be overridden. A similar functionality can be created by get and set methods for the instance variable
and overriding the methods.
The method definition in the sub-class must use the override keyword and match the superclass version of the
method to override an instance method that meets the criteria as shown in the following ways:
¾¾ There should be a same level of access control as the Base class method in the override method.
¾¾ Those methods that are marked internal should have the same level of access control as methods without
access control specifier.
¾¾ The same number of parameters as the Base class method must be present in the override method.
¾¾ The same data annotations as the parameters in the Base class method must be present in the override method
parameters.
¾¾ The same return type as the Base class method must be present in the override method.
As long as the number of parameters and the data type of each parameter matches, it is not necessary that the names
of the parameters in the override method has to match the names of the parameters in the Base class.
■■ Super statement
While overriding a method, the behavior of the superclass method can be added instead of completely replacing
the behavior. This can be done using a mechanism that allows a method in a sub-class to call the superclass
version. This is provided by the super statement that contains a method named thanks() and a sub-class of the
Base class named Extender that overrides the thanks() method. The super statement is used by the Extender.
thanks() method to call Base.thanks(). Refer to the following example:
package
import flash.display.MovieClip;
class Base {
return “Mahalo”;
Getters and setters can be overridden but not variables defined in a superclass. As shown in the following example,
the code overrides a getter named currentLabel defined in the MovieClip class in the Flash Player API:
package
import flash.display.MovieClip;
trace(currentLabel)
str += super.currentLabel;
return str;
The output of the trace()statement in the OverrideExample class constructor is Override: null, which
shows that the example was able to override the inherited currentLabel property.
For example, the following code defines a Base class named Base and a sub-class that extends Base named Extender.
A static variable named test is defined in the Base class. The code as written in the following excerpt does not compile
in strict mode and generates a run-time error in the standard mode.
package
import flash.display.MovieClip;
trace(myExt.test); // error
class Base {
The only way to access the static variable test is through the class object, as demonstrated in the following
code:
Base.test;
An instance property can be defined by using the same name as a static property in the same class or in a sub-class.
As given in the example, the Base class could have an instance property named test. This is complied and executed
by the following code as the instance property is inherited by the Extender class. Also, if the definition test instance
variable is moved, but not copied to the Extender class, then the code would compile and execute. Refer to the
following example:
package
import flash.display.MovieClip;
class Base
In the following example, the classes are modified which are defined in the previous example to show that the static
test variable defined in the Base class is in scope of the Extender class. The static test variable can be accessed
by the Extender class without prefixing the variable with the name of the class that defines test. Refer to the following
example:
package
import flash.display.MovieClip;
class Base {
The instance property has higher precedence in the scope chain, if an instance property is defined that uses the same
name as a static property in the same class or a superclass. The static property is said to be shadowed by the instance
property. In simple terms it means that the value of the static property is used rather than the value of the instance
property as shown in the following example:
package
import flash.display.MovieClip;
class Base
As shown in this example, the code demonstrates that if the Extender class defines an instance variable named test,
the trace() statement uses the value of the instance variable instead of the value of the static variable.
eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How>> Inheritance>> Static properties
and the scope chain.
11.5 Summary
In this session, Object-Oriented Programming with ActionScript 3.0, you learned that:
¾¾ The elements of ActionScript that help to support Object-Oriented Programming (OOP).
¾¾ An abstract representation of an object is called a class. The syntax for a class definition is called for the class
keyword followed by the class name.
¾¾ Anything that can be a member of a class is termed as property, and it also includes variables.
¾¾ Variables can be declared with var or const keyboards.
¾¾ By using a combination of the static keyword and var or const keywords, static variables can be declared
which on attaching to a class and not an instance of a class, are used for storing and sharing information that
applies to an entire class of objects.
¾¾ A totalCount variable can be created to track the number of class instantiations and a MAX_NUM constant to
store the maximum number of instantiations.
¾¾ Instance variables that are attached to class instances are used to store values specific to an instance.
¾¾ Functions that are part of a class definition are called methods. A method is bound to an instance once instance
of the class is created and it cannot be used other than the instance to which it is attached.
¾¾ Constructor methods are also called as constructors. These functions share the same name as the class in
which they are defined.
¾¾ Static methods are also called class methods that are declared with the static keyword. They are useful for
encapsulating functionality that affects something and not the state of an individual instance.
¾¾ Methods that are declared without the static keyword are called instance methods. Instance methods attached
to instances of a class are useful for implementing functionality affecting individual instances of a class.
¾¾ get and set accessor methods allows follow of the programming principles and provides a user-friendly
programming interface for the classes created.
¾¾ To summarize a small set of values, create custom data types called as enumerations. A specific enumeration
facility is not supported by ActionScript 3.0, but enumerations using classes and static constants can be created.
¾¾ Embedded asset classes are special classes used in ActionScript 3.0 that represents assets. For example,
image, font, or sound being included in an SWF file at the time of compiling.
¾¾ A collection of method declarations that allows unrelated objects to communicate with one another is called an
interface.
¾¾ A code that allows programmers to develop new classes that are based on existing classes is called as
inheritance. The existing classes are called base classes or superclasses, and the new classes are known as
sub-classes.
¾¾ The ability to use a single method name for a method that behaves differently when applied to different data
types is termed as polymorphism.
¾¾ Whether an instance property is defined with the function, var, or const keywords, inherits all sub-classes
unless not declared with the private attribute in the Base class.
¾¾ Override a method means to redefine the behavior of an inherited method.
¾¾ While overriding a method, the behavior of the superclass method can be added instead of completely
replacing the behavior. This can be done using a mechanism that allows a method in a sub-class to call the
superclass version of it.
¾¾ Getters and setters can be overridden but not variables defined in a superclass.
¾¾ Static properties can be accessed through an instance of a sub-class. It can only be accessed through the class
object on which it is defined.
¾¾ Static properties are within the scope chain of the class that defines them and any sub-class of that class, even
if they are not inherited.
11.6 Exercise
1. Which of these stores information about the types of data that an object can hold and the behaviors that an object
can exhibit?
Variables
Classes
Array
Inheritance
2. A code that allows programmers to develop new classes that are based on existing classes is called as __________.
Interface
Polymorphism
Inheritance
3. An instance property is inherited by all sub-classes as long as the property is not declared with the __________
attribute in the Base class.
private
public
static
protected
4. Properties can be overridden that are declared with the var or const keywords, but they can be inherited.
True
False
5. Attempting to access a private variable will not result in a run-time error when classes are declared with the dynamic
attribute.
True
False
Session 12
Working with ActionScript 3.0 Objects
Learning Outcomes
In this session, you will learn to:
¾¾ Understand the basic concept of Objects in AS 3.0 programming
¾¾ Identify properties in AS 3.0 programming
¾¾ Determine methods in AS 3.0 programming
¾¾ Understand Event Handling and process in AS 3.0 programming
12.1 Introduction
ActionScript is an object-oriented programming language. It helps in managing code by organizing it into logical chunks
known as objects. Objects are logical containers that have chunks of code providing similar functionality. In addition,
they may contain supporting information required by the code to provide this functionality.
12.2 Properties
Properties represent pieces of data that is bundled together in an object. For example, a song object may have the name
of the artist and title of the song as its properties. In ActionScript 3.0, the MovieClip class has properties like width,
rotation, and alpha.
Properties are individual variables and are considered ‘child’ variables of an object.
A property can be accessed or modified by first mentioning the name of the object followed by a period (.) and then
mentioning the name of the property. Following are some examples of ActionScript code that uses property ‘x’ to move
the MovieClip object named ‘square’ to the ‘x’ coordinate by 110 pixels:
square.x = 110;
To match with the rotation of the triangle MovieClip, the following code uses the rotation property to make the
square MovieClip rotate accordingly.
square.rotation = triangle.rotation;
To change the size of the square MovieClip to one-and-a-half times wider than its original size, this code alters the
horizontal scale of the square MovieClip.
square.scaleX = 1.5;
A variable (square, triangle) is used as the name of the object which is followed by a period (.) and then the name
of the property (x, rotation, scaleX) is mentioned. The period is known as dot operator, which is used to specify
that one of the child elements of an object is being accessed.
12.3 Methods
An action that can be performed by an object is called as a method. For example, if a movie clip symbol in Flash is made
with some keyframes and animation on its timeline, then the MovieClip can be instructed either to play, stop, or move
the playhead to a particular frame.
The following code directs the MovieClip named shortFilm to start playing:
shortFilm.play();
The following code instructs the MovieClip named shortFilm to stop playing:
shortFilm.stop();
The following code directs a MovieClip named shortFilm to move its playhead to Frame 1 and stop playing:
shortFilm.gotoAndStop(1);
Just like properties, methods are accessed by writing the object’s name (variable), followed by a period, and the name
of the method, followed by parentheses. The parentheses indicate that the method has been called or the object has
been directed to execute an action. Values or variables can be placed in the parentheses to convey extra information
required to carry out an action by the method. These values or variables are called method parameters. For example,
the gotoAndStop() method requires a single parameter in the parentheses so as to know which frame it should go to.
The play() and stop() methods are easy to understand and are written with parentheses.
Methods are not used as value placeholders. Some methods can perform calculations and return a result that can be used
like a variable. For example, to convert the numeric value to its text representation, the Number class’s toString()
method is used as follows:
var numericData:Number = 9;
The actual text content displayed on the screen, which is the TextField class’s text property, is defined as a String
that contains only text values.
The numeric value in the variable numericData to text is converted by the line of code to show up on the screen in
the TextField object as follows:
calculatorDisplay:
calculatorDisplay.text = numericData.toString();
eResources 4 Me>> My Varsity>> Web Animation and Interactivity>> Show Me How >> Events and Handling Events
In ActionScript 3.0, an event object represents each event that belongs to an instance of the Event class or one of
its sub-classes. An event object contains methods that assist in manipulation of the object and also stores information
about a specific event. It is similar to the Flash Player, which creates an event object on detecting a click. This event
object is an instance of the MouseEvent class that represents a particular mouse-click event.
Flash Player dispatches or passes an event object to the object which is the target of the event.
Even though the event target is on the display list, the event object passes down through the hierarchy until it reaches
the event target. Sometimes the event object ‘bubbles’ back the display list hierarchy along the same route. This display
list hierarchy is called the event flow.
By using event listeners, event objects can be listened. The functions or methods that are written to respond to specific
events are called event listeners. By adding event listeners to the event target or to any display list object, which is a
part of an event flow ensures that the program responds to events. Event listener code follows a basic structure, where
the elements in bold are the placeholders to be filled in for a specific case:
function eventResponse(eventObject:EventType):void
eventTarget.addEventListener(EventType.EVENT_NAME, eventResponse);
12.4.2 Difference between ActionScript 3.0 Event Handling and Earlier Versions
There is only one system for Event Handling in ActionScript 3.0 as compared to the previous versions of ActionScript 1.0
and 2.0. Following are the differences:
■■ Event Handling in previous versions of ActionScript
These mechanisms have their own individual set of advantages and disadvantages that are as follows:
¾¾ It is easy to use the on() and onClipEvent() handlers, but maintenance of projects is hectic as it is difficult
to find the codes placed directly on the buttons.
¾¾ It is simple to implement Callback functions, but it allows only one function for any given event.
¾¾ Apparently, event listeners are more complicated to apply as they need the registration of the listener with the
object that generates the event along with the creation of a listener object and function. This creates some
listener objects and registers them all for the same event.
ActionScript 2.0 developed another event model that was embodied in the UIEventDispatcher class, which was
based on a sub-set of the DOM Events Specification. The transition to the new ActionScript 3.0 event model was
effortless.
The syntax used by the event models overlaps and differs. For example, some properties like TextField.
onChanged in ActionScript 2.0 can be used as a Callback function or as an event listener.
The syntax for registering listener objects varies depending on whether the UIEventDispatcher class or one of
the six classes that support listeners is being used. The Mouse, Key, MovieClipLoader, Selection, TextField
classes, and Stage can be used for using the addEventListener() method for Event Handling.
■■ Event Handling in ActionScript 3.0
A single Event Handling model was introduced in ActionScript 3.0 replacing the different Event Handling mechanisms
that existed in the previous versions of the language. This is based on the DOM Level 3 Events Specification. There
are adequate similarities between the display list and the structure of the DOM that makes the implementation of
the DOM event model possible. An object on the display list is similar to a node in the DOM hierarchical structure,
and the terms display list object and node that are used throughout. One such concept named default behaviors is
included in the Flash Player implementation of the DOM event model.
■■ Default behaviors
Flash Player is commonly associated with a behavior of an event that it involuntarily executes unless the developer
adds code to cancel it. Such behaviors are called default behaviors as Flash Player automatically exhibits them.
For example, when a text is entered into a TextField object, the behavior is built into Flash Player. This default
behaviour can be cancelled using the new Event Handling system. Flash Player creates an instance of the
TextEvent class when the user inputs text into a TextField object. To prevent this, the specific TextEvent
instance must be accessed and that instance’s preventDefault() method should be called.
Not all default behaviors can be prevented. For example, Flash Player generates a MouseEvent object when a user
double-clicks a word in the TextField object. This default behavior cannot be prevented and also the word under
the cursor gets highlighted. When a network connection is established, Flash Player dispatches a connect event
object, but a default behavior is not associated with it. Each type of event is listed by the API documentation for the
Event class and its sub-classes. It also describes any associated default behavior, and whether that behavior can
be prevented.
Default behaviors are associated only with event objects that are dispatched by the Flash Player. They do not exist
for event objects that are dispatched programmatically through ActionScript. For example, the methods of the
EventDispatcher class can be used to dispatch an event object of type textInput without a default behavior
associated with it. This means that a character in a TextField object will not be displayed by Flash Player due to
a textInput event being dispatched programmatically.
■■ Event listeners in ActionScript 2.0 and ActionScript 3.0
Refer to Table 12.1 that shows some key differences between the two event models.
The way the event object moves through the display list is described by the event flow. The display list is arranged in a
hierarchy that starts with the Stage, which is a special display object container that serves as the root of the display list.
The flash.display.Stage class represents the Stage and is accessed through a display object. Each display object
has a property named Stage that refers to the Stage for that application.
When an event object is dispatched by the Flash Player, it moves from the Stage to the target node. The node representing
the event target is defined by the DOM Events Specification that defines the target node. In simpler terms, the target
node is the display list object where the event occurs. For example, Flash Player dispatches an event object using
Child1 as the target node, when a user displays list object named Child1.
The event flow is split into three parts. Refer to Figure 12.2.
Refer to Figure 12.3 that shows a display list as a vertical hierarchy with the Stage at the top.
Flash Player dispatches an event object into the event flow when a user clicks Child1 Node.
Refer to Figure 12.4, where the object begins at Stage, next it moves to Parent Node, and then finally to Child1 Node,
and then it goes again to Stage, repeating the same procedure. In this example, Stage and Parent Node are the
‘Capture Phases’. The time spent at Child1 Node is the ‘Target Phase’. The Parent Node and Stage are the ‘Bubbling
Phase’ and they are encountered while going up to the root node.
Figure 12.4: Event flow displaying Capture, Bubbling, and Target Phases
A more powerful Event Handling System is contributed by the event flow. However, it does not exist in the previous
versions of ActionScript.
When a user interface component comprises more than one object, then it is useful to add event listeners along with the
event flow. In the example, a button object that serves as the button’s label often contains a text object. In case a listener
is not added to the event flow, then both the button and the text objects need to be added to ensure that notification
is received about click events that occur anywhere on the button. Nevertheless, the event flow allows placing a single
event listener on the button object that handles click events.
Not all event objects take part in all three phases of the event flow. The enterFrame and init event types are some
of the types of events that are dispatched directly to the target node and participate in neither the Capture Phase nor the
Bubbling Phase. Events that are dispatched to an instance of the Socket class may not be present on the display list
and without participating in the Capture and Bubbling Phases these event objects will flow directly to the target object.
By either checking the API documentation or examining the event object’s properties, the behavior of a particular event
type can be found.
¾¾ Event objects include a set of methods that provide its manipulation and also affect the behavior of the Event
Handling System.
The Flash Player API defines an Event class that serves as the base class for all event objects, enabling accessibility to
these properties and methods. Thus, a fundamental set of properties and methods that are common to all event objects
is defined by the Event class.
ActionScript 3.0 event model deviates from the DOM event model as it creates the listener functions.
¾¾ There is a clear difference between an event listener and a listener function in the DOM event model. An event
listener is an instance of a class that implements the EventListener interface. A listener function is a method
of a class named handleEvent(). However, there is no difference between an event listener and a listener
function in the ActionScript 3.0 event model. Moreover, it does not have an EventListener interface but the
listener functions can be defined outside a class or as a part of a class.
¾¾ In the DOM event model, the class instance is registered that contains the listener function. In ActionScript 3.0,
the name of the actual listener function is registered. Listener functions can be named with any valid identifier.
■■ Adding event listeners
The IEventDispatcher interface relies on the addEventListener() method, which is used to register listener
function. It requires two parameters:
¾¾ Type: This parameter is used to specify the type of event.
¾¾ Listener: This parameter is used to specify the listener function that will be implemented when the event occurs.
It can also be a reference to a function or a class method.
To remove an event listener, the removeEventListener() method can be used. It is advisable to remove any
listeners that will no longer be used. The necessary parameters are the eventName and listener parameters similar
to the parameters for the addEventListener() method. By calling addEventListener() twice, events can
be listened during all event phases; once by using useCapture, it can be set to true and later to false. By calling
removeEventListener() twice, both event listeners can be removed; once by using useCapture set to true,
and then by setting useCapture to false.
Another easy method of creating an object instance does not require ActionScript. In Flash, when a movie clip symbol,
text field on the Stage, or button symbol, assign an instance name in the Property inspector, then Flash declares a
variable with that instance name and creates an object instance, which stores that object in the variable.
Object instances can also be created using only ActionScript. By using many ActionScript data types, an instance using
a literal expression can be created, which is the value written in the ActionScript code. For example,
■■ Literal numeric value (the number is entered directly):
var someNumber:Number = 17.239;
</employee>;
■■ Literal expressions such as Array, RegExp, Object, and Function data types are defined in
ActionScript. The new operator with the class name can be used for any other data type
as follows:
var raceCar:MovieClip = new MovieClip();
“Calling the class’s constructor” is referred to by creating an object using the new operator. A special method known as
a constructor is called as part of the process of creating an instance of a class. It is important to note, that parentheses
should be put after the class name when creating an instance, and also parameter values should be specified.
The new operator can be used to create an object instance for data types that create instances using a literal
expression.
An instance can be created of any ActionScript data type that does not have a visual representation by creating the
object directly in ActionScript using the new operator.
The new operator, in Flash, can be used to create an instance of a movie clip symbol by defining it in the Library but not
placing on the Stage.
12.7 Summary
In this session, Working with ActionScript 3.0 Objects, you learned that:
¾¾ ActionScript is an object-oriented programming language. It helps in managing code by organizing it into
logical chunks known as objects. The three components in ActionScript 3.0 object-oriented programming are:
Properties, Methods, and Events.
¾¾ An event is an important occurrence that triggers a response in a program, such as mouse click or loading of a
frame. In ActionScript, events are split in two categories — namely, Built-in and Custom.
¾¾ The things that happen and the way they are responded to in ActionScript 3.0 are called events.
¾¾ An event object contains methods that assist in manipulation of the object and also stores information about a
specific event.
¾¾ Sometimes the event object ‘bubbles’ back the display list hierarchy along the same route. The display list
hierarchy is called the event flow.
¾¾ The functions or methods that are written to respond to specific events are called event listeners.
¾¾ The technique for specifying certain actions that should be performed in response to particular events is known
as Event Handling.
¾¾ Flash Player is commonly associated with a behavior with an event that it involuntarily executes unless the
developer adds code to cancel it. Such behavior is called as default behavior.
¾¾ Whenever an event occurs, Flash Player dispatches event objects directly to the event target if the event target
is not on the display list. The way the event object moves through the display list is described by the event flow.
The three parts of event flow are: Capture Phase, Target Phase, and Bubbling Phase.
¾¾ A number of read-only properties and constants that provide important information about an event object are
defined by the Event class.
¾¾ Event listeners are also called event handlers. These are functions that Flash Player executes in response to
specific events.
¾¾ An object can be created by declaring a variable, which in turn creates an empty space in the computer’s
memory. The objects can also be created using only ActionScript.
¾¾ The Toolkit for CreateJS will enable influencing the core animation and illustration capabilities of Flash
Professional including vectors, bitmaps, tweens, and sounds. Once developers receive the assets, they can
leverage them as reusable JavaScript symbols, and interactivity can be added using the familiar CreateJS
framework.
12.8 Exercise
1. The technique for specifying certain actions that should be performed in response to a particular event is known as
___________.
Event Handling
Event flow
Event listeners
Event method
Event flow
Event handlers
Event class
Event object
3. The functions or methods that are written to respond to specific events are called _________.
Event flow
Event class
Event listeners
Event object
4. The IEventDispatcher interface relies on the addEventListener() method, which is used to register listener
functions.
True
False
True
False
Answer Key
Exercise 9.7
1. Compiling a 2. String
program
3. Constructor 4. True
parameter
5. False
Exercise 10.5
1. Dynamic text 2. Capture input from
the user’s camera
3. True 4. SoundChannel
4. False
Exercise 11.6
1. Classes 2. Inheritance
3. private 4. False
3. True
Exercise 12.8
1. Event Handling 2. Event handlers
3. Event listeners 4. True
5. False
Bibliography
Web Animation & Interactivity
- Christine Saucier