MACROMEDIA FLASH 8-LEARNING ACTIONSCRIPT 2.0 IN FLASH Manual

Summary of FLASH 8-LEARNING ACTIONSCRIPT 2.0 IN FLASH

  • Page 1

    Learning actionscript 2.0 in flash.

  • Page 2

    Trademarks 1 step robopdf, activeedit, activetest, authorware, blue sky software, blue sky, breeze, breezo, captivate, central, coldfusion, contribute, database explorer, director, dreamweaver, fireworks, flash, flashcast, flashhelp, flash lite, flashpaper, flash video encoder, flex, flex builder, f...

  • Page 3

    3 contents introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 intended audience . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 system requirements. . . . . . . . . . . . . . . . . . . . . . . . . . ....

  • Page 4

    4 contents chapter 5: syntax and language fundamentals . . . . . . . . . . . . 113 about syntax, statements, and expressions . . . . . . . . . . . . . . . . . . . . . .114 about dot syntax and target paths. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .118 about language punctuators . ....

  • Page 5

    Contents 5 chapter 10: handling events . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329 using event handler methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330 using event listeners . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ....

  • Page 6

    6 contents chapter 13: animation, filters, and drawings. . . . . . . . . . . . . . 469 scripting animation with actionscript 2.0 . . . . . . . . . . . . . . . . . . . . . .470 about bitmap caching, scrolling, and performance . . . . . . . . . . . . . 480 about the tween and transitionmanager classes...

  • Page 7

    Contents 7 chapter 18: debugging applications . . . . . . . . . . . . . . . . . . . . . . 711 debugging your scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 711 using the output panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ...

  • Page 8

    8 contents.

  • Page 9

    9 introduction macromedia flash basic 8 and macromedia flash professional 8 are the professional standard authoring tools for producing high-impact web experiences. Actionscript is the language you use to add interactivity to flash applications, whether your applications are simple animated swf file...

  • Page 10

    10 introduction system requirements actionscript 2.0 does not have any system requirements in addition to flash 8. This manual assumes that you are using the default publishing settings for your flash files: flash player 8 and actionscript 2.0. If you change either of these settings, explanations an...

  • Page 11

    About the documentation 11 learning actionscript 2.0 book overview the following list summarizes the contents of this manual: ■ chapter 1, “what’s new in flash 8 actionscript,” describes features that are new in actionscript, changes to the compiler and debugger, and the new programming model for th...

  • Page 12

    12 introduction ■ chapter 15, “working with images, sound, and video,” describes how to import external media files, such as bitmap images, mp3 files, flash video (flv) files, and other swf files, in your flash applications. This chapter also provides an overview of how to work with video in your ap...

  • Page 13

    About the documentation 13 ■ bold code font , typically within a procedure, indicates code that you need to modify or add to code you have already added to your fla file. In some case, it might be used to highlight code to look at. ■ boldface text indicates data you need to type into the user interf...

  • Page 14

    14 introduction be cautious of proper line breaks when you copy and paste code. If you paste your code from some locations, the line of code might break in an improper location. Make sure that the color coding of your syntax is correct in the actionscript editor if you think line breaks might be a p...

  • Page 15

    Additional resources 15 you can find the actionscript-focused sample source files in the samples folder on your hard disk. ■ in windows, browse to boot drive\program files\macromedia\flash 8\ samples and tutorials\samples\actionscript\. ■ on the macintosh, browse to macintosh hd/applications/macrome...

  • Page 16

    16 introduction technical writers monitor the livedocs website. One of the advantages of livedocs is seeing comments that clarify the documentation or correct any errata or issues that arise after a software release. Livedocs is not the place to make help requests, such as asking questions about you...

  • Page 17

    Additional resources 17 the macromedia web forums ( http://webforums.Macromedia.Com ) provides numerous forums for asking specific questions about flash, your applications, or the actionscript language. The forums are monitored by team macromedia volunteers and often visited by macromedia employees ...

  • Page 18

    18 introduction.

  • Page 19

    19 1 chapter 1 what’s new in flash 8 actionscript macromedia flash basic 8 and macromedia flash professional 8 provide several enhancements that make it easy for you to write robust scripts using the actionscript (as) language. The new features, which are discussed in this chapter, include new langu...

  • Page 20

    20 what’s new in flash 8 actionscript the following features were added to both flash basic 8 and flash professional 8 (unless noted otherwise): ■ actionscript editor enhancements let you show hidden characters in your scripts. For more information, see “showing hidden characters” on page 53 . ■ deb...

  • Page 21

    New in actionscript 2.0 and flash 8 21 ■ a new garbage collector is built into flash player, which uses an incremental collector to improve performance. ■ the workflow for creating accessible applications is improved. Flash player 8 no longer requires developers to add all objects to the tab index f...

  • Page 22

    22 what’s new in flash 8 actionscript additions to the actionscript language this section lists additions to actionscript language elements and classes that are new or changed in flash 8. The following classes and language elements are new additions or newly supported in flash player 8. The followin...

  • Page 23

    New in actionscript 2.0 and flash 8 23 ■ the locale class (in the mx.Lang package) lets you control how multilanguage text appears in a swf file. ■ the matrix class (in the flash.Geom package) represents a transformation matrix that determines how to map points from one coordinate space to another. ...

  • Page 24

    24 what’s new in flash 8 actionscript ■ the onhttpstatus event handler of the loadvars class returns the status code that’s returned from the server (for example, the value 404 for page not found). For more information, see onhttpstatus (loadvars.Onhttpstatus handler) in the actionscript 2.0 languag...

  • Page 25

    New in actionscript 2.0 and flash 8 25 ■ the status parameter of the moviecliploader . Onloadcomplete event handler returns the status code that’s returned from the server (for example, the value 404 for page not found). For more information, see onloadcomplete (moviecliploader.Onloadcomplete event ...

  • Page 26

    26 what’s new in flash 8 actionscript ■ the letterspacing property in the textformat class, which lets you specify the amount of space that is uniformly distributed between characters. ■ the _alpha property in the video class, which is the specified amount of transparency for the video object. ■ the...

  • Page 27

    New in actionscript 2.0 and flash 8 27 ■ the prefix property of the xmlnode class, which reads the prefix of the node name. ■ the getnamespaceforprefix() method of the xmlnode class, which returns the namespace uri associated with the specified prefix for the node. ■ the getprefixfornamespace method...

  • Page 28

    28 what’s new in flash 8 actionscript reload modified files you can reload modified script files when working on an application. A warning message appears, prompting you to reload the modified script files associated with the application you’re working on. This feature is particularly beneficial to ...

  • Page 29

    Changes to security model for locally installed swf files 29 in flash player 7 and earlier, local swf files had permissions to access both the local file system and the network. In flash player 8, local swf files can have three levels of permission: ■ access the local file system only (the default l...

  • Page 30

    30 what’s new in flash 8 actionscript.

  • Page 31

    31 2 chapter 2 writing and editing actionscript 2.0 when you write actionscript code in macromedia flash basic 8 or macromedia flash professional 8, you use the actions panel or script window. The actions panel and script window contain a full-featured code editor (called the actionscript editor) th...

  • Page 32

    32 writing and editing actionscript 2.0 for more information on handling events, see the following sections: about actionscript and events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 organizing actionscript code . . . . . . . . . . . . . . . . . . . ....

  • Page 33

    Organizing actionscript code 33 clip events within a movie clip, you may react to a number of clip events that are triggered when the user enters or exits the scene or interacts with the scene by using the mouse or keyboard. You might, for example, load an external swf file or jpg image into the mov...

  • Page 34

    34 writing and editing actionscript 2.0 rather than attaching your scripts to elements like keyframes, movie clips, and buttons, you should respond to events by calling functions that reside in a central location. One method is to attach embedded actionscript to the first or second frame of a timeli...

  • Page 35

    Using the actions panel and script window 35 when you use behaviors, which are predefined actionscript functions (see “about behaviors” on page 61 ), other workflow and code organization issues must be considered. About writing scripts to handle events writing code for events can be categorized into...

  • Page 36

    36 writing and editing actionscript 2.0 about the actions panel you use the actions panel to create actionscript in a flash document (a fla file). The actions panel consists of three panes, each of which supports you in creating and managing scripts. Actions toolbox use the actions toolbox to browse...

  • Page 37

    About the script window 37 script pane the script pane is where you type your code. The script pane provides you with tools to create scripts in a full-featured editor (called the actionscript editor) that includes code syntax formatting and checking, code hinting, code coloring, debugging, and othe...

  • Page 38

    38 writing and editing actionscript 2.0 you will also notice that many of the options available in the actions panel are unavailable in the script window. The script window supports the following editor options: the actions toolbox, find and replace, syntax checking, automatic formatting, code hinti...

  • Page 39

    About coding in the actions panel and script window 39 the following topics present the many features of the actionscript editor (actions panel and script window): ■ “about the actions panel and script window toolbars” on page 39 ■ “about actionscript editing options” on page 41 ■ “about actionscrip...

  • Page 40

    40 writing and editing actionscript 2.0 the features you find in the toolbar are discussed in detail in “using the actions panel and script window” on page 35 . A quick summary of the buttons you find on the toolbars of both the actions panel and the script window follows. Add a new item to the scri...

  • Page 41

    About coding in the actions panel and script window 41 pop-up menu actions panel only. Contains the many commands and preferences that apply to the actions panel or script window. For example, you can set line numbers and word wrapping in the actionscript editor, access the actionscript preferences,...

  • Page 42

    42 writing and editing actionscript 2.0 import script allows you to import a script file (actionscript) into the script pane. For more information, see “import and export preferences” on page 57 . Export script exports the current script to an external actionscript (as) file. For more information, s...

  • Page 43

    About coding in the actions panel and script window 43 2. To access actionscript preferences in the script window, select edit > preferences and then click actionscript (windows) or flash > preferences and then click actionscript (macintosh). The following image shows the actionscript settings you c...

  • Page 44

    44 writing and editing actionscript 2.0 use dynamic font mapping checks to ensure that the selected font family has the necessary glyphs to render each character. If not, flash substitutes a font family that contains the necessary characters. For more information, see “formatting code” on page 50 . ...

  • Page 45

    About coding in the actions panel and script window 45 about triggering code hints when you work in the actions panel or script window, flash can detect what action you are entering and display a code hint. The two different styles of code hint are a tooltip that contains the complete syntax for tha...

  • Page 46

    46 writing and editing actionscript 2.0 to specify a delay for code hints: 1. In the actions panel or script window, select edit > preferences (windows) or flash > preferences (macintosh) from the main menu. 2. Click actionscript in the category list. 3. Use the slider to select an amount of delay. ...

  • Page 47

    About coding in the actions panel and script window 47 3. To dismiss the code hint, do one of the following: ■ type a closing parens [ ) ]. ■ click outside the statement. ■ press escape. To work with menu-style code hints: 1. Display the code hint by typing a period after the variable or object name...

  • Page 48

    48 writing and editing actionscript 2.0 2. Do one of the following: ■ click show code hint in the actions panel or script window toolbar. ■ press control+spacebar (windows) or command+spacebar (macintosh). ■ if you are working in the actions panel, select show code hint from the pop-up menu. About t...

  • Page 49

    About coding in the actions panel and script window 49 the following table lists the suffixes required for support of automatic code hinting: for information on using code hints when they appear, see “using code hints” on page 45 . Object type variable suffix array _array button _btn camera _cam col...

  • Page 50

    50 writing and editing actionscript 2.0 about using comments to trigger code hints you can also use actionscript comments to specify an object’s class for code hints. The following example tells actionscript that the class of the theobject instance is object, and so on. If you were to enter mc follo...

  • Page 51

    About coding in the actions panel and script window 51 to format code according to auto format settings, do one of the following: ■ click the auto format button in the actions panel or script window toolbar. ■ in the actions panel, select auto format from the pop-up menu. ■ press control+shift+f (wi...

  • Page 52

    52 writing and editing actionscript 2.0 to set preferences for syntax coloring as you type, do one of the following: ■ select edit > preferences (windows) or flash > preferences (macintosh), click actionscript in the category list, and specify syntax coloring settings. ■ in the actions panel, select...

  • Page 53

    About coding in the actions panel and script window 53 for example, if you are working in the script pane and press escape+d+o, the following code is placed in your script: do { } while (); the insertion point is placed immediately following the word while , so you can begin typing your condition. S...

  • Page 54

    54 writing and editing actionscript 2.0 the following symbols are used to display each hidden character: to show hidden characters, do one of the following: ■ select hidden characters from the pop-up menu. ■ press control+shift+8 (windows) or command+shift+8 (macintosh). With hidden characters shown...

  • Page 55

    About coding in the actions panel and script window 55 3. Click find next. If the text or characters are present in the script, the words or characters will be highlighted in the script pane. To find and replace text in a script: 1. From the actions panel or script window toolbar, click the find too...

  • Page 56

    56 writing and editing actionscript 2.0 to check for punctuation balance, do one of the following: ■ click between braces ({}), brackets ([]), or parentheses [()] in your script. ■ for windows, press control+' (single quote), or for macintosh, press command+' (single quote) to highlight the text bet...

  • Page 57

    About coding in the actions panel and script window 57 unicode support for actionscript flash 8 supports unicode text encoding for actionscript. This means that you can include text in different languages in an actionscript file. For example, you can include text in english, japanese, and french in ...

  • Page 58

    58 writing and editing actionscript 2.0 to turn the export encoding warning off or on: 1. In the flash system menu, select edit > preferences (windows) or flash > preferences (macintosh), and click warnings from the category list. 2. Select or deselect warn on encoding conflicts when exporting actio...

  • Page 59

    About actions panel features 59 in the example below, the gotoandplay function was added to the script pane. Script assist displays all of the prompts needed to use this actionscript function—in this case, the scene name, the type, and the frame number. Pinning scripts in the actions panel if you do...

  • Page 60

    60 writing and editing actionscript 2.0 to pin a script: 1. Position your mouse pointer on the timeline so the script appears in a tab at the lower left of the script pane in the actions panel. 2. Do one of the following: ■ click the pushpin icon to the right of the tab. ■ right-click (windows) or c...

  • Page 61

    About behaviors 61 the target path tool, which is available in the actions panel, prompts you to enter the target path for the selected action in your script. To insert a target path: 1. Select and position the pointer in an action in your script. 2. Click target path on the actions panel toolbar. T...

  • Page 62

    62 writing and editing actionscript 2.0 the behavior is added to the object and is displayed in the actions panel. About actionscript publish settings you can edit actionscript in two ways. You can edit actionscript that is embedded into a flash document by using the actions panel. Or you can edit a...

  • Page 63

    About actionscript publish settings 63 to change the actionscript version: 1. Select file > publish settings and then select the flash tab. 2. Select the actionscript version from the pop-up menu. Actionscript 2.0 is selected by default. If you write your scripts in actionscript 1.0 instead of 2.0, ...

  • Page 64

    64 writing and editing actionscript 2.0 3. Do one of the following: ■ to add a directory to the classpath, click browse to path, browse to the directory you want to add, and click ok. Alternatively, click add new path (+) to add a new line to the classpath list. Double- click the new line, type a re...

  • Page 65

    About actionscript publish settings 65 configuration files that install with flash 8 when you install flash basic 8 or flash professional 8, several actionscript-related configuration folders and files are placed on your system. You might use these files to make certain configurations to the authori...

  • Page 66

    66 writing and editing actionscript 2.0

  • Page 67

    67 3 chapter 3 about actionscript the object-oriented programming (oop) features in actionscript 2.0 are based on the ecmascript 4 draft proposal currently in development by ecma tc39-tg1 (see www.Mozilla.Org/js/language/es4/index.Html ). Because the ecma-4 proposal is not yet a standard, and becaus...

  • Page 68

    68 about actionscript although macromedia recommends that you use actionscript 2.0, you can continue to use actionscript 1.0 syntax, especially if you are doing more traditional flash work such as simple animation that doesn’t require user interaction. What is actionscript the main features of actio...

  • Page 69

    About choosing between actionscript 1.0 and actionscript 2.0 69 about choosing between actionscript 1.0 and actionscript 2.0 when you start a new document or application in flash, you must decide how to organize its associated files. You might use classes in some projects, such as when you are build...

  • Page 70

    70 about actionscript understanding actionscript and flash player if you compile a swf file that contains actionscript 2.0 with publish settings set to flash player 6 and actionscript 1.0, your code functions as long as it does not use actionscript 2.0 classes. No case sensitivity is involved with t...

  • Page 71

    71 4 chapter 4 data and data types this chapter is the first of several chapters that outline and demonstrate some fundamental concepts of actionscript. You’ll practice some basic coding techniques to learn how to create complex applications. In this chapter, you’ll also learn about how to work with...

  • Page 72

    72 data and data types some of the most common kinds of data include strings (a sequence of characters, such as names and passages of text), numbers, objects (such as movie clips), boolean values ( true and false ), and so on. In this chapter, you’ll also learn about the data types in flash and how ...

  • Page 73

    About data types 73 you can find a sample source file, datatypes.Fla, in the samples folder on your hard disk, which shows you how to use data types in an application. ■ in windows, browse to boot drive\program files\macromedia\flash 8\samples and tutorials\samples\actionscript\datatypes. ■ on the m...

  • Page 74

    74 data and data types you can find a sample source file, datatypes.Fla, in the samples folder on your hard disk, which shows you how to use data types in an application. ■ in windows, browse to boot drive\program files\macromedia\flash 8\samples and tutorials\samples\actionscript\datatypes. ■ on th...

  • Page 75

    About data types 75 boolean data type a boolean value is one that is either true or false . Actionscript also converts the values true and false to 1 and 0 when appropriate. Boolean values are most often used with logical operators in actionscript statements that make comparisons to control the flow...

  • Page 76

    76 data and data types //display the label welcome_lbl.Visible = true; } }; submit_button.Addeventlistener("click", btnlistener); for more information, see “using functions in flash” on page 214 and “about logical operators” on page 194 . Movieclip data type movie clips are symbols that can play ani...

  • Page 77

    About data types 77 the second example creates a movie clip called square_mc that uses the drawing api to draw a rectangle. Event handlers and the startdrag() and stopdrag() methods of the movieclip class are added to make the rectangle draggable. This.Createemptymovieclip("square_mc", 1); square_mc...

  • Page 78

    78 data and data types number data type the number data type is a double-precision floating-point number. The minimum value of a number object is approximately 5e-324. The maximum is approximately 1.79e+308. You can manipulate numbers using the arithmetic operators addition ( + ), subtraction (-), m...

  • Page 79

    About data types 79 the actionscript movieclip object has methods that let you control movie clip symbol instances on the stage. This example uses the play() and nextframe() methods: mcinstancename.Play(); mc2instancename.Nextframe(); you can also create custom objects to organize information in you...

  • Page 80

    80 data and data types to include a quotation mark in a string, precede it with a backslash character (\). This is called escaping a character. There are other characters that cannot be represented in actionscript except by special escape sequences. The following table lists all the actionscript esc...

  • Page 81

    About data types 81 if your application has multiple frames, the code does not execute a second time because the init variable is no longer undefined. Void data type the void data type has one value, void , and is used in a function definition to indicate that the function does not return a value, a...

  • Page 82

    82 data and data types using strict data typing helps ensure that you don’t inadvertently assign an incorrect type of value to a variable. Flash checks for typing mismatch errors at compile time, and displays an error message if you use the wrong type of value. Therefore, using strict typing also he...

  • Page 83

    About data types 83 to assign a specific data type to an item, specify its type using the var keyword and post- colon syntax, as shown in the following example: // strict typing of variable or object var mynum:number = 7; var birthday:date = new date(); // strict typing of parameters function welcom...

  • Page 84

    84 data and data types another advantage of strict data typing is that flash automatically shows code hints for built- in objects when they are strictly typed. For more information, see “about assigning data types and strict data typing” on page 81 . Files published using actionscript 1.0 do not res...

  • Page 85

    About data types 85 for example, the following code does not specify the data type of the parameter xparam . At runtime, you use the parameter to hold a value of type number and then a value of type string . The dynamictest() function then uses the typeof operator to test whether the parameter is of...

  • Page 86

    86 data and data types the following example shows how you can use the typeof operator to return the kind of object that you trace: // create a new instance of loadvars class. Var my_lv:loadvars = new loadvars(); /* typeof operator doesn't specify class, only specifies that my_lv is an object */ var...

  • Page 87

    About variables 87 it’s a good idea to assign a value to a variable the first time you declare the variable. Assigning an initial value is called initializing the variable, and it’s often done on frame 1 of the timeline or from within a class that loads when the swf file begins to play. There are di...

  • Page 88

    88 data and data types about declaring variables you can declare variables on a frame in the timeline, directly on an object, or within an external class file. Define variables using the var keyword and follow the variable naming conventions. You can declare a variable called firstname, as shown in ...

  • Page 89

    About variables 89 this example assigns the value of pirate eye to the catname variable. When you declare the variable, you can also assign a value to it instead of assigning it afterwards (as in the previous examples). You could set the catname variable when you declare it, as shown in the followin...

  • Page 90

    90 data and data types if you want to create an array and assign values to it, the format is slightly different, as shown in the following code: var childrenarr:array = new array("pylon", "smithers", "gil"); there is an alternative (shorthand) syntax for creating an array using array access operator...

  • Page 91

    About variables 91 when you assign a value, you use an operator to define a value to a variable. For example, the following script uses the assignment operator to assign a value of 7 to the variable numchildren : var numchildren:number = 7; if you want to change the value of the numchildren variable...

  • Page 92

    92 data and data types the actionscript editor supports code hints for built-in classes and for variables that are based on these classes. If you want flash to provide code hints for a particular object type that you assign to a variable, you can strictly type the variable. Code hints provide toolti...

  • Page 93

    About variables 93 3. Type the following code on frame 1 of the timeline. // does not work function badclicklistener(evt:object):void { geturl(targeturl); var targeturl:string = "http://www.Macromedia.Com"; } bad_button.Addeventlistener("click", badclicklistener); 4. Select control > test movie, and...

  • Page 94

    94 data and data types when you change mynum to 30 (in line 3 of the code), the value of othernum remains 15 because othernum doesn’t look to mynum for its value. The othernum variable contains the value of mynum that it receives (in line 2 of the code). 3. Select control > test movie to see the val...

  • Page 95

    About variables 95 to pass an object by reference: 1. Select file > new and then select flash document to create a new fla file, and save it as copybyref.Fla. 2. Select frame 1 of the timeline, and type the following code into the actions panel: var myarray:array = new array("tom", "josie"); var new...

  • Page 96

    96 data and data types 3. Select control > test movie to test your actionscript. The first trace() statement in this actionscript displays the original contents of the myarray array ( 1,2,3 ). After you call the zeroarray() function and pass a reference to the myarray array, each of the array’s valu...

  • Page 97

    About variables 97 global variables global variables and functions are visible to every timeline and scope in your document. To declare (or create) a variable with global scope, use the _global identifier before the variable name and do not use the var = syntax. For example, the following code creat...

  • Page 98

    98 data and data types to use timeline variables in a document: 1. Create a new flash document, and name it timelinevar.Fla. 2. Add the following actionscript to frame 1 of the timeline: var mynum:number = 15; /* initialized in frame 1, so it's available to all frames */ 3. Select frame 20 of the ti...

  • Page 99

    About variables 99 if the variable name you use for your local variable is already declared as a timeline variable, the local definition takes precedence over the timeline definition while the local variable is in scope. The timeline variable will still exist outside of the function. For example, th...

  • Page 100

    100 data and data types the variables i and j are often used as loop counters. In the following example, you use i as a local variable; it exists only inside the initarray() function: var myarr:array = new array(); function initarray(arraylength:number):void { var i:number; for(i = 0; i myarr[i] = i...

  • Page 101

    About variables 101 you can use variables in different ways in a swf file, depending on what you need the variables for. For more information, see the following topics: ■ “using variables from the url” on page 101 ■ “using flashvars in an application” on page 104 ■ “loading variables from a server” ...

  • Page 102

    102 data and data types the following code demonstrates the html in the document that is responsible for embedding a flash document in an html page. You need to look at this html to understand how url variables work in the following step (where you add additional code for url variables). Codebase="h...

  • Page 103

    About variables 103 remember, you need to make the same changes to both the object tag and the embed tag to maintain consistency between all browsers. You might notice that the words are separated by + punctuators. The words are separated this way because the values are url- encoded and the + punctu...

  • Page 104

    104 data and data types using flashvars in an application using flashvars to pass variables into flash is similar to passing variables along the url in the html code. With flashvars, instead of passing variables after the filename, variables are passed in a separate param tag as well as in the embed...

  • Page 105

    About variables 105 this code passes a single variable called myurl , which contains the string http://weblogs.Macromedia.Com . When the swf file loads, a property named myurl is created in the _level0 scope. One of the advantages of using flashvars or passing variables along the url is that the var...

  • Page 106

    106 data and data types 3. Select control > test movie to test the document. If the file successfully loads, the complete event is called and the output panel displays the value of daynames . If the text file cannot be downloaded, the success argument is set to false and the output panel displays th...

  • Page 107

    About variables 107 the first line of code specifies the image that you want to dynamically load into your flash document. Next, you check whether a new value for imgurl was specified using flashvars or url-encoded variables. If a new value was specified, the default image url is overwritten with th...

  • Page 108

    108 data and data types flashvars="imgurl=http:// www.Helpexamples.Com/flash/images/image2.Jpg" bgcolor="#ffffff" width="550" height="400" name="urlvariables" align="middle" allowscriptaccess="samedomain" type="application/x-shockwave-flash" pluginspage="http://www.Macromedia.Com/go/getflashplayer" ...

  • Page 109

    Organizing data in objects 109 this code, which is one way to create a simple object, creates a new object instance and defines a few properties within the object. 3. Now enter the following actionscript after the code you entered in step 2. // the second way var secondobj:object = {firstvar:"hello ...

  • Page 110

    110 data and data types the following example presents another way to loop over objects. In this example, an object is created and looped over using a for..In loop, and each property appears in the output panel: var myobj:object = {var1:"one", var2:"two", var3:18, var4:1987}; var i:string; for (i in...

  • Page 111

    About casting 111 about casting objects the syntax for casting is type(item) , where you want the compiler to behave as if the data type of the item is type . Casting is essentially a function call, and the function call returns null if the cast fails at runtime (this occurs in files published for f...

  • Page 112

    112 data and data types this example defines two string variables ( firstnum and secondnum ), which are added together. The initial result is that the numbers are concatenated instead of added because they are a string data type. The second trace statement converts both numbers to a number data type...

  • Page 113

    113 5 chapter 5 syntax and language fundamentals learning actionscript syntax and statements is like learning how to put together words to make sentences, which you can then put together into paragraphs. Actionscript can be as simple. For example, in english, a period ends a sentence; in actionscrip...

  • Page 114

    114 syntax and language fundamentals for more information on working with actionscript syntax and language fundamentals, see the following topics: about syntax, statements, and expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .114 about dot syntax and target paths . . . ...

  • Page 115

    About syntax, statements, and expressions 115 expressions, different from statements, are any legal combination of actionscript symbols that represent a value. Expressions have values, while values and properties have types. An expression can consist of operators and operands, values, functions, and...

  • Page 116

    116 syntax and language fundamentals some of the differences between actionscript and javascript are described in the following list: ■ actionscript does not support browser-specific objects such as document, window, and anchor. ■ actionscript does not completely support all the javascript built-in ...

  • Page 117

    About syntax, statements, and expressions 117 when you publish for versions of flash player (flash player 6 and earlier), flash traces the string jimmy in the output panel. Because flash player 7 and later versions are case-sensitive, firstname and firstname are two separate variables (when you use ...

  • Page 118

    118 syntax and language fundamentals about dot syntax and target paths in actionscript, you use a dot ( . ) operator (dot syntax) to access properties or methods that belong to an object or instance on the stage. You also use the dot operator to identify the target path to an instance (such as a mov...

  • Page 119

    About dot syntax and target paths 119 you name instances using an instance name, which you can specify in two different ways (both demonstrated below): ■ manually by selecting an instance and typing an instance name in the property inspector (when an instance is on the stage). ■ dynamically by using...

  • Page 120

    120 syntax and language fundamentals 5. Select modify > convert to symbol, select the movie clip option, and then click ok to create the symbol. 6. Select the movie clip on the stage and give it the instance name myclip in the property inspector. 7. Insert a new layer and rename the layer actions. 8...

  • Page 121

    About dot syntax and target paths 121 if you work with nested movie clips that have their own timelines, you can manipulate the playhead in a nested instance’s timeline using code similar to the following snippet: myclip.Nestedclip.Gotoandplay(15); myclip.Someotherclip.Gotoandstop("tweenin"); notice...

  • Page 122

    122 syntax and language fundamentals 6. Type the following actionscript after the code you added in step 3: rotateclip.Loadmovie("http://www.Helpexamples.Com/flash/images/ image1.Jpg"); this code loads an image into the rotateclip movie clip that you created with code. You’re targeting the rotatecli...

  • Page 123

    About dot syntax and target paths 123 about scope and targeting when you nest instances, the movie clip that nests a second movie clip is known as the parent to the nested instance. The nested instance is known as the child instance. The main stage and main timeline are essentially a movie clip them...

  • Page 124

    124 syntax and language fundamentals using the target path button sometimes it takes some time to figure out what a given target path is, or what target path you need for a piece of code. If you target an instance you have on the stage, you can use the target path button to determine what the path i...

  • Page 125

    About language punctuators 125 for more information on the dot ( . ) operator and array access ( [] ) operators, see “using dot and array access operators” on page 184 . For information on white space and code formatting, see “formatting actionscript syntax” on page 764 . Semicolons and colons actio...

  • Page 126

    126 syntax and language fundamentals you can declare the data type of objects based on built-in classes (button, date, movieclip, and so on) and on classes and interfaces that you create. In the following snippet, you create a new object of the custom type student: var firststudent:student = new stu...

  • Page 127

    About language punctuators 127 in the following example, you create both an event listener object and a moviecliploader instance. Var imgurl:string = "http://www.Helpexamples.Com/flash/images/image1.Jpg"; this.Createemptymovieclip("img_mc", 100); var mcllistener:object = new object(); mcllistener.On...

  • Page 128

    128 syntax and language fundamentals 4. Save the class file. 5. Select file > new and click flash document to create a new fla file. 6. Save the new fla file as student_test.Fla. 7. Type the following actionscript on frame 1 of the main timeline: // student_test.Fla import student; var firststudent:...

  • Page 129

    About language punctuators 129 9. Select file > save to save the flash document. 10. Select control > test movie to test the code in the authoring environment. In the swf file, an error message is displayed if you click the button instance on the stage when you do not have text in the firstname_ti t...

  • Page 130

    130 syntax and language fundamentals because of order of precedence, if you didn’t use parentheses or use two separate statements, the multiplication would be computed first, meaning that the first operation would be 20 * 0.8. The result, 16, would then be added to the current value of circleclip._x...

  • Page 131

    About language punctuators 131 literals can also be used to initialize a generic object. A generic object is an instance of the object class. Object literals are enclosed in curly braces ( {} ) and use the comma punctuator ( , ) to separate object properties. Each property is declared with the colon...

  • Page 132

    132 syntax and language fundamentals avoid using cluttered comments. An example of cluttered comments is a line of equal signs (=) or asterisks (*) used to create a block or separation around your comments. Instead, use white space to separate your comments from the actionscript. If you format your ...

  • Page 133

    About language punctuators 133 multiline comments use multiline comments, also called block comments, for comments that are several lines in length. Developers commonly use multiline comments to describe files, data structures, methods, and descriptions of files. They are usually placed at the begin...

  • Page 134

    134 syntax and language fundamentals trailing comments you use trailing comments to add a comment on the same line as your code. These comments appear on the same line as your actionscript code. Developers commonly use trailing comments to indicate what a variable contains or to describe or note the...

  • Page 135

    About constants and keywords 135 include one documentation comment per class, interface, or member, and place it directly before the declaration. If you have additional information to document that does not fit into the documentation comments, use implementation comments (in the format of block comm...

  • Page 136

    136 syntax and language fundamentals for more information on objects and properties, see “object data type” on page 78 . For a list of constants in the language (such as false and nan ), see the actionscript language elements > constants category in the actionscript 2.0 language reference. Using con...

  • Page 137

    About constants and keywords 137 for example, the class definition in the next example creates three constants that follow the naming convention used by actionscript 2.0. To use constants in an application: 1. Select file > new and then select actionscript file to create an as file. 2. Name the new ...

  • Page 138

    138 syntax and language fundamentals 10. Type the following code into the actions panel: var myexample:constexample = new constexample(); trace(myexample.Example_public); // output: public access this code instantiates the myexample instance and accesses the example_public property. 11. Select contr...

  • Page 139

    About constants and keywords 139 about reserved words reserved words are words that you cannot use as identifiers in your code because the words are reserved for use by actionscript. Reserved words include keywords, which are actionscript statements, and words that are reserved for future use. That ...

  • Page 140

    140 syntax and language fundamentals all built-in class names, component class names, and interface names are reserved words, and should not be used as identifiers in your code: several words, although they are not reserved words, should not be used as identifiers (such as variable or instance names...

  • Page 141

    About statements 141 to learn what these names are, refer to the actionscript 2.0 language reference, and search the help panel for additional instructional and usage sections in this book (learning actionscript 2.0 in flash). About statements a statement is an instruction you give the fla file to d...

  • Page 142

    142 syntax and language fundamentals for more information on each statement, see the following topics: ■ “about compound statements” on page 142 ■ “about conditions” on page 142 ■ “repeating actions using loops” on page 153 about compound statements a compound statement contains numerous statements ...

  • Page 143

    About statements 143 for more information on conditions that you can use, and how to write them, see the following topics: ■ “about writing conditions” on page 143 ■ “using the if statement” on page 144 ■ “using the if..Else statement” on page 145 ■ “using the if..Else if statement” on page 146 ■ “u...

  • Page 144

    144 syntax and language fundamentals using the if statement use the if statement when you want to execute a series of statements based on a whether a certain condition is true. // if statement if (condition) { // statements; } there are several times when you’ll use if statements when you work on a ...

  • Page 145

    About statements 145 using the if..Else statement the if..Else conditional statement lets you test a condition and then execute a block of code if that condition exists or execute an alternative block of code if the condition does not exist. For example, the following code tests whether the value of...

  • Page 146

    146 syntax and language fundamentals using the if..Else if statement you can test for more than one condition using the if..Else if conditional statement. You use the following syntax in an if..Else if statement: // else-if statement if (condition) { // statements; } else if (condition) { // stateme...

  • Page 147

    About statements 147 3. Select control > test movie to test the actionscript. In this code, you create a string called currenthour that holds the current hour number (for example, if it’s 6:19 pm, currenthour holds the number 18 ). You use the gethours() method of the date class to get the current h...

  • Page 148

    148 syntax and language fundamentals to use a switch statement in a document: 1. Select file > new and then select flash document. 2. Select frame 1 of the timeline, and then type the following actionscript in the actions panel: var listenerobj:object = new object(); listenerobj.Onkeydown = function...

  • Page 149

    About statements 149 using try..Catch and try..Catch..Finally statements using try..Catch..Finally blocks lets you add error handling to your flash applications. The try..Catch..Finally keywords let you enclose a block of code where an error can occur and respond to that error. If any code within th...

  • Page 150

    150 syntax and language fundamentals to use the try..Catch..Finally block for data validation before dividing some numbers: 1. Select file > new and then select flash document. 2. Select frame 1 of the timeline, and then type the following actionscript in the actions panel: var n1:number = 7; var n2...

  • Page 151

    About statements 151 to create a custom error: 1. Select file > new and create a new actionscript file. 2. Select file > save as and name the file dividebyzeroexception.As. 3. Type the following actionscript into the script pane: // in dividebyzeroexception.As: class dividebyzeroexception extends er...

  • Page 152

    152 syntax and language fundamentals about the conditional operator and alternative syntax if you like shortcuts, you can use the conditional ( ?: ) operator, also called conditional expressions. The conditional operator lets you convert simple if..Else statements into a single line of code. The ope...

  • Page 153

    About statements 153 when you write complex conditions, it is good form to use parentheses [ () ] to group conditions. If you do not use parentheses, you (or others working with your actionscript) might run into operator precedence errors. For more information on operator precedence, see “about oper...

  • Page 154

    154 syntax and language fundamentals the most common type of loop is the for loop, which loops over a block of code a predefined number of times. For example, if you have an array of items, and you want to perform a series of statements on each item in the array, you would use a for loop and loop fr...

  • Page 155

    About statements 155 to repeat an action using a built-in counter: ■ use the for statement. Most loops use some kind of counter to control how many times the loop executes. Each execution of a loop is called an iteration. You can declare a variable and write a statement that increases or decreases t...

  • Page 156

    156 syntax and language fundamentals for more information on the for..In statement, see “using for..In loops” on page 158 . For more information on each statement, see the individual sections that follow in this chapter, such as “using while loops” on page 160 , and their respective entries in the a...

  • Page 157

    About statements 157 when you work with loops (and especially while and do..While loops), always make sure that the loop can exit properly and does not end up in an infinite loop. For more information on controlling loops, see “using a switch statement” on page 147 . Using for loops the for loop let...

  • Page 158

    158 syntax and language fundamentals 5. Select frame 1 of the timeline, and then type the following actionscript in the actions panel: var i:number; for (i = 0; i this.Attachmovie("librarylinkageclassname", "clip" + i + "_mc", i, {_x:(i * 100)}); } 6. Select control > test movie to test the code in ...

  • Page 159

    About statements 159 this code outputs the following in the output panel: three two one for more information on objects and properties, see “object data type” on page 78 . The following example uses for..In to iterate over the properties of an object: to create a for loop: 1. Select file > new and t...

  • Page 160

    160 syntax and language fundamentals using while loops use the while statement to repeat an action while a condition exists, similar to an if statement that repeats as long as the condition is true . A while loop evaluates an expression and executes the code in the body of the loop if the expression...

  • Page 161

    About statements 161 4. Select frame 1 of the timeline, and then type the following actionscript in the actions panel: var users_ds:mx.Data.Components.Dataset; // users_ds.Additem({name:"irving", age:34}); users_ds.Additem({name:"christopher", age:48}); users_ds.Additem({name:"walter", age:23}); // ...

  • Page 162

    162 syntax and language fundamentals using nested loops in your actionscript the following example demonstrates how to make an array of objects and display each of the values in the nested structure. This example shows you how to use the for loop to loop through each item in the array and how to use...

  • Page 163

    About arrays 163 about arrays an array is an object whose properties are identified by numbers representing their positions in the structure. Essentially, an array is a list of items. It’s important to remember that each element in an array doesn’t have to be the same data type. You can mix numbers,...

  • Page 164

    164 syntax and language fundamentals for more information on modifying arrays, see “about modifying arrays” on page 166 . For information on using arrays and about indexes, see “using arrays” on page 164 . For information on adding and removing elements, see “about adding and removing elements” on p...

  • Page 165

    About arrays 165 to use arrays in your code: 1. Create a new flash document, and save it as basicarrays.Fla. 2. Add the following actionscript to frame 1 of the timeline: // define a new array var myarr:array = new array(); // define values at two indexes myarr[1] = "value1"; myarr[0] = "value0"; //...

  • Page 166

    166 syntax and language fundamentals about modifying arrays you can also control and modify the array using actionscript. You can move values around an array, or you can change the size of the array. For example, if you want to exchange data at two indexes in an array, you can use the following code...

  • Page 167

    About arrays 167 about referencing and finding length when you work with arrays, you often need to know how many items exist in the array. This can be very useful when writing for loops that iterate through every element in the array and execute a series of statements. You can see an example in the ...

  • Page 168

    168 syntax and language fundamentals about adding and removing elements an array contains elements and each element has a numeric position (the index), which is how you refer to each element's position in the array. Each element can either hold a piece of data or be empty. An element can hold the fo...

  • Page 169

    About arrays 169 to create an indexed array: 1. Create a new flash document, and save it as indexarray.Fla. 2. Add the following actionscript to frame 1 of the timeline: var myarray:array = new array(); myarray.Push("one"); myarray.Push("two"); myarray.Push("three"); trace(myarray); // one,two,three...

  • Page 170

    170 syntax and language fundamentals to create a basic multidimensional array and retrieve elements from the array: 1. Create a new flash document, and save it as multiarray1.Fla. 2. Add the following actionscript to frame 1 of the timeline: var twodarray:array = new array(new array("one","two"), ne...

  • Page 171

    About arrays 171 for (j = 0; j mainarr[i][j] = "[" + i + "][" + j + "]"; } } trace(mainarr); this actionscript creates a 3 x 3 array and sets the value of each array node to its index. Then you trace the array ( mainarr ). 3. Select control > test movie to test the code. You see the following displa...

  • Page 172

    172 syntax and language fundamentals 4. Select control > test movie to view the elements that are displayed in the output panel. You will see the following in the output panel: [0][0] [0][1] [0][2] [1][0] [1][1] [1][2] [2][0] [2][1] [2][2] for information on using arrays, see “using arrays” on page ...

  • Page 173

    About arrays 173 2. Type the following actionscript on frame 1 of the timeline: // define the object to use as an associative array. Var someobj:object = new object(); // define a series of properties. Someobj.Myshape = "rectangle"; someobj.Myw = 480; someobj.Myh = 360; someobj.Myx = 100; someobj.My...

  • Page 174

    174 syntax and language fundamentals to create an associative array using an object constructor: 1. Create a new flash document, and save it as assocarray.Fla. 2. Add the following actionscript to frame 1 of the timeline: var monitorinfo:object = {type:"flat panel", resolution:"1600 x 1200"}; trace(...

  • Page 175

    About arrays 175 the second way to create an associative array is to use the array constructor and then use either the bracket operator ( [] ) or the dot operator ( . ) to add key and value pairs to the array. If you declare your associative array to be of type array, you cannot use an object litera...

  • Page 176

    176 syntax and language fundamentals about operators this section describes general rules about common types of operators, operator precedence, and operator associativity. Operators are characters that specify how to combine, compare, or change values in an expression. An expression is any statement...

  • Page 177

    About operators 177 ■ “about multiplicative operators” on page 187 ■ “about additive operators” on page 187 ■ “using numeric operators” on page 188 ■ “about relational operators” on page 189 ■ “about equality operators” on page 189 ■ “using relational and equality operators” on page 190 ■ “about ass...

  • Page 178

    178 syntax and language fundamentals to manipulate values using operators: 1. Create a new flash document. 2. Open the actions panel (window > actions) and type the following code into the script pane: // example one var myscore:number = 0; myscore = myscore + 1; trace("example one: " + myscore); //...

  • Page 179

    About operators 179 you can manipulate the value of a variable using operators while a condition is true . For example, you can use the increment operator ( ++ ) to increment the variable i while the condition is true. In the following code, the condition is true while i is less than the value of 10...

  • Page 180

    180 syntax and language fundamentals it’s also possible for operators to have the same precedence. In this case, the associativity determines the order in which the operators perform. You can either have left-to-right associativity or right-to-left associativity. Take a look at the multiplication op...

  • Page 181

    About operators 181 the following table lists all the actionscript operators and their associativity, from highest to lowest precedence. For more information and guidelines on using operators and parentheses, see chapter 19, “formatting actionscript syntax,” on page 764 . Operator description associ...

  • Page 182

    182 syntax and language fundamentals about using operators with strings comparison operators compare strings only if both operands are strings. An exception to this rule is the strict equality ( === ) operator. If only one operand is a string, actionscript converts both operands to numbers and perfo...

  • Page 183

    About operators 183 in this actionscript, the sort() method of the array class reorders the contents of the array alphabetically. You can see that the value “egg” comes before the value “chicken” because uppercase e comes before a lowercase c. If you want to compare the strings regardless of case, y...

  • Page 184

    184 syntax and language fundamentals the previous example shows how you can use the addition (+) and addition assignment (+=) operators to concatenate strings. Notice how the third line of code uses the addition operator to concatenate the value of the mynum variable into the text field, and the fou...

  • Page 185

    About operators 185 4. Add the following actionscript to frame 1 of the timeline: myclip.Spam = 5; trace(myclip.Spam); // 5 if you want to set a value in the myclip instance on the current timeline you can use the dot or array access operators, as demonstrated in this actionscript. If you write an e...

  • Page 186

    186 syntax and language fundamentals about postfix operators the postfix operators take one operator and either increment or decrement the operator’s value. Although these operators are unary operators, they are classified separately from the rest of the unary operators because of their higher prece...

  • Page 187

    About operators 187 all of the operators in this table have equal precedence: about multiplicative operators the multiplicative operators take two operands and perform multiplication, division, or modulo calculations. Other numeric operators include additive operators. For information on additive op...

  • Page 188

    188 syntax and language fundamentals using numeric operators you use numeric operators to add, subtract, divide, and multiply values in actionscript. You can perform different kinds of arithmetic operations. One of the most common operators is the increment operator, commonly formed as i++ . There a...

  • Page 189

    About operators 189 about relational operators the relational operators take two operands, compare their values, and return a boolean value. All of the operators in this table have equal precedence: for information on using relational operators, see “using relational and equality operators” on page ...

  • Page 190

    190 syntax and language fundamentals using relational and equality operators relational and equality operators, also called comparison operators, compare values of expressions, and they return either true or false (a boolean value). You frequently use comparison operators in conditional statements a...

  • Page 191

    About operators 191 5. Select control > test movie again. The string it equals 2 doesn’t appear in the output panel. 6. Return to the authoring environment and change: if (mynum == 2) { to if (mynum = 2) { 7. Select control > test movie again. The string it equals 2 appears in the output panel again...

  • Page 192

    192 syntax and language fundamentals to use the greater than or equal to operator in your code: 1. Select file > new and then select flash document to create a new fla file. 2. Add the following code to frame 1 of the main timeline: this.Createtextfield("mytxt", 20, 0, 0, 100, 20); mytxt.Type = "inp...

  • Page 193

    About operators 193 except for the strict equality ( === ) operator, the comparison operators compare strings only if both operands are strings. If only one of the operands is a string, both operands convert to numbers and perform a numeric comparison. For more information on strings and operators, ...

  • Page 194

    194 syntax and language fundamentals using assignment operators you can use the assignment operator (=) to assign a given value to a variable. You might assign a string to a variable, as follows: var mytext:string = "scratchycat"; you can also use the assignment operator to assign several variables ...

  • Page 195

    About operators 195 using logical operators you often use logical operators with comparison operators to determine the condition of an if statement. This is demonstrated by the next example. To use logical operators in your code: 1. Select file > new and create a new flash document. 2. Open the acti...

  • Page 196

    196 syntax and language fundamentals when you use operands, you need to be careful of the order. This is particularly the case when you use complex conditions. In the following snippet, you can see how you use the logical and operator to check that a number is between 10 and 20. Based on the result,...

  • Page 197

    About operators 197 about bitwise logical operators the bitwise logical operators take two operands and perform bit-level logical operations. The bitwise logical operators differ in precedence and are listed in the table in order of decreasing precedence: for information on using bitwise operators, ...

  • Page 198

    198 syntax and language fundamentals the first line defines an array of random names and traces them to the output panel. Then you call the array.Sort() method and specify two sort options using the constant values array.Caseinsensitive and array.Descending . The result of the sort method causes the...

  • Page 199

    About operators 199 about the conditional operator the conditional operator is a ternary operator, which means that it take three operands. The conditional operator is a short-hand method of applying the if..Else conditional statement: for information on using the conditional operator and an example...

  • Page 200

    200 syntax and language fundamentals 3. Select control > test movie. The output panel displays the following text: you got 11 out of 13 answers correct, for a score of 84.62%. When you call math.Round() in this example, the score rounds to the nearest integer (85) and is displayed in the output pane...

  • Page 201

    201 6 chapter 6 functions and methods understanding functions is important when you’re writing actionscript, creating classes, and using methods.There are several different kinds of functions that you’ll work with. In this chapter, you learn about functions and methods: how to use them in your appli...

  • Page 202

    202 functions and methods if you pass values as parameters to a function, the function can perform calculations using the supplied values. Each function has individual characteristics, and some functions require that you pass certain types or numbers of values. If you pass more parameters than the f...

  • Page 203

    About functions and methods 203 for more information on passing parameters, see “passing parameters to a function” on page 218 . There are numerous kinds of functions that you can write. For more information on writing functions, as well as links to sections on writing specific kinds of functions, s...

  • Page 204

    204 functions and methods class person { public static var numpeople:number = 0; // instance members private var _speed:number; // constructor public function person(speed:number) { person.Numpeople++; this._speed = speed; } // static methods public static function getpeople():number { return person...

  • Page 205

    About functions and methods 205 to add a top-level function call to your code, just add a single line of code in the script pane of the actions panel. For example, type the following: trace("my message"); when you test the swf file with this single line of code, the top-level trace() function is cal...

  • Page 206

    206 functions and methods you can use functions that are built into the actionscript language. They might be top level, as described in “about types of methods and functions” on page 203 ; or the function might be in a built-in class, such as math or movieclip, which you use as a method in your appl...

  • Page 207

    About functions and methods 207 writing named functions a named function is a kind of function that you commonly create in your actionscript code to carry out all kinds of actions. When you create a swf file, the named functions are compiled first, which means that you can reference the function any...

  • Page 208

    208 functions and methods 6. Select control > test movie to test the swf file. You use the function statement to create your own function in actionscript. Remember that parameters are optional; however, if you don’t have parameters, you still need to include the brackets. The content between the cur...

  • Page 209

    About functions and methods 209 for example, sometimes you need to write actionscript to handle data that loads into a swf file from the server. After you finish loading data into a swf file, you can access the data from that location. It's important to use actionscript to check whether the data has...

  • Page 210

    210 functions and methods similarly, the following code placed on any frame does not work: mywidth(); var mywidth:function = function () { trace(my_mc._width); }; however, this code works properly: var mywidth:function = function () { trace(my_mc._width); }; mywidth(); when defining a named function...

  • Page 211

    About functions and methods 211 about function literals a function literal is an unnamed function that you declare in an expression instead of in a statement. Function literals are useful when you need to use a function temporarily or to use a function in your code where you might use an expression ...

  • Page 212

    212 functions and methods defining global and timeline functions in “about functions and methods” on page 201 , you explored the different kinds of functions that are available in flash. As with variables, functions are attached to the timeline of the movie clip that defines them, and you must use a...

  • Page 213

    About functions and methods 213 targeting and calling user-defined functions user-defined functions are simply functions that you create yourself to use in applications, as opposed to functions in built-in classes that perform predefined functions. You name the functions yourself and add statements ...

  • Page 214

    214 functions and methods 3. Select control > test movie to test the flash document. For more information on named functions, see “writing named functions” on page 207 . Classes contain many user-defined functions. For information on writing functions in class files, see “using functions in flash” o...

  • Page 215

    About functions and methods 215 you can create functions in a fla file or a class file or write actionscript code that resides in a code-based component. The following examples show you how to create functions on a timeline and in a class file. The following example shows you how to create and call ...

  • Page 216

    216 functions and methods anonymous functions are often more difficult to read. Compare the following code to the preceding code. Var mycircle:function = function(radius:number):number { // function block here return (math.Pi * radius * radius); }; trace(mycircle(5)); you can also place functions in...

  • Page 218

    218 functions and methods using variables in functions local variables are valuable tools for organizing code and making it easy to understand. When a function uses local variables, it can hide its variables from all other scripts in the swf file; local variables are invoked in the scope of the body...

  • Page 219

    About functions and methods 219 after passing the parameter, you can pass a value to the function when you call the function. This value traces in the output panel, as follows: myfunc("this is what traces"); when you call the function, you should always pass the specified number of parameters unless...

  • Page 220

    220 functions and methods 3. Type the following code after the function: var area:number = getarea(10, 12); trace(area); // 120 the getarea() function call assigns the values 10 and 12 to the width and height, respectively, and you save the return value in the area instance. Then you trace the value...

  • Page 221

    About functions and methods 221 the following rules govern how to use the return statement in functions: ■ if you specify a return type other than void for a function, you must include a return statement and it must be followed by the returned value in the function. ■ if you specify a return type of...

  • Page 222

    222 functions and methods about nested functions you can call a function from inside another function. This lets you nest functions so that you can have them perform specific tasks in flash. For example, you can nest functions on a timeline to perform specific tasks on a string. Type the following c...

  • Page 223

    Understanding methods 223 you use the sorton() method of the array class to create a new array object named userarr . The array is populated by three objects that contain a first name and age, and then the array is sorted based on the value of each object’s firstname property. Finally, you loop over...

  • Page 224

    224 functions and methods when you use this actionscript, you are calling the eatcabbage() method of the eatinghabits class. 6. After the previous line of actionscript, add the following code: function eatcarrots():void { trace("tastes good"); } eatcarrots(); in this code, you write and call the eat...

  • Page 225

    225 7 chapter 7 classes this chapter introduces you to using and writing classes using actionscript 2.0. Classes are the backbone of actionscript 2.0, and are more important than they were in earlier versions of macromedia flash. You will learn how important classes are in flash throughout this chap...

  • Page 226

    226 classes for more information on working with custom and built-in classes, see the following topics: about object-oriented programming and flash . . . . . . . . . . . . . . . . . . . . . . . . . . . . .226 writing custom class files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ...

  • Page 227

    About object-oriented programming and flash 227 flash player 8, available in both flash basic 8 and flash professional 8, adds several new features to the actionscript language such as filter effects, file upload and download, and the external api. As always, actionscript 2.0 provides several powerf...

  • Page 228

    228 classes when you use a class, you can also extend existing classes and add new functionality or modify existing functionality. For example, if you create three very similar classes, you can write a base class and then write two other classes that extend the base class. These two classes can add ...

  • Page 229

    About object-oriented programming and flash 229 because these three class files are related, you might decide to put them in a package (directory) called shapes. In this case, the fully qualified class name would contain the package path, as well as the simple class name. Package paths are denoted w...

  • Page 230

    230 classes working with packages packages are directories that contain one or more class files and reside in a designated classpath directory. For example, the flash.Filters package is a directory on your hard disk that contains several class files for each filter type (such as bevelfilter, blurfil...

  • Page 231

    About object-oriented programming and flash 231 the import statement applies only to the current script (frame or object) in which it’s called. For example, suppose on frame 1 of a flash document you import all the classes in the macr.Util package. On that frame, you can reference classes in that pa...

  • Page 232

    232 classes the following sections use the analogy of a cat, demonstrating how cats might compare to oop concepts. Objects think of a real-world object, such as a cat. A cat could be said to have properties (or states), such as name, age, and color; a cat also has behaviors such as sleeping, eating,...

  • Page 233

    About object-oriented programming and flash 233 one of the major benefits of using a superclass/subclass structure is that it is easier to reuse similar code between various classes. For example, you could build a superclass called animal, which contains common characteristics and behaviors of all a...

  • Page 234

    234 classes encapsulation in elegant object-oriented design, objects are seen as “black boxes” that contain, or encapsulate, functionality. A programmer should be able to interact with an object by knowing only its properties, methods, and events (its programming interface), without knowing the deta...

  • Page 235

    Writing custom class files 235 writing custom class files the following example examines the parts of a class file. You learn how to write a class, and how you can modify the class to extend the ways that you can use it with flash. You learn about the parts of a class and how to import them as well ...

  • Page 236

    236 classes to create class files: 1. Select file > new and then select actionscript file, and then click ok. 2. Select file > save as and name the new file user.As. 3. Type the following actionscript code into the script window: /** user class author: john doe version: 0.8 modified: 08/21/2005 copy...

  • Page 237

    Writing custom class files 237 the user class’s constructor statement takes two parameters: p_username and p_password , which are copied into the class’s private instance variables __username and __password . The remainder of the code in the class defines the getter and setter properties for the pri...

  • Page 238

    238 classes a sample file on your hard disk demonstrates how to create a dynamic menu with xml data and a custom class file. The sample calls the actionscript xmlmenu() constructor and passes it two parameters: the path to the xml menu file and a reference to the current timeline. The rest of the fu...

  • Page 239

    About working with custom classes in an application 239 for more information on working with custom classes, see the following topics: ■ “about importing class files” on page 239 ■ “using a class file in flash” on page 244 ■ “using methods and properties from a class file” on page 245 ■ “about class...

  • Page 240

    240 classes when you import class files, the following rules apply: ■ the import statements can exist in the following locations: ■ anywhere before the class definition in class files ■ anywhere in frame or object scripts ■ anywhere in actionscript files that you include in an application (using the...

  • Page 241

    About working with custom classes in an application 241 when you create an actionscript class file, you need to save the file to one of the directories specified in the classpath or a subdirectory therein. (you can modify the classpath to include the desired directory path). Otherwise, flash won’t b...

  • Page 242

    242 classes the relative path portion of the global classpath is denoted by a single dot ( . ) and points to the current document directory. Be aware that relative classpaths can point to different directories, depending on the location of the document being compiled or published. You can use the fo...

  • Page 243

    About working with custom classes in an application 243 for example, you might create a directory such as the following for your custom classes: ■ windows: hard disk\documents and settings\user\custom classes. ■ macintosh: hard disk/users/user/custom classes. Then, you would add this path to the lis...

  • Page 244

    244 classes using a class file in flash to create an instance of an actionscript class, use the new operator to invoke the class’s constructor function. The constructor function always has the same name as the class and returns an instance of the class, which you typically assign to a variable. For ...

  • Page 245

    About working with custom classes in an application 245 using methods and properties from a class file in oop, members (properties or methods) of a class can be instance members or class members. Instance members are created for each instance of the class; they are defined to the prototype of the cl...

  • Page 246

    246 classes to use the picture and pictureclass classes in a fla file: 1. Select file > new and then select actionscript file. Save the document as picture.As and then click ok. You write your custom picture class in this document. 2. Type the following actionscript code into the script window: /** ...

  • Page 247

    About working with custom classes in an application 247 5. Type the following actionscript code into frame 1 of the timeline: var picture1:picture = new picture("http://www.Helpexamples.Com/flash/ images/image1.Jpg"); picture1.Showinfo(); this.Createemptymovieclip("img_mc", 9); img_mc.Loadmovie(pict...

  • Page 248

    248 classes public methods and properties the public keyword specifies that a variable or function is available to any caller. Because variables and functions are public by default, the this keyword is used primarily for stylistic and readability benefits, indicating that the variable exists in the ...

  • Page 249

    About working with custom classes in an application 249 if you want to add a private property to the previous class, you simply use the keyword private before the var keyword. If you attempt to access the private id property from outside the sample class, you get a compiler error and a message in th...

  • Page 250

    250 classes for example, the top-level math class consists only of static methods and properties. To call any of its methods, you don’t create an instance of the math class. Instead, you simply call the methods on the math class itself. The following code calls the sqrt() method of the math class: v...

  • Page 251

    About working with custom classes in an application 251 similarly, any function declared within a class is considered a method of the class. In the person class example, you can create a method called getinfo() : class person { public var age:number; public var username:string; public function getin...

  • Page 252

    252 classes for more information on class members (also called static properties), see “static methods and properties” on page 249 . A sample file on your hard disk demonstrates how to create a dynamic menu with xml data and a custom class file. The sample calls the actionscript xmlmenu() constructo...

  • Page 253

    About working with custom classes in an application 253 to use the singleton design pattern: 1. Select file > new and then select actionscript file. Save the document as singleton.As. 2. Type the following actionscript code into the script window: /** singleton class author: john doe version: 0.53 m...

  • Page 254

    254 classes remember not to use too few or too many class files for your application, because doing so can lead to poorly designed class files, which are not beneficial to the application’s performance or to your workflow. You should always attempt to use class files instead of placing code in other...

  • Page 255

    About working with custom classes in an application 255 5. In widget_test.Fla, type the following code into frame 1 of the timeline: // before you create any instances of the class, // widget.Widgetcount is zero (0). Trace("widget count at start: " + widget.Widgetcount); // 0 var widget1:widget = ne...

  • Page 256

    256 classes when you write classes, you are always encouraged to make as many as possible of your instance variables private and add getter and setter methods accordingly. This is because there are several times when you may not want to let users change certain variables within your classes. For exa...

  • Page 257

    About working with custom classes in an application 257 3. Save the actionscript document as login.As. As you can see, getusername() returns the current value of username , and setusername() sets the value of username to the string parameter passed to the method. 4. Select file > new and then select...

  • Page 258

    258 classes to use implicit getter and setter methods: 1. Select file > new and then select actionscript file, and then click ok. 2. Type the following code into the script window: class login2 { private var __username:string; public function login2(username:string) { this.__username = username; } p...

  • Page 259

    About working with custom classes in an application 259 6. Save the flash document and select control > test movie to test the file. Flash displays the following information in the output panel: rickym enriquei about dynamic classes adding the dynamic keyword to a class definition specifies that obj...

  • Page 260

    260 classes 6. Add the following code to create a new instance of the person class ( firstperson ), and try to assign a value to a property called haircolor (which doesn’t exist in the person class): var firstperson:person = new person(); firstperson.Haircolor = "blue"; // error. There is no propert...

  • Page 261

    About working with custom classes in an application 261 8. Save your changes to the person2_test.Fla file. 9. Select control > test movie to test the code. Because the custom flash class is dynamic, you can add methods and properties to the class at runtime (when the swf file plays). When you test t...

  • Page 262

    262 classes an example of encapsulation in flash would be setting all your member and class variables to private and forcing people who implement your classes to access these variables using getter and setter methods. Performing encapsulation this way ensures that if you ever need to change the stru...

  • Page 263

    Example: writing custom classes 263 example: writing custom classes now that you’ve explored the basics of a class file, and what kinds of things it contains, it’s time to learn some of the general guidelines for creating a class file. The first example in this chapter shows you how to write classes...

  • Page 264

    264 classes a sample file on your hard disk demonstrates how to create a dynamic menu with xml data and a custom class file. The sample calls the actionscript xmlmenu() constructor and passes it two parameters: the path to the xml menu file and a reference to the current timeline. The rest of the fu...

  • Page 265

    Example: writing custom classes 265 this code declares the same variable inside an inner block. ■ do not assign many variables to a single value in a statement, because it is difficult to read, as you can see in the following actionscript code samples: // bad form xpos = ypos = 15; or // bad form cl...

  • Page 266

    266 classes creating and packaging your class files in this section, you create, name, and package your class files for this example ( “example: writing custom classes” on page 263 ). The following sections show you how to write complete (yet simple) class files. For detailed information on packages...

  • Page 267

    Example: writing custom classes 267 6. Save the classa.As actionscript document. 7. Select file > new and then select actionscript file, and then click ok. 8. Select file > save as, name the new file classb.As, and save it in the same directory as classa.As created in an earlier step. 9. Type the fo...

  • Page 268

    268 classes 2. Create the required directory structure after you’ve chosen a package name. For example, if your package was named com.Macromedia.Utils , you would need to create a directory structure of com/macromedia/utils and place your classes in the utils folder. 3. Use the com.Macromedia.Utils ...

  • Page 269

    Example: writing custom classes 269 consider the following points when you write constructor functions: ■ if no constructor function is explicitly declared—that is, if you don’t create a function whose name matches that of the class—the compiler automatically creates an empty constructor function fo...

  • Page 270

    270 classes 5. Save both actionscript files before you proceed. To continue writing your class file, see “adding methods and properties” on page 270 . Adding methods and properties to create the properties for the classa and classb classes, use the var keyword to define variables. To add properties ...

  • Page 271

    Example: writing custom classes 271 a class’s members consist of properties (variable declarations) and methods (function definitions). You must declare and define all properties and methods inside the class body (the curly braces [ {} ]); otherwise, an error occurs during compilation. For informati...

  • Page 272

    272 classes you can initialize properties inline—that is, when you declare them—with default values, as shown in the following example: class person { var age:number = 50; var username:string = "john doe"; } when you initialize properties inline, the expression on the right side of an assignment mus...

  • Page 273

    Example: writing custom classes 273 controlling member access in your classes by default, any property or method of a class can be accessed by any other class: all members of a class are public by default. However, in some cases you might want to protect data or methods of a class from access by oth...

  • Page 274

    274 classes this previous code sets both methods (the classa constructor and the dosomething() method) as public, meaning that they can be accessed by external scripts. The static _classname variable is set as private, meaning the variable can be accessed only from within the class and not from exte...

  • Page 275

    Example: writing custom classes 275 if you have to document additional information that does not fit into the documentation comments, use implementation comments (in the format of block comments or single-line comments, as described in “about comments” on page 131 ). Implementation comments, if you ...

  • Page 276

    276 classes you might also add the block, single-line, or trailing comments within the class’s code. For information on writing good comments within your code, see “writing good comments” on page 743 . For general information about comments, see “single-line comments” on page 132 , “multiline commen...

  • Page 277

    Example: using custom class files in flash 277 to specify package paths, use dot ( . ) notation to separate package directory names. Package paths are hierarchical; that is, each dot represents a nested directory. For example, suppose you create a class named classname that resides in a com/macromed...

  • Page 278

    278 classes to import a class or package: 1. Open the file called package_test.Fla. 2. Type the following code into the script window: import com.Macromedia.Utils.*; var a = new classa(); // classa constructor var b = new classb(); // classb constructor the previous block of code begins by importing...

  • Page 279

    Assigning a class to symbols in flash 279 to create a new instance of the classa and classb classes: 1. Open the file called package_test.Fla. 2. Type the following boldface code into the script window: import com.Macromedia.Utils.*; var a:classa = new classa(); // classa constructor a.Dosomething()...

  • Page 280

    280 classes 5. Select file > new and then select flash document to create a new fla file, and then click ok. 6. Select file > save as, name the file animal_test.Fla, and save the file to the same folder as the animal.As file you created in step 2. 7. Select insert > new symbol to launch the create n...

  • Page 281

    Compiling and exporting classes 281 2. Rename the default layer to content, drag a progressbar component from the components panel to the stage, and give it an instance name of my_pb. 3. Create a new layer, drag it above the content layer, and rename it actions. 4. Add the following actionscript cod...

  • Page 282

    282 classes 15. Select control > test movie to test the flash document. If the components load too quickly, select view > simulate download from the swf file. Flash simulates downloading the flash document at a lower speed, which allows you to see the progress bar component animate as the class file...

  • Page 283

    Understanding classes and scope 283 to delete aso files: if you are editing a fla file, and you want to delete an aso file, select one of the following in the authoring environment: ■ select control > delete aso files to delete aso files and continue editing. ■ select control > delete aso files and ...

  • Page 284

    284 classes to understand scope and external class files: 1. Select file > new and then select actionscript file, and then click ok. 2. Type or paste the following code into the script window: /** product class product.As */ class product { private var productsxml:xml; // constructor // targetxmlstr...

  • Page 285

    Understanding classes and scope 285 3. Save the previous actionscript code as product.As. 4. Create a new flash document named testproduct.Fla in the same directory. 5. Select frame 1 of the main timeline. 6. Type the following actionscript into the actions panel: var myproduct:product = new product...

  • Page 286

    286 classes 4. Select file > new and then select flash document to create a new fla file, and save the fla file in the same directory as user.As. 5. Type the following actionscript code in frame 1 of the timeline: trace(user.Instances); // 0 var user1:user = new user(); trace(user.Instances); // 1 v...

  • Page 287

    About top-level and built-in classes 287 you can find the actionscript classes installed on your hard disk. You can find the classes folders here: ■ windows: hard disk\documents and settings\user\local settings\application data\macromedia\flash 8\language\configuration\classes. ■ macintosh: hard dis...

  • Page 288

    288 classes other language elements there are other language elements that make up actionscript, outside of classes. These include directives, constants, global functions, global properties, operators, and statements. For information on how to use each of these language elements, see the following t...

  • Page 289

    About top-level and built-in classes 289 button the button class provides methods, properties, and event handlers for working with buttons. See button.Note that the built-in button class is different from the button component class, associated with the version 2 component, button. Camera the camera ...

  • Page 290

    290 classes loadvars the loadvars class lets you transfer variables between a swf file and a server in name-value pairs. See loadvars. Localconnection the localconnection class lets you develop swf files that send instructions to each other without using the fscommand() method or javascript. See loc...

  • Page 291

    About top-level and built-in classes 291 sharedobject the sharedobject class offers persistent local data storage on the client computer, similar to cookies. This class offers real-time data sharing between objects on the client’s computer. See sharedobject. Sound the sound class provides control ov...

  • Page 292

    292 classes the flash.Display package the flash.Display package contains the bitmapdata class that you can use to build visual displays. The flash.External package the flash.External package lets you communicate with the flash player container using actionscript code. For example, if you embed a swf...

  • Page 293

    About top-level and built-in classes 293 the flash.Filters package the flash.Filters package contains classes for the bitmap filter effects available in flash player 8. Filters let you apply rich visual effects, such as blur, bevel, glow, and drop shadows, to image and movieclip instances. For more ...

  • Page 294

    294 classes the flash.Geom package the flash.Geom package contains geometry classes, such as points, rectangles, and transformation matrices. These classes support the bitmapdata class and the bitmap caching feature. For more information on each class, see the cross references provided in the follow...

  • Page 295

    About top-level and built-in classes 295 the flash.Text package the flash.Text package contains the textrenderer class for working with advanced anti- aliasing in available in flash player 8. The mx.Lang package the mx.Lang package contains the locale class for working with multilanguage text. The s...

  • Page 296

    296 classes the textfield package contains the stylesheet class that you can use to apply css styles to text. About working with built-in classes in object-oriented programming (oop), a class defines a category of object. A class describes the properties (data) and behavior (methods) for an object, ...

  • Page 297

    About working with built-in classes 297 for example, the following code creates a new sound object: var song_sound:sound = new sound(); in some cases, you don’t need to create an instance of a class to use its properties and methods. For more information, see “about class (static) members” on page 2...

  • Page 298

    298 classes about calling built-in object methods you call an object’s method by using the dot ( . ) operator followed by the method. For example, the following code creates a new sound object and calls its setvolume() method: var my_sound:sound = new sound(this); my_sound.Setvolume(50); for example...

  • Page 299

    About working with built-in classes 299 to exclude classes from compilation: 1. Create a new xml file. 2. Name the xml file fla_filename_exclude.Xml, where fla_filename is the name of your fla file without the extension. For example, if your fla file is sellstocks.Fla, the xml filename must be sells...

  • Page 300

    300 classes to select a different frame for the classes to load into a swf file: 1. Select file > publish settings. 2. Select the flash tab, and click the settings button. 3. In the export frame for classes text box, type the number of a new frame to determine when to load the classes. 4. Click ok. ...

  • Page 301

    301 8 chapter 8 inheritance in chapter 7, “classes,” you learned how to write class files and how classes help you organize code into external files. The chapter also demonstrated how you can organize class files into related packages. This chapter aims to show you how to write more advanced classes...

  • Page 302

    302 inheritance your subclass typically defines additional methods and properties that you can use in your application, hence it extends the superclass. Subclasses can also override (provide their own definitions for) methods inherited from a superclass. If a subclass overrides a method inherited fr...

  • Page 303

    About writing subclasses in flash 303 about writing subclasses in flash in object-oriented programming, a subclass can inherit the properties and methods of another class, called the superclass. You can extend your own custom classes as well as many of the core and flash player actionscript classes....

  • Page 304

    304 inheritance if you don’t place a call to super() in the constructor function of a subclass, the compiler automatically generates a call to the constructor of its immediate superclass with no parameters as the first statement of the function. If the superclass doesn’t have a constructor, the comp...

  • Page 305

    About writing subclasses in flash 305 5. In subwidget.As, type the following code into the script window: class subwidget extends widget { public function subwidget() { trace("creating subwidget #" + widget.Widgetcount); } } 6. Save your changes to subwidget.As. 7. Create a new fla file, and save it...

  • Page 306

    306 inheritance if you don’t specify the class name for the widget.Widgetcount property but instead refer only to widgetcount , the actionscript 2.0 compiler resolves the reference to widget.Widgetcount and correctly exports that property. Similarly, if you refer to the property as subwidget.Widgetc...

  • Page 307

    About writing subclasses in flash 307 3. Save your changes to the actionscript document. The widget class now defines a constructor and a public method called dosomething() . 4. Create a new actionscript file named subwidget.As and save it in the same directory as widget.As. 5. In subwidget.As, type...

  • Page 308

    308 inheritance 11. Open the subwidget class and add a new method named dosomething() . Modify your class so that it matches the following code (add the code that’s in boldface): class subwidget extends widget { public function subwidget() { trace("creating subwidget # " + widget.Widgetcount); dosom...

  • Page 309

    Using polymorphism in an application 309 for example, you might start with a class called mammal that has play() and sleep() methods. You then create cat, monkey, and dog subclasses to extend the mammal class. The subclasses override the play() method from the mammal class to reflect the habits of t...

  • Page 310

    310 inheritance the previous class defines two private variables, _gender and _name , which are used to store the animal’s gender and mammal type. Next, the mammal constructor is defined. The constructor takes a single parameter, gender , which it uses to set the private _gender variable defined ear...

  • Page 311

    Using polymorphism in an application 311 8. In dog.As, type the following actionscript code into the script window: class dog extends mammal { // constructor public function dog(gender:string) { super(gender); speciesname = "dog"; } public function play():string { return "fetch a stick."; } } notice...

  • Page 312

    312 inheritance 14. In mammaltest.Fla, type the following actionscript code into frame 1 of the main timeline: var mammals_arr:array = new array(); this.Createtextfield("info_txt", 10, 10, 10, 450, 80); info_txt.Html = true; info_txt.Multiline = true; info_txt.Border = true; info_txt.Wordwrap = true...

  • Page 313

    313 9 chapter 9 interfaces in object-oriented programming (oop), an interface is a document that lets you declare (but not define) the methods that must appear within a class. When you work in teams of developers, or build larger applications in flash, interfaces can be very beneficial during develo...

  • Page 314

    314 interfaces an interface is not a class; however, this is not altogether true in actionscript at runtime because an interface is abstract. Actionscript interfaces do exist at runtime to allow type casting (changing an existing data type to a different type). The actionscript 2.0 object model does...

  • Page 315

    About interfaces 315 for more information on using interfaces, see the following sections: ■ “about the interface keyword” on page 315 ■ “about naming interfaces” on page 315 ■ “defining and implementing interfaces” on page 316 about the interface keyword the interface keyword defines an interface. ...

  • Page 316

    316 interfaces defining and implementing interfaces the process for creating an interface is the same as for creating a class. Like classes, you can define interfaces only in external actionscript files. At a minimum, the workflow for creating an interface involves the following steps: ■ defining a ...

  • Page 317

    About interfaces 317 4. Create a new actionscript file and save it as myclass.As in the same directory as the imyinterface.As. 5. In the myclass class file, type the following actionscript code into the script window: class myclass { } in order to instruct the custom class (myclass) to use your inte...

  • Page 318

    318 interfaces interface files cannot contain any variable declarations or assignments. Functions that you declare in an interface cannot contain curly braces. For example, the following interface does not compile: interface ibadinterface { // compiler error. Variable declarations not allowed in int...

  • Page 319

    Creating interfaces as data types 319 5. In box.As, type the following actionscript code into the script window: class box implements imovable { public var xpos:number; public var ypos:number; public function box() { } public function moveup():void { trace("moving up"); // method definition } public...

  • Page 320

    320 interfaces this actionscript code checks whether the newbox instance implements the imovable interface before you call the moveup() method on the object. 11. Save the flash document, and then select control > test movie to test the swf file. Because the box instance implements the imovable inter...

  • Page 321

    Example: using interfaces 321 8. In classa.As, type the following actionscript code into the script window: class classa implements ib { // f1() and f2() are defined in interface ia. Public function f1():void { } public function f2():void { } // f8() and f9() are defined in interface ib, which exten...

  • Page 322

    322 interfaces 5. In flashpaper.As, type the following actionscript code into the script window: class flashpaper implements idocumentation { } 6. Save the changes that you made to the actionscript file. 7. Click the check syntax button for your actionscript class. You see an error that’s similar to...

  • Page 323

    Example: creating a complex interface 323 11. Save your changes to the interface file, and then reopen the flashpaper.As document. 12. Click the check syntax button, and you see a new error message in the output panel: **error** path\flashpaper.As: line 1: the class must implement method 'addcomment...

  • Page 324

    324 interfaces 3. In interface.As, type the following actionscript code into the script window: // filename: interfacea.As interface interfacea { public function k():number; public function n(z:number):number; } 4. Save the actionscript document and then create a new actionscript document named clas...

  • Page 325

    Example: creating a complex interface 325 10. In classc.As, type the following actionscript code into the script window: // filename: classc.As class classc implements interfacea { public function k():number { return 25; } // **error** the class must also implement method 'n' from interface 'interfa...

  • Page 326

    326 interfaces 16. In classdtest.Fla, add the following actionscript code on frame 1 of the timeline: // filename: classdtest.Fla import classd; var myd:classd = new classd(); trace(myd.K()); // 15 trace(myd.N(7)); // 49 myd.O(); // o 17. Save your changes to the classdtest.Fla file and then select ...

  • Page 327

    Example: creating a complex interface 327 23. In classetest.Fla, type the following actionscript code on frame 1 of the timeline: // filename: classetest.Fla import classe; var mye:classe = new classe(); trace(mye.K()); // 15 trace(mye.N(7)); // 12 mye.O(); // o mye.P(); // p 24. Save the flash docu...

  • Page 328

    328 interfaces.

  • Page 329

    329 10 chapter 10 handling events events are actions that occur while a swf file is playing. An event such as a mouse click or a keypress is called a user event because it occurs as a result of direct user interaction. An event that flash player generates automatically, such as the initial appearanc...

  • Page 330

    330 handling events for more information on handling events, see the following sections: using event handler methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330 using event listeners . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ....

  • Page 331

    Using event handler methods 331 for example, suppose you have a button named next_btn on the stage. The following code assigns a function to the button’s onpress event handler; this function advances the playhead to the next frame in the current timeline: next_btn.Onpress = function () { nextframe()...

  • Page 332

    332 handling events event handlers for runtime objects you can also assign functions to event handlers for objects you create at runtime. For example, the following code creates a new movie clip instance ( newclip_mc ) and then assigns a function to the clip’s onpress event handler: this.Attachmovie...

  • Page 333

    Using event listeners 333 the listener-broadcaster model for events, unlike event handler methods, lets you have multiple pieces of code listen to the same event without conflict. Event models that do not use the listener/broadcaster model, such as xml.Onload() , can be problematic when various piec...

  • Page 334

    334 handling events the code starts with an object, listenerobject , with a property eventname . Your listener object can be any object, such as an existing object, movie clip, or button instance on the stage, or it can be an instance of any actionscript class. For example, a custom movie clip could...

  • Page 335

    Using event listeners with components 335 5. To create an object that listens for focus notification from the selection class, enter the following code in the actions panel: // creates listener object, focuslistener. Var focuslistener:object = new object(); // defines function for listener object. F...

  • Page 336

    336 handling events 3. Add the following code to frame 1 of the main timeline; system.Security.Allowdomain("http://www.Helpexamples.Com"); var loaderlistener:object = new object(); loaderlistener.Progress = function(evt_obj:object):void { trace(evt_obj.Type); // progress trace("\t" + evt_obj.Target....

  • Page 337

    Using button and movie clip event handlers 337 instead of using a listener object, as in the first procedure under “using event listeners with components” on page 335 , you can use a custom function. The code in the previous example could be rewritten as follows: system.Security.Allowdomain("http://...

  • Page 338

    338 handling events you can attach onclipevent() and on() only to movie clip instances that have been placed on the stage during authoring. You cannot attach onclipevent() or on() to movie clip instances that are created at runtime (using the attachmovie() method, for example). To attach event handl...

  • Page 339

    Using button and movie clip event handlers 339 to use an on handler and onpress event handler: 1. Create a new flash document and save it as handlers.Fla. 2. Select the rectangle tool and draw a large square on the stage. 3. Select the selection tool, double-click the square on the stage, and press ...

  • Page 340

    340 handling events specifying events for on or onclipevent methods to use an on() or onclipevent() handler, attach it directly to an instance of a button or movie clip on the stage and specify the event you want to handle for that instance. For a complete list of events supported by the on() and on...

  • Page 341

    Using button and movie clip event handlers 341 attaching or assigning multiple handlers to one object you can also attach more than one handler to an object if you want different scripts to run when different events occur. For example, you could attach the following onclipevent() handlers to the sam...

  • Page 342

    342 handling events 3. Select control > test movie to test the document. The image loads into the img_mc instance, and the onpress() and onrelease() event handlers let you drag the image around the stage. Broadcasting events from component instances for any component instance, you can specify how an...

  • Page 343

    Event handler scope 343 9. Rename the new layer actions and add the following actionscript to frame 1 of the movie clip’s timeline: stop(); 10. Select frame 10, all three layers, and select insert > timeline > keyframe. 11. Add a stop() action on frame 10 of the actions layer, and add a frame label ...

  • Page 344

    344 handling events for example, consider the following two event handlers. The first is an onpress event handler associated with a movie clip named clip_mc . The second is an on() handler attached to the same movie clip instance. // attached to clip_mc's parent clip timeline: clip_mc.Onpress = func...

  • Page 345

    Event handler scope 345 within an event handler or event listener definition, the same play() function applies to the timeline that contains the function definition. For example, suppose you declare the following my_mc.Onpress event handler method on the timeline that contains the my_mc movie clip i...

  • Page 346

    346 handling events this code cannot work correctly because there is a problem involving scope with the event handlers, and what this refers to is confused between the onload event handler and the class. The behavior that you might expect in this example is that the onloadvarsdone() method will be i...

  • Page 347

    Using the delegate class 347 scope of the this keyword the this keyword refers to the object in the currently executing scope. Depending on what type of event handler technique you use, this can refer to different objects. Within an event handler or event listener function , this refers to the objec...

  • Page 348

    348 handling events to use the delegate class to listen for events: 1. Create a new flash document and save it as delegate.Fla. 2. Drag a button component from the user interface folder of the components panel to the library. You add and position the button instance on the stage using actionscript i...

  • Page 349

    Using the delegate class 349 the remaining three sections of code each create a new button component instance on the stage, reposition the instance, and add an event listener for the click event. The first button adds an event listener for the click event and passes a reference to a click handler fu...

  • Page 350

    350 handling events.

  • Page 351

    351 11 chapter 11 working with movie clips movie clips are like self-contained swf files that run independently of each other and the timeline that contains them. For example, if the main timeline has only one frame and a movie clip in that frame has ten frames, each frame in the movie clip plays wh...

  • Page 352

    352 working with movie clips for more information on movie clips, see the following topics: about controlling movie clips with actionscript . . . . . . . . . . . . . . . . . . . . . . . . . . . . .352 calling multiple methods on a single movie clip . . . . . . . . . . . . . . . . . . . . . . . . . ....

  • Page 353

    About controlling movie clips with actionscript 353 in the first statement, play() moves the playhead in the mymovieclip instance. In the second statement, gotoandplay() sends the playhead in childclip (which is a child of the instance parentclip ) to frame 3 and continues to move the playhead. Glob...

  • Page 354

    354 working with movie clips you can find samples of photo gallery applications on your hard disk.These files provide examples of how to use actionscript to control movie clips dynamically while loading image files into a swf file, which includes scripted animation. You can find the sample source fi...

  • Page 355

    Loading and unloading swf files 355 loading and unloading swf files to play additional swf files without closing flash player, or to switch swf files without loading another html page, you can use one of the following options: ■ the global loadmovie() function or loadmovie() method of the movieclip ...

  • Page 356

    356 working with movie clips specifying a root timeline for loaded swf files the _root actionscript property specifies or contains a reference to the root timeline of a swf file. If a swf file has multiple levels, the root timeline is on the level that contains the currently executing script. For ex...

  • Page 357

    Changing movie clip position and appearance 357 this step ensures that any references to _root in contents.Swf—or any swf file loaded into target_mc —refers to its own timeline, not to the actual root timeline of container.Swf. Now when you click the button, " tim " appears. Alternatively, the autho...

  • Page 358

    358 working with movie clips some properties, called read-only properties, have values that you can read but cannot set. (these properties are specified as read-only in their actionscript 2.0 language reference entries.) the following are read-only properties: _currentframe , _droptarget , _frameslo...

  • Page 359

    Dragging movie clips 359 ■ on the macintosh, browse to macintosh hd/applications/macromedia flash 8/samples and tutorials/samples/actionscript/galleries. Dragging movie clips you can use the global startdrag() function or the movieclip.Startdrag() method to make a movie clip draggable. For example, ...

  • Page 360

    360 working with movie clips creating movie clips at runtime in addition to creating movie clip instances in the flash authoring environment, you can also create movie clip instances at runtime in the following ways: ■ “creating an empty movie clip” on page 360 ■ “duplicating or removing a movie cli...

  • Page 361

    Creating movie clips at runtime 361 for example, the following code creates a new child movie clip named new_mc at a depth of 10 in the movie clip named parent_mc : parent_mc.Createemptymovieclip("new_mc", 10); the following code creates a new movie clip named canvas_mc on the root timeline of the s...

  • Page 362

    362 working with movie clips duplicating or removing a movie clip to duplicate or remove movie clip instances, use the duplicatemovieclip() or removemovieclip() global functions, or the movieclip class methods of the same name. The duplicatemovieclip() method creates a new instance of an existing mo...

  • Page 363

    Creating movie clips at runtime 363 3. In the library panel, select linkage from the library panel pop-up menu. The linkage properties dialog box appears. 4. For linkage, select export for actionscript. 5. For identifier, enter an id for the movie clip. By default, the identifier is the same as the ...

  • Page 364

    364 working with movie clips for more information, see attachmovie ( movieclip.Attachmovie method) in the actionscript 2.0 language reference. Adding parameters to dynamically created movie clips when you use movieclip.Attachmovie() and movieclip.Duplicatemovie() to create or duplicate a movie clip ...

  • Page 365

    Adding parameters to dynamically created movie clips 365 6. Select edit > edit document to return to the main timeline. 7. Select the movie clip symbol in the library, and select linkage from the library pop-up menu. The linkage properties dialog box appears. 8. Select the export for actionscript op...

  • Page 366

    366 working with movie clips managing movie clip depths every movie clip has its own z-order space that determines how objects overlap within its parent swf file or movie clip. Every movie clip has an associated depth value, which determines if it renders in front of or behind other movie clips in t...

  • Page 367

    Managing movie clip depths 367 determining the next highest available depth to determine the next highest available depth within a movie clip, use movieclip.Getnexthighestdepth() . The integer value returned by this method indicates the next available depth that will render in front of all other obj...

  • Page 368

    368 working with movie clips determining the depth of an instance to determine the depth of a movie clip instance, use movieclip.Getdepth() . The following code iterates over all the movie clips on a swf file’s main timeline and shows each clip’s instance name and depth value in the output panel: fo...

  • Page 369

    About caching and scrolling movie clips with actionscript 369 11. Select control > test movie to test the document. When you click the instances on the stage, they swap depths. You’ll see the two instances change which clip is on top of the other clip. For more information, see swapdepths (movieclip...

  • Page 370

    370 working with movie clips the following table contains brief descriptions of the new properties for movie clip instances: these three properties are independent of each other, however, the opaquebackground and scrollrect properties work best when an object is cached as a bitmap. You only see perf...

  • Page 371

    About caching and scrolling movie clips with actionscript 371 ■ on the macintosh, browse to macintosh hd/applications/macromedia flash 8/samples and tutorials/samples/actionscript/cachebitmap. You can also find a sample source file that shows you how to apply bitmap caching to scrolling text. Find t...

  • Page 372

    372 working with movie clips scrolling text field an application that displays a large amount of text in a scrolling text field. You can place the text field in a movie clip that you set as scrollable with scrolling bounds (the scrollrect property). This enables fast pixel scrolling for the specifie...

  • Page 373

    About caching and scrolling movie clips with actionscript 373 ■ use surfaces for movie clip instances that are largely static (nonanimating). You can drag or move the instance, but the contents of the instance should not animate or change a lot. For example, if you rotate or transform an instance, t...

  • Page 374

    374 working with movie clips 9. Select frame 1 of the timeline, and then add the following actionscript to the actions panel: import mx.Transitions.Tween; var star_array:array = new array(); for (var i:number = 0; i makestar(); } function makestar():void { var depth:number = this.Getnexthighestdepth...

  • Page 375

    About caching and scrolling movie clips with actionscript 375 for examples of scrolling movie clips, see scrollrect (movieclip.Scrollrect property) in the actionscript 2.0 language reference. For information on alpha channel masking, which requires you to set the cacheasbitmap property to true , see...

  • Page 376

    376 working with movie clips 5. Select the instance on the stage, and then type my_mc into the instance name text box in the property inspector. 6. Select frame 1 of the timeline, and then type the following code into the actions panel: /* when you set cacheasbitmap, the internal bitmap is opaque an...

  • Page 377

    Using movie clips as masks 377 6. In the actions panel, enter the following code: system.Security.Allowdomain("http://www.Helpexamples.Com"); this.Createemptymovieclip("img_mc", 10); var mcllistener:object = new object(); mcllistener.Onloadinit = function(target_mc:movieclip):void { target_mc.Setmas...

  • Page 378

    378 working with movie clips in the actions panel, the following code is placed on frame 1 of the timeline: flower_maskee.Setmask(oval_mask); when you test the document (control > test movie), the maskee is alpha blended by using the mask. Handling movie clip events movie clips can respond to user e...

  • Page 379

    Initializing class properties 379 3. Enter the following code in your script file: // moveright class -- moves clip to the right 20 pixels when clicked class moveright extends movieclip { public function onpress() { this._x += 20; } } 4. Save the document as moveright.As in the balltest directory. T...

  • Page 380

    380 working with movie clips for example, the following class named moverightdistance is a variation of the moveright class (see “assigning a class to a movie clip symbol” on page 378 ). The difference is a new property named distance , whose value determines how many pixels a movie clip moves each ...

  • Page 381

    381 12 chapter 12 working with text and strings many of the applications, presentations, and graphics that you create with macromedia flash professional 8 or macromedia flash basic 8 include some kind of text. You can use many different kinds of text. You might use static text in your layouts, but d...

  • Page 382

    382 working with text and strings device fonts device fonts are special fonts in flash that are not embedded in a swf file. Instead, flash player uses whatever font on the local computer that most closely resembles the device font. Because font outlines are not embedded, a swf file size is smaller t...

  • Page 383

    About text fields 383 about text fields a dynamic or input text field is a textfield object (an instance of the textfield class). When you create a text field in the authoring environment, you can assign it an instance name in the property inspector. You can use the instance name in actionscript sta...

  • Page 384

    384 working with text and strings in flash player 7 and later, you can apply cascading style sheet (css) styles to text fields using the textfield.Stylesheet class. You can use css styles to style built-in html tags, define new formatting tags, or apply styles. For more information on using css, see...

  • Page 385

    About text fields 385 ■ on the macintosh, browse to macintosh hd/applications/macromedia flash 8/samples and tutorials/samples/actionscript/textfields. Assigning text to a text field at runtime when you build applications with flash, you may want to load text from an external source, such as a text ...

  • Page 386

    386 working with text and strings to create an html-formatted text field: use one of the following two steps to enable html formatting for the text field: ■ select a text field and click render text as html in the property inspector. ■ set the text field’s html property to true by using actionscript...

  • Page 387

    About text fields 387 do not confuse a text field’s instance name with its variable name, however. A text field’s variable name is a variable reference to the text contained by that text field; it is not a reference to an object. For example, if you assigned a text field the variable name mytextvar ...

  • Page 388

    388 working with text and strings 3. To access the methods and properties of the newly created text field, use the instance name specified in the first parameter of the createtextfield() method. For example, the following code creates a new text field named test_txt , and modifies its properties to ...

  • Page 389

    About text fields 389 about manipulating text fields you can manipulate text fields that you create in a fla file in several ways. You can manipulate a text field as long as you assign an instance name in the property inspector, or you can assign one with code if you use code to create the field. Th...

  • Page 390

    390 working with text and strings you can find sample source files that demonstrate how to work with text fields using actionscript. The source files are called textfieldsa.Fla and textfieldsb.Fla, and you can find them in the samples folder on your hard disk: ■ in windows, browse to boot drive\prog...

  • Page 391

    About text fields 391 to automatically resize text fields based on content: 1. Create a new flash document and save it as resizetextauto.Fla. 2. Add the following code to frame 1 of the main timeline: this.Createtextfield("my_txt", 10, 10, 10, 160, 120); my_txt.Autosize = "left"; my_txt.Border = tru...

  • Page 392

    392 working with text and strings ■ on the macintosh, browse to macintosh hd/applications/macromedia flash 8/samples and tutorials/samples/actionscript/textfields. About loading text and variables into text fields you can load text into a flash document several ways, including (but certainly not lim...

  • Page 393

    About loading text and variables into text fields 393 you can find sample source files that demonstrate how to work with text fields using actionscript. The source files are called loadtext.Fla and formattedtext.Fla, and you can find them in the samples folder on your hard disk: ■ in windows, browse...

  • Page 394

    394 working with text and strings 5. In the html document, modify the code inside the object tag to match the following. The code you need to add is in boldface. Codebase="http://fpdownload.Macromedia.Com/pub/shockwave/cabs/flash/ swflash.Cab#version=8,0,0,0" width="550" height="400" id="flashvars" ...

  • Page 395

    About loading text and variables into text fields 395 to use loadvars to populate a text field with external text: 1. Create a new flash document and save it as loadvarstext.Fla. 2. Add the following actionscript to frame 1 of the timeline: this.Createtextfield("my_txt", 10, 10, 10, 320, 100); my_tx...

  • Page 396

    396 working with text and strings loading variables by using loadvars the loadvars class also lets you load variables in a url-encoded format, similar to passing variables in the query string in a web browser. The following example demonstrates how to load a remote text file into a swf file and disp...

  • Page 397

    About loading text and variables into text fields 397 loading and displaying text from an xml document xml data is a popular way to distribute content on the internet, in part because it is a widely accepted standard for organizing and parsing data. As such, xml is an excellent choice for sending an...

  • Page 398

    398 working with text and strings using fonts fonts are sets of characters with a similar font face, style, and size. No matter what you create using flash basic 8 or flash professional 8, you will probably use text with at least one or two fonts in your flash applications. If you build animations, ...

  • Page 399

    Using fonts 399 don’t embed clears any previously specified individual characters or character sets. Embedding characters if you’re working with embedded fonts and know exactly what characters you need, you can reduce file size by embedding only the characters that you need instead of including addi...

  • Page 400

    400 working with text and strings you will see the string “helo wrd”. Instead of having to tell flash which characters you want to include, flash can determine all unique characters in the specified text field for you. 11. Click ok. Embedding fonts when you embed fonts, flash stores all of the font ...

  • Page 401

    Using fonts 401 4. Select the text field, and open the property inspector. A. Set the text field to single-line. B. Select the name of the embedded font by using the font drop-down menu. Embedded fonts have an asterisk (*) after the font name. 5. Click embed in the property inspector to launch the c...

  • Page 402

    402 working with text and strings the embedded font rotates 45º clockwise, and you can still see the text because it’s embedded in the swf file. Creating custom character sets in addition to using the flash default character sets, you can also create your own character sets and add them to the chara...

  • Page 403

    Using fonts 403 another example of an xml glyphrange node is the numerals [0..9] node: this range of characters includes the unicode values 0x0030 (zero) through 0x0039 (9), as well as 0x002e (.). Before you create a custom character set, you need to know the characters and their corresponding unico...

  • Page 404

    404 working with text and strings 5. Add a new textfield instance on the stage by using the text tool. 6. Set the text type of the textfield to dynamic in the property inspector, and then click embed character options to open the character embedding dialog box. 7. Scroll to the bottom of the charact...

  • Page 405

    Using fonts 405 e. Click ok. 3. In the library, right-click the font symbol, and then select linkage from the context menu. Flash opens the linkage properties dialog box. 4. Select the export for actionscript and export in first frame options and click ok. 5. Add the following actionscript to frame ...

  • Page 406

    406 working with text and strings 6. Save your changes to the fla file. 7. Select control > test movie to test your flash document. When you move the mouse pointer to the left half of the stage, the font thickness decreases. When you move the mouse pointer to the right half of the stage, the font th...

  • Page 407

    About font rendering and anti-alias text 407 flashtype is a high-quality font rendering technology that you can enable by using either the flash 8 authoring tool or actionscript. The flashtype technology lets you render font faces with high-quality output at small sizes, with more control. You can a...

  • Page 408

    408 working with text and strings font rendering options in flash five different font rendering options are available in flash 8. To select an option, select the text field and open the property inspector. Select an option from the font rendering method pop-up menu. Device fonts produces a smaller s...

  • Page 409

    About font rendering and anti-alias text 409 setting anti-alias with actionscript flash 8 offers two types of anti-aliasing: normal and advanced. Advanced anti-aliasing is available only in flash player 8 and later, and can be used only if you embed the font in the library and have the text field’s ...

  • Page 410

    410 working with text and strings 5. Select the export for actionscript and export in first frame options, enter the linkage identifier arial-10, and click ok. 6. Add the following actionscript to frame 1 of the main timeline: var text_fmt:textformat = new textformat(); text_fmt.Font = "arial-10"; t...

  • Page 411

    About font rendering and anti-alias text 411 the fourth, and final, block of code defines onrelease event handlers for both the normal_mc movie clip and the advanced_mc movie clip. When the user clicks and releases either one of these options, the anti-alias type for the text field on the stage chan...

  • Page 412

    412 working with text and strings adjusting the outside and inside cutoff values affects stroke weight and edge sharpness. The spacing between these two parameters is comparable to twice the filter radius of classic anti- aliasing methods; a narrow spacing provides a sharper edge, while a wider spac...

  • Page 413

    About font rendering and anti-alias text 413 8. Select frame 1 of the main timeline, and add the following actionscript in the actions panel: import flash.Text.Textrenderer; var arialtable:array = new array(); arialtable.Push({fontsize:16.0, insidecutoff:0.516, outsidecutoff:0.416}); arialtable.Push...

  • Page 414

    414 working with text and strings after the text loads from the remote server, flash displays some text in the text field, and you can see the advanced anti-aliasing table properties applied to your text field. The embedded font on the stage should appear like it has a slight blur effect because of ...

  • Page 415

    About text layout and formatting 415 to modify a text field’s sharpness and thickness: 1. Create a new flash document and save it as sharpness.Fla. 2. Select new font from the pop-up menu in the upper-right corner of the library panel. 3. Select arial from the font drop-down menu and set the font si...

  • Page 416

    416 working with text and strings this actionscript code can be separated into five key sections. The first section of code defines a new textformat instance that will be applied to a dynamically created text field. The next two sections create two new text fields on the stage. The first text field,...

  • Page 417

    About text layout and formatting 417 using a grid fit type when you use advanced anti-aliasing on a text field, three types of grid fitting are available: none specifies no grid fitting. Horizontal and vertical lines in the glyphs are not forced to the pixel grid. This setting is usually good for an...

  • Page 418

    418 working with text and strings 8. Add the following code to frame 1 of the main timeline: var my_fmt:textformat = new textformat(); my_fmt.Size = 10; my_fmt.Font = "arial-10"; var h:number = math.Floor(stage.Height / 3); this.Createtextfield("none_txt", 10, 0, 0, stage.Width, h); none_txt.Antiali...

  • Page 419

    About text layout and formatting 419 the preceding actionscript code can be separated into five sections. The first section defines a new text format object that specifies two properties, size and font . The font property refers to the linkage identifier of the font symbol currently in the document ...

  • Page 420

    420 working with text and strings to format a text field with the textformat class: 1. In a new flash document, create a text field on the stage using the text tool. Type some text in the text field on the stage, such as bold, italic, 24 point text. 2. In the property inspector, type mytext_txt in t...

  • Page 421

    Formatting text with cascading style sheet styles 421 default properties of new text fields text fields created at runtime with createtextfield() receive a default textformat object with the following properties: align = "left" blockindent = 0 bold = false bullet = false color = 0x000000 font = "tim...

  • Page 422

    422 working with text and strings you can create styles that redefine built-in html formatting tags that flash player uses (such as and ). You can also create style classes that can be applied to specific html elements using the or tag’s class attribute, or define new tags. You use the textfield.Sty...

  • Page 423

    Formatting text with cascading style sheet styles 423 supported css properties flash player supports a subset of properties in the original css1 specification ( www.W3.Org/ tr/rec-css1 ). The following table shows the supported css properties and values as well as their corresponding actionscript pr...

  • Page 424

    424 working with text and strings creating a style sheet object csss are represented in actionscript by the textfield.Stylesheet class. This class is available only for swf files that target flash player 7 or later. To create a style sheet object, call the constructor function of the textfield.Style...

  • Page 425

    Formatting text with cascading style sheet styles 425 in the following example, you create and load an external css file and use the textfield.Stylesheet.Getstylenames() method to retrieve the names of the loaded styles. To load an external style sheet: 1. In your preferred text or css editor, creat...

  • Page 426

    426 working with text and strings as with all other actionscript methods that load data over the network, the css file must reside in the same domain as the swf file that is loading the file. (see “cross-domain and subdomain access between swf files” on page 696 .) for more information on using css ...

  • Page 427

    Formatting text with cascading style sheet styles 427 applying styles to a textfield object to apply a style sheet object to a textfield object, you assign the style sheet object to the text field’s stylesheet property. Textobj_txt.Stylesheet = styles; when you assign a style sheet object to a textf...

  • Page 428

    428 working with text and strings 3. Add the following actionscript to frame 1 of the main timeline: // create a new style sheet object and set styles for it. Var styles:textfield.Stylesheet = new textfield.Stylesheet(); styles.Setstyle("html", {fontfamily:'arial,helvetica,sans-serif', fontsize:'12p...

  • Page 429

    Formatting text with cascading style sheet styles 429 combining styles css styles in flash player are additive; that is, when styles are nested, each level of nesting can contribute style information, which is added together to result in the final formatting. The following example shows some xml dat...

  • Page 430

    430 working with text and strings styling built-in html tags flash player supports a subset of html tags. (for more information, see “using html- formatted text” on page 436 .) you can assign a css style to every instance of a built-in html tag that appears in a text field. For example, the followin...

  • Page 431

    Formatting text with cascading style sheet styles 431 an example of using styles with html this section presents an example of using styles with html tags. You can create a style sheet that styles some built-in tags and defines some style classes. Then, you can apply that style sheet to a textfield ...

  • Page 432

    432 working with text and strings 4. Create a new text file in a text or html editor, and save the document as mytext.Htm. Add the following text to the file: flash adds flashtype rendering technology! P> san francisco, ca--macromedia inc. Announced today a new version of flash that features a brand...

  • Page 433

    Formatting text with cascading style sheet styles 433 } else { trace("unable to load css file."); } }; styles.Load(css_url); 8. Save the file as news_html.Fla in the same directory that contains the css file you created in step 3. 9. Select control > test movie to see the styles applied to the html ...

  • Page 434

    434 working with text and strings an example of using styles with xml in this section, you create a fla file that has xml-formatted text. You’ll create a style sheet using actionscript, rather than importing styles from a css file as shown in “an example of using styles with html” on page 431 to for...

  • Page 435

    Formatting text with cascading style sheet styles 435 this code creates a new style sheet object named styles that defines styles by using the setstyle() method. The styles exactly match the ones you created in an external css file earlier in this chapter. 7. To create the xml text to assign to the ...

  • Page 436

    436 working with text and strings using html-formatted text flash player supports a subset of standard html tags such as and that you can use to style text in any dynamic or input text field. Text fields in flash player 7 and later also support the tag, which lets you embed image files (jpeg, gif, p...

  • Page 437

    Using html-formatted text 437 to render html correctly, you must use the correct syntax. Attributes of html tags must be enclosed in double (") or single (') quotation marks. Attribute values without quotation marks can produce unexpected results, such as improper rendering of text. For example, the...

  • Page 438

    438 working with text and strings anchor tag the tag creates a hypertext link and supports the following attributes: ■ href a string of up to 128 characters that specifies the url of the page to load in the browser. The url can be either absolute or relative to the location of the swf file that is l...

  • Page 439

    Using html-formatted text 439 font tag the tag specifies a font or list of fonts to display the text. The font tag supports the following attributes: ■ color only hexadecimal color ( #ffffff ) values are supported. For example, the following html code creates red text: mytext_txt.Htmltext = "this is...

  • Page 440

    440 working with text and strings the tag supports the following attributes: ■ src specifies the url to an image or swf file, or the linkage identifier for a movie clip symbol in the library. This attribute is required; all other attributes are optional. External files (jpeg, gif, png, and swf files...

  • Page 441

    Using html-formatted text 441 ■ apples ■ oranges ■ lemons paragraph tag the tag creates a new paragraph. You must set the text field to be a multiline text field to use this tag. The tag supports the following attributes: ■ align specifies alignment of text within the paragraph; valid values are lef...

  • Page 442

    442 working with text and strings text format tag the tag lets you use a subset of paragraph formatting properties of the textformat class within html text fields, including line leading, indentation, margins, and tab stops. You can combine tags with the built-in html tags. The tag has the following...

  • Page 443

    Using html-formatted text 443 to create a formatted table of data using tab stops: 1. Create a new flash document, and save it as tabstops.Fla. 2. In the timeline, select the first frame on layer 1. 3. Open the actions panel (window > actions), and enter the following code in the actions panel: // c...

  • Page 444

    444 working with text and strings about supported html entities html entities help you display certain characters in html formatted text fields, so that they are not interpreted as html. For example, you use less-than ( ) and greater-than ( > ) characters to enclose html tags, such as and . To displ...

  • Page 445

    Using html-formatted text 445 about embedding images, swf files, and movie clips in text fields in flash player 7 and later, you can use the tag to embed image files (jpeg, gif, png), swf files, and movie clips inside dynamic and input text fields, and textarea component instances. (for a full list ...

  • Page 446

    446 working with text and strings 4. Save the document and select control > test movie to test the document. The upper text field should have a sentence of text and most likely an error message in the output panel saying that flash was unable to locate a file named beach.Gif in the current directory...

  • Page 447

    Using html-formatted text 447 9. Select control > test movie to test the flash document. About specifying height and width values if you specify width and height attributes for an tag, space is reserved in the text field for the image file, swf file, or movie clip. After an image or swf file is down...

  • Page 448

    448 working with text and strings 8. Click a blank frame between frame 1 and 20, and set the tween type to shape in the property inspector. 9. Save the current document as animation.Fla. 10. Select control > test movie to preview the animation. The swf file is created in the same directory as the fl...

  • Page 449

    Example: creating scrolling text 449 about making hypertext links out of embedded media to make a hypertext link out of an embedded image file, swf file, or movie clip, enclose the tag in an tag: textfield_txt.Htmltext = "click the image to return home href='home.Htm'>"; href='home.Htm'> when the mo...

  • Page 450

    450 working with text and strings to use the scroll property to create scrolling text: 1. Do one of the following: ■ use the text tool to drag a text field on the stage. Assign the text field the instance name textfield_txt in the property inspector. ■ use actionscript to create a text field dynamic...

  • Page 451

    About strings and the string class 451 you can associate each character with a specified character code, which you can also optionally use to display text. For example, the character “a” is represented by the unicode character code 0041, or 65 in ascii (american standard code for information interch...

  • Page 452

    452 working with text and strings you can find a sample source file, strings.Fla, in the samples folder on your hard disk. This file shows you how to build a simple word processor that compares and retrieves string and substring selections. ■ in windows, browse to boot drive\program files\macromedia...

  • Page 453

    About strings and the string class 453 using the locale class the locale class (mx.Lang.Locale) allows you to control how multilanguage text is displayed in a flash application at runtime. With the strings panel, you can use string ids instead of string literals in dynamic text fields, which allows ...

  • Page 454

    454 working with text and strings 9. Type the string bonjour in the fr column. You use these strings when you use the lang_cb combo box to change the language on the stage. 10. Add the following actionscript to frame 1 of the main timeline: import mx.Lang.Locale; locale.Setloadcallback(localelistene...

  • Page 455

    About strings and the string class 455 for more information, see locale (mx.Lang.Locale) in the actionscript 2.0 language reference. Using an input method editor an input method editor (ime) lets users type non-ascii text characters in asian languages such as chinese, japanese, and korean. The ime c...

  • Page 456

    456 working with text and strings 3. Select control > test movie to test the document. A message appears in the output panel stating whether you have an ime installed and currently active. You can also use the ime class to enable and disable the ime in flash at runtime. The following example require...

  • Page 457

    About strings and the string class 457 return false; } } else { trace("please install an ime and try again."); return false; } } the preceding code is separated into five sections. The first section calls the checkime() method, which displays a message in the output panel if the system has an ime in...

  • Page 458

    458 working with text and strings the string class is a wrapper for the string primitive data type, and provides methods and properties that let you manipulate primitive string values. You can convert the value of any object into a string by using the string() function. All the methods of the string...

  • Page 459

    About strings and the string class 459 to create and use strings: 1. Create a new flash document and save it as strings.Fla. 2. Add the following actionscript to frame 1 of the main timeline: var firststr:string = "foo"; var secondstr:string = new string("foo"); trace(firststr == secondstr); // true...

  • Page 460

    460 working with text and strings about the escape character you can use the backslash escape character ( \ ), to define other characters in string literals. For more information on string literals, see chapter 5, “about literals,” on page 130 and “creating strings” on page 458 . Analyzing and compa...

  • Page 461

    About strings and the string class 461 if a string doesn’t contain a value, its length is set to undefined: var thirdstr:string; trace(thirdstr.Length); // undefined you can also use character codes to define a string. For more information on character codes and character encoding, see “about string...

  • Page 462

    462 working with text and strings 4. Modify the existing actionscript code so that it traces the ascii value for each character: var mystr:string = "hello world!"; for (var i:number = 0; i trace(mystr.Charat(i) + " - ascii=" + mystr.Charcodeat(i)); } 5. Save the current flash document and select con...

  • Page 463

    About strings and the string class 463 to compare strings to other data types: 1. Create a new flash document and save it as comparenum.Fla. 2. Add the following actionscript to frame 1 of the main timeline: var mystr:string = "4"; var total:number = 4; if (mystr == total) { trace("types are convert...

  • Page 464

    464 working with text and strings converting and concatenating strings you can use the tostring() method to convert many objects to strings. Most built-in objects have a tostring() method for this purpose: var n:number = 0.470; trace(typeof(n.Tostring())); // string when you use the addition ( + ) o...

  • Page 465

    About strings and the string class 465 the preceding code shows two methods of concatenating strings. The first method uses the addition (+) operator to join the str1 string with the string "ish" . The second method uses the addition and assignment (+=) operator to concatenate the string "ish" with ...

  • Page 466

    466 working with text and strings to create an array of substrings segmented by delimiter: 1. Create a new flash document and save it as strsplit.Fla. 2. Add the following actionscript to frame 1 of the main timeline: var querystr:string = "first=joe&last=cheng&title=manager&startdate=3/6/ 65"; var ...

  • Page 467

    About strings and the string class 467 returning substrings the substr() and substring() methods of the string class are similar. Both return a substring of a string and both take two parameters. In both methods, the first parameter is the position of the starting character in the given string. Howe...

  • Page 468

    468 working with text and strings to find the character position of a matching substring: 1. Create a new flash document and save it as indexof.Fla. 2. Add the following actionscript to frame 1 of the main timeline: var mystr:string = "the moon, the stars, the sea, the land"; trace(mystr.Indexof("th...

  • Page 469

    469 13 chapter 13 animation, filters, and drawings this chapter describes how to add animation to your macromedia flash basic 8 and macromedia flash professional 8 applications using actionscript instead of (or in addition to) timeline-based animations that use motion or shape tweens. Using code to ...

  • Page 470

    470 animation, filters, and drawings scripting animation with actionscript 2.0 you can use actionscript 2.0 to add animation to your flash applications, instead of using motion or shape tweens on a timeline.The following sections show you how to use code to animate instances, such as changing the tr...

  • Page 471

    Scripting animation with actionscript 2.0 471 about animation and frame rate when you add animation to an application, consider the frame rate that you set your fla file to. You need to think about frame rate when working with animations because it can affect the performance of your swf file and the...

  • Page 472

    472 animation, filters, and drawings fading objects with code when you work with movie clips on the stage, you might want to fade the movie clip in or out instead of toggling its _visible property. The following procedure demonstrates how to use an onenterframe event handler to animate a movie clip....

  • Page 473

    Scripting animation with actionscript 2.0 473 to fade an object by using the setinterval() function: 1. Create a new flash document called fade2.Fla. 2. Draw some graphics on the stage, or import an image to the stage (file > import > import to stage). 3. Select the content on the stage and select m...

  • Page 474

    474 animation, filters, and drawings adding color and brightness effects with code in addition to using actionscript to set and animate alpha fades (see “fading objects with code” on page 472 ), you can animate various color and brightness effects by using code instead of using the filters panel in ...

  • Page 475

    Scripting animation with actionscript 2.0 475 to use the colormatrixfilter class to change an image to a grayscale image: 1. Create a new flash document called grayscale.Fla. 2. Select frame 1 of the timeline, and add the following code to the actions panel: import flash.Filters.Colormatrixfilter; s...

  • Page 476

    476 animation, filters, and drawings to change an image’s brightness: 1. Create a new flash document called brightness.Fla. 2. Select frame 1 of the timeline and add the following code to the actions panel: import flash.Filters.Colormatrixfilter; system.Security.Allowdomain("http://www.Helpexamples....

  • Page 477

    Scripting animation with actionscript 2.0 477 ■ on the macintosh, browse to macintosh hd/applications/macromedia flash 8/samples and tutorials/samples/actionscript/galleries. Moving objects with code using actionscript to move an object is similar to modifying an object’s _alpha property, except tha...

  • Page 478

    478 animation, filters, and drawings for information on using an onenterframe event handler or setinterval() function to animate the image, see “fading objects with code” on page 472 . For an example of scripted animation in flash, you can find a sample source file, animation.Fla, in the samples fol...

  • Page 479

    Scripting animation with actionscript 2.0 479 to pan an instance on the stage using code: 1. Create a new flash document called pan.Fla. 2. Change the frame rate of the document to 24 fps in the property inspector. The animation is much smoother if you use a higher frame rate, such as 24 fps. 3. Sel...

  • Page 480

    480 animation, filters, and drawings the first section of code in this code example defines two variables: direction and speed . The direction variable controls whether the masked image scrolls from left to right ( 1 ) or right to left ( -1 ). The speed variable controls how many pixels are moved ea...

  • Page 481

    About the tween and transitionmanager classes 481 for detailed information on caching button or movie clip instances see the following sections in chapter 11, “working with movie clips” : ■ “about caching and scrolling movie clips with actionscript” on page 369 ■ “caching a movie clip” on page 373 ■...

  • Page 482

    482 animation, filters, and drawings you can also use the tween and transitionmanager classes outside of a screen-based document, in either flash basic 8 or flash professional 8. For example, you can use the classes with the component set of version 2 of the macromedia component architecture, or wit...

  • Page 483

    About the tween and transitionmanager classes 483 adding tweens and transitions to a file in flash professional 8 (flash professional 8 only) the tween and transitionmanager classes are designed to let you use simple actionscript to add animations to parts of your swf file. The flash authoring envir...

  • Page 484

    484 animation, filters, and drawings this code calls the transitionmanager class and then applies the zoom transition with the specified mx.Transitions.Easing.Bounce.Easeout easing method. In this case, the transition applies to the selected slide. To apply this effect to a movie clip, you can modif...

  • Page 485

    About the tween and transitionmanager classes 485 each transition has slightly different customizations that you can apply to the animation. The transitions dialog box lets you preview a sample animation before you apply the effect to the slide or form. Animating with the transitionmanager and tween...

  • Page 486

    486 animation, filters, and drawings 9. With the image still selected, open the property inspector (window > properties > properties), and assign the movie clip the instance name img1_mc. 10. Select frame 1 of the main timeline and add the following actionscript to the actions panel: mx.Transitions....

  • Page 487

    About the tween and transitionmanager classes 487 5. In the convert to symbol dialog box, click the center of the 3 x 3 grid to set the registration point to the center of the bitmap and click ok. 6. Select the new movie clip on the stage and use the property inspector to give it an instance name of...

  • Page 488

    488 animation, filters, and drawings about easing classes and methods “adding tweens and transitions to a file in flash professional 8 (flash professional 8 only)” on page 483 describes how to use the bounce easing class to add a bouncing effect to the movie clip. In addition to bounce, flash 8 offe...

  • Page 489

    About the tween and transitionmanager classes 489 for information on each method and property of the tween class, see chapter 51, “tween class” in the components language reference. For information on each method and property of the transitionmanager class, see chapter 48, “transitionmanager class” ...

  • Page 490

    490 animation, filters, and drawings for example, imagine that you want to move a movie clip across the stage. You can add keyframes to a timeline and insert a motion or shape tween between them, you can write some code in an onenterframe event handler, or you can use the setinterval() function to c...

  • Page 491

    About the tween and transitionmanager classes 491 this code example uses two import statements. The first statement imports the mx.Transitions.Tween class only, and the second import statement uses the wildcard ( * ) shortcut to import each of the six easing classes by using a single line of code. T...

  • Page 492

    492 animation, filters, and drawings instead of using seconds, you can fade the symbol over a few frames. To set the duration in frames instead of seconds in the tween class, you change the final parameter, useseconds , from true to false . When you set the parameter to true , you tell flash that th...

  • Page 493

    About the tween and transitionmanager classes 493 to trigger code when an animation is completed: 1. Create a new document, and call it triggertween.Fla. 2. Create a movie clip on the stage. 3. Select the movie clip instance and type ball_mc into the instance name text box in the property inspector....

  • Page 494

    494 animation, filters, and drawings after the initial tween finishes, the ball_mc movie clip tweens back to its original position at 0 pixels. The following snippet (edited for brevity) shows the function prototype for the continueto() method: function continueto(finish:number, duration:number):voi...

  • Page 495

    About the tween and transitionmanager classes 495 to create an animation that continues endlessly: 1. Create a new flash document called yoyo.Fla. 2. Open the actions panel and enter the following actionscript on frame 1 of the timeline: import mx.Transitions.Tween; import mx.Transitions.Easing.*; t...

  • Page 496

    496 animation, filters, and drawings 6. Test the animation again (control > test movie). Now, the box stops easing before it goes off the boundaries of the stage. Combining the transitionmanager and tween classes you can generate interesting effects when you combine the transitionmanager and tween c...

  • Page 497

    About the tween and transitionmanager classes 497 the second section of actionscript creates a listener object for the moviecliploader class instance, which you create in the third section of code. When the target movie clip loads into the moviecliploader instance, the onloadinit event triggers and ...

  • Page 498

    498 animation, filters, and drawings using filter effects filters are visual effects that you can apply to objects rendered at runtime by flash player, such as movie clip instances. The filters include drop shadow, blur, glow, bevel, gradient glow, and gradient bevel. You can also use an adjust colo...

  • Page 499

    Using filter effects 499 this code completes two different functionalities. The first section creates and positions a movie clip instance, and draws a black rounded rectangle on the stage. The second block of code applies a glow filter to the rectangle on the stage and defines an onenterframe event ...

  • Page 500

    500 animation, filters, and drawings the import statement lets you access classes without specifying their fully qualified names. For example, to use a blurfilter in a script, you must refer to it by its fully qualified name (flash.Filters.Blurfilter) or import it; if you import it, you can refer to...

  • Page 501

    Using filter effects 501 when you use import statements, remember that classes are only imported for the level that you specify. For example, if you import all classes in the mx.Transitions package, only the classes within the /transitions/ directory are imported, not all classes within subdirectori...

  • Page 502

    502 animation, filters, and drawings to modify a filter’s properties when applied to a movie clip instance: 1. Create a new flash document and save the file as modifyfilter.Fla. 2. Add the following actionscript to frame 1 of the timeline: this.Createemptymovieclip("my_mc", 10); // draw square with ...

  • Page 503

    Using filter effects 503 for an example of using actionscript to apply filters, you can find a sample source file, filters.Fla, in the samples folder on your hard disk. ■ in windows, browse to boot drive\program files\macromedia\flash 8\samples and tutorials\samples\actionscript\filters. ■ on the ma...

  • Page 504

    504 animation, filters, and drawings about error handling, performance, and filters one problem that arises if you use too many filters in an application is the potential to use large amounts of memory and cause flash player performance to suffer. Because a movie clip with filters attached has two b...

  • Page 505

    Working with filters using actionscript 505 working with filters using actionscript the flash.Filters package contains classes for the bitmap filter effects that are new in flash player 8. Filters let you use actionscript to apply rich visual effects, such as blur, bevel, glow, and drop shadow, to t...

  • Page 506

    506 animation, filters, and drawings the following sections describe how to use the filters: ■ “using the blur filter” on page 507 ■ “using the drop shadow filter” on page 509 ■ “using the glow filter” on page 513 ■ “creating gradient glows” on page 515 ■ “using the bevel filter” on page 517 ■ “appl...

  • Page 507

    Working with filters using actionscript 507 using the blur filter the blurfilter class lets you apply a blur visual effect to a variety of objects in flash. A blur effect softens the details of an image. You can produce blurs that range from creating a softly unfocused look to a gaussian blur, a haz...

  • Page 508

    508 animation, filters, and drawings to blur an image based on the mouse pointer’s position: 1. Create a new flash document and save it as dynamicblur.Fla. 2. Add the following code to frame 1 of the timeline: import flash.Filters.Blurfilter; system.Security.Allowdomain("http://www.Helpexamples.Com"...

  • Page 509

    Working with filters using actionscript 509 3. Select control > test movie to test the flash document. Move the mouse pointer along the x-axis to modify the amount of horizontal blurring. The instance blurs more when the pointer moves farther away from the horizontal center of the stage. Moving the ...

  • Page 510

    510 animation, filters, and drawings to use the drop shadow filter: 1. Create a new flash document and save it as dropshadow.Fla. 2. Add the following actionscript to frame 1 of the timeline: // import the filter classes import flash.Filters.Dropshadowfilter; // create a movie clip called shapeclip ...

  • Page 511

    Working with filters using actionscript 511 3. Select control > test movie to test the flash document. Move the mouse pointer along the x-axis to change the value of the drop shadow’s distance, and move the mouse pointer along the y-axis to change the amount of blur applied to the movie clip instanc...

  • Page 512

    512 animation, filters, and drawings to create a drop shadow that follows the mouse pointer: 1. Create a new flash document and save it as dropshadowmouse.Fla. 2. Add the following actionscript to frame 1 of the timeline: import flash.Filters.Dropshadowfilter; system.Security.Allowdomain("http://www...

  • Page 513

    Working with filters using actionscript 513 you can also apply drop shadows to dynamically loaded semitransparent png images. In the following procedure, the drop shadow filter is applied only to the solid area of the png, not the transparency. To apply a drop shadow to a semitransparent image: 1. C...

  • Page 514

    514 animation, filters, and drawings the following procedure demonstrates how you can apply a glow filter to a dynamically created movie clip on the stage. Moving your mouse pointer around the stage causes the movie clip’s blur to change, and clicking the dynamically created shape causes the filter’...

  • Page 515

    Working with filters using actionscript 515 3. Select control > test movie to test the document. The amount of horizontal and vertical blurring is calculated by the mouse pointer’s current _xmouse and _ymouse position. As you move the mouse pointer to the upper-left corner of the stage, the amount o...

  • Page 516

    516 animation, filters, and drawings to apply a gradient glow filter: 1. Create a new flash document and save it as gradientglow.Fla. 2. Add the following actionscript to frame 1 of the timeline: import flash.Filters.Gradientglowfilter; // create a new shapeclip instance var shapeclip:movieclip = th...

  • Page 517

    Working with filters using actionscript 517 3. Select control > test movie to test the document. As you move your mouse pointer around the stage, the gradient glow filter’s blur increases and decreases strength. Click the left mouse button to increase the glow’s strength. Using the bevel filter the ...

  • Page 518

    518 animation, filters, and drawings to use the bevel filter: 1. Create a new flash document and save it as bevel.Fla. 2. Add the following actionscript to frame 1 of the timeline: import flash.Filters.Bevelfilter; // define a bevel filter var bevel:bevelfilter = new bevelfilter(4, 45, 0xffffff, 1, ...

  • Page 519

    Working with filters using actionscript 519 3. Select control > test movie to test the flash document. When you move the mouse pointer along the x-axis, the offset distance of the bevel increases or decreases. When you move the mouse pointer along the y-axis, the mouse pointer’s current coordinates ...

  • Page 520

    520 animation, filters, and drawings the different properties of the gradient bevel filter control the way the filter is applied. The colors of the gradient bevel are set in the colors array. The actual distribution of colors in each portion of the rectangle is determined by the ratios array. The di...

  • Page 521

    Working with filters using actionscript 521 ■ the last four colors range from 129 through 255, increasing in value so each value is greater than or equal to the previous one. This is the second bevel edge, for example, your shadow. If you think of a gradient as composed of stripes of various colors,...

  • Page 522

    522 animation, filters, and drawings the following figure shows the gradient bevel filter created by the code above, a nine-color rainbow bevel applied to a red rectangle movie clip: the dashed line shows how angles are determined. The figure shows how the angle of 225° is realized on the filter, an...

  • Page 523

    Working with filters using actionscript 523 square_mc.Lineto(40, 200); square_mc.Lineto(40, 40); square_mc.Endfill(); /* gradientbevelfilter(distance:number, angle:number, colors:array, alphas:array, ratios:array, blurx:number, blury:number, strength:number, quality:number, type:string, knockout:boo...

  • Page 524

    524 animation, filters, and drawings to use the gradient bevel filter: 1. Create a new flash document and save it as gradientbevel.Fla. 2. Add the following actionscript to frame 1 of the timeline: import flash.Filters.Gradientbevelfilter; var shapeclip:movieclip = this.Createemptymovieclip("shape_m...

  • Page 525

    Working with filters using actionscript 525 using the color matrix filter the colormatrixfilter class lets you apply a 4 x 5 matrix transformation on the argb color and alpha values of every pixel on the input image to produce a result with a new set of argb color and alpha values. This filter allow...

  • Page 526

    526 animation, filters, and drawings you could also create an animated brightness effect by combining the tween class with the colormatrixfilter class, as the next procedure shows. To animate the brightness level of an instance by using the tween class: 1. Create a new flash document and save it as ...

  • Page 527

    Working with filters using actionscript 527 the first section of code uses the moviecliploader class to load a jpeg image onto the stage. After the image completely loads, you reposition the image to the center of the stage. Then you use the tween class to animate the image brightness level. To anim...

  • Page 528

    528 animation, filters, and drawings to use the convolution filter to modify an image’s color: 1. Create a new flash document and save it as convolution.Fla. 2. Add the following actionscript to frame 1 of the timeline: import flash.Filters.Convolutionfilter; import flash.Display.Bitmapdata; this.Cr...

  • Page 529

    Working with filters using actionscript 529 this filter is only available by using actionscript. For more information on this filter, see displacementmapfilter (flash.Filters.Displacementmapfilter) in the actionscript 2.0 language reference. The following procedure loads a jpeg image and applies a d...

  • Page 530

    530 animation, filters, and drawings 3. Select control > test movie to test the document. Move your mouse pointer around the stage to re-create a displacement map by calling the perlinnoise() method, which changes the appearance of the jpeg image. Manipulating filter effects with code flash basic 8 ...

  • Page 531

    Manipulating filter effects with code 531 setting the filters property duplicates the filters array passed in and does not store it as a reference. When getting the filters property, it returns a new copy of the array. One negative implication of this approach is that the following code does not wor...

  • Page 532

    532 animation, filters, and drawings moving the mouse pointer along the x -axis modifies the blur filter’s blurx property. Moving the mouse pointer along the y -axis modifies the blur filter’s blury property. The closer the mouse pointer is to the upper-left corner of the stage, the less blurring is...

  • Page 533

    Manipulating filter effects with code 533 the preceding code is separated into three sections. The first section imports the required classes and packages. The second section creates a nested movie clip that is used to load an image and apply filters to the holder movie clip. The final section of co...

  • Page 534

    534 animation, filters, and drawings the preceding code creates a new instance of the drop shadow filter and gives it the name greendropshadow . The green drop shadow object is duplicated by using the dropshadowfilter.Clone() method and creates a new filter object called reddropshadow . Both the gre...

  • Page 535

    Creating bitmaps with the bitmapdata class 535 ■ on the macintosh, browse to macintosh hd/applications/macromedia flash 8/samples and tutorials/samples/actionscript/bitmapdata. The following procedure dynamically loads a jpeg image onto the stage, and uses the bitmapdata class to create a noise effe...

  • Page 536

    536 animation, filters, and drawings 3. Select control > test movie to test the document. Moving the mouse pointer along the x-axis affects the low parameter; moving the mouse pointer along the y-axis affects the high parameter. The bitmapdata class also lets you distort a dynamically loaded image b...

  • Page 537

    About blending modes 537 this code example consists of five logical sections. The first section imports the necessary classes for the example. The second block of code creates a nested movie clip and loads a jpeg image from a remote server. The third block of code creates a new bitmapdata instance n...

  • Page 538

    538 animation, filters, and drawings normal used to specify that the pixel values of the blend image override those of the base image. Overlay commonly used to create shading effects. Screen commonly used to create highlights and lens flares. Subtract commonly used to create an animated darkening di...

  • Page 539

    About blending modes 539 var mcllistener:object = new object(); mcllistener.Onloadinit = function(target_mc:movieclip) { var blendmodeclip:movieclip = target_mc.Createemptymovieclip("blendmodetype_mc", 20); with (blendmodeclip) { beginfill(0x999999); moveto(0, 0); lineto(target_mc._width / 2, 0); li...

  • Page 540

    540 animation, filters, and drawings about operation order the following list is the order of operations in which a filters array, blend modes, color transforms, and mask layers are attached or performed for a movie clip instance: 1. The movie clip’s bitmap is updated from vector content (the cachea...

  • Page 541

    Drawing with actionscript 541 for more information on drawing with actionscript, see the following topics: ■ “using drawing methods to draw lines, curves, and shapes” on page 541 ■ “drawing specific shapes” on page 543 ■ “using complex gradient fills” on page 547 ■ “using line styles” on page 548 ■ ...

  • Page 542

    542 animation, filters, and drawings to draw a curve: 1. Create a new flash document and save it as curve.Fla. 2. Add the following actionscript to frame 1 of the timeline: this.Createemptymovieclip("circle_mc", 1); with (circle_mc) { linestyle(4, 0x000000, 100); beginfill(0xff0000); moveto(200, 300...

  • Page 543

    Drawing with actionscript 543 for detailed information on these methods, see their entries in movieclip in the actionscript 2.0 language reference. You can find a sample source file, drawingapi.Fla, in the samples folder on your hard disk, which shows you how to use the drawing api in a flash applic...

  • Page 544

    544 animation, filters, and drawings to create a rounded rectangle: 1. Create a new flash document and save it as roundrect.Fla. 2. Add the following actionscript code to frame 1 of the timeline: this.Createemptymovieclip("rectangle_mc", 10); rectangle_mc._x = 100; rectangle_mc._y = 100; drawrounded...

  • Page 545

    Drawing with actionscript 545 to create a circle: 1. Create a new flash document and save as circle2.Fla. 2. Add the following actionscript code to frame 1 of the timeline: this.Createemptymovieclip("circle_mc", 10); circle_mc._x = 100; circle_mc._y = 100; drawcircle(circle_mc, 100, 0x99ff00, 100); ...

  • Page 546

    546 animation, filters, and drawings to create a fancy triangle: 1. Create a new flash document and save it as fancytriangle.Fla. 2. Add the following actionscript to frame 1 of the timeline: this.Createemptymovieclip("triangle_mc", 10); triangle_mc._x = 100; triangle_mc._y = 100; drawtriangle(trian...

  • Page 547

    Drawing with actionscript 547 using complex gradient fills the flash drawing api supports gradient fills as well as solid fills. The following procedure creates a new movie clip on the stage, use the drawing api to create a square, and then fills the square with a radial red and blue gradient. To cr...

  • Page 548

    548 animation, filters, and drawings using line styles the flash drawing api lets you specify a line style that flash uses for subsequent calls to movieclip.Lineto() and movieclip.Curveto() until you call movieclip.Linestyle() with different parameters, as follows: linestyle(thickness:number, rgb:nu...

  • Page 549

    Drawing with actionscript 549 with (line2_mc) { createtextfield("label_txt", 1, 5, 10, 100, 20); label_txt.Text = "square"; linestyle(20, 0x99ff00, 100, true, "none", "square", "miter", 0.8); moveto(0, 0); lineto(200, 0); _x = 50; _y = 150; } // line 3 (capsstyle: none) this.Createemptymovieclip("li...

  • Page 550

    550 animation, filters, and drawings to create a hairline stroke: 1. Create a new flash document and save it as hairline.Fla. 2. Add the following actionscript to frame 1 of your timeline: this.Createemptymovieclip("drawing_mc", 10); // create a red, hairline thickness line drawing_mc.Linestyle(0, 0...

  • Page 551

    Drawing with actionscript 551 setting line alpha the third parameter in the linestyle() method, alpha , lets you control the transparency (alpha) level for the line. Transparency is a numerical value between 0 and 100, where 0 represents a completely transparent line, and 100 is completely opaque (v...

  • Page 552

    552 animation, filters, and drawings to set different caps styles: 1. Create a new flash document and save it as capsstyle2.Fla. 2. Add the following actionscript to frame 1 of the timeline: var linelength:number = 100; // round this.Createemptymovieclip("round_mc", 10); round_mc.Linestyle(20, 0xff0...

  • Page 553

    Drawing with actionscript 553 you can set the following three types of joint styles for the jointstyle parameter: ■ round (default) ■ miter ■ bevel the following example demonstrates the differences between each of the three joint styles. To set different joint styles: 1. Create a new flash document...

  • Page 554

    554 animation, filters, and drawings var lbl:textfield = bevel_mc.Createtextfield("label_txt", 10, 0, linelength + 20, linelength, 20); lbl.Autosize = "center"; lbl.Text = "bevel"; flash uses the drawing api to draw three triangles on the stage. Each triangle has a different value for its joint styl...

  • Page 555

    Drawing with actionscript 555 lineto(0, target_mc._height); lineto(0, 0); endfill(); } target_mc.Setmask(maskclip); target_mc._visible = true; var mask_tween:object = new tween(maskclip, "_yscale", strong.Easeout, 0, 100, 2, true); }; this.Createemptymovieclip("img_mc", 10); var img_mcl:moviecliploa...

  • Page 556

    556 animation, filters, and drawings understanding scaling and slice guides you can use 9-slice scaling (scale-9) to specify component-style scaling for movie clips. 9-slice scaling lets you create movie clip symbols that scale appropriately for use as user interface components, as opposed to the ty...

  • Page 557

    Understanding scaling and slice guides 557 you can see that even though the component resized, the button’s border and text label do not distort. The button’s label remained centered and maintained its font size. Although components of version 2 of the macromedia component architecture do not use 9-...

  • Page 558

    558 animation, filters, and drawings working with 9-slice scaling in actionscript in the following example, you use the drawing tools to draw a 300 pixel by 300 pixel square which is resized by using 9-slice scaling. The square is split up into nine smaller squares, each one approximately 100 pixels...

  • Page 559

    Understanding scaling and slice guides 559 13. Add the following actionscript to frame 1 of the main timeline: import mx.Controls.Button; import flash.Geom.Rectangle; var grid:rectangle = new rectangle(100, 100, 100, 100); var small_button:button = this.Createclassobject(button, "small_button", 10, ...

  • Page 560

    560 animation, filters, and drawings next, you create a new button component instance and give it an instance name of small_button . Whenever you click this button, the movie clip that you created earlier resizes to 100 pixels wide by 100 pixels high. The fourth section of code dynamically creates a...

  • Page 561

    561 14 chapter 14 creating interaction with actionscript in simple animations, macromedia flash player plays the scenes and frames of a swf file sequentially. In an interactive swf file, your audience uses the keyboard and mouse to jump to different parts of a swf file, move objects, enter informati...

  • Page 562

    562 creating interaction with actionscript about events and interaction whenever a user clicks the mouse or presses a key, that action generates an event. These types of events are generally called user events because they are generated in response to some action by the user. You can write actionscr...

  • Page 563

    Controlling swf file playback 563 the following example uses the global gotoandplay() function within a button object’s onrelease event handler to send the playhead of the timeline that contains the button to frame 10: jump_btn.Onrelease = function () { gotoandplay(10); }; in the next example, the m...

  • Page 564

    564 creating interaction with actionscript this same on() event handler code produces a different result when attached to a movie clip object rather than a button. When attached to a button object, statements made within an on() handler are applied to the timeline that contains the button, by defaul...

  • Page 565

    Controlling swf file playback 565 you can also send variables along with the url, using get or post methods. This is useful if the page you are loading from an application server, such as a coldfusion server (cfm) page, expects to receive form variables. For example, suppose you want to load a cfm p...

  • Page 566

    566 creating interaction with actionscript creating interactivity and visual effects to create interactivity and other visual effects, you need to understand the following techniques: ■ “creating a custom mouse pointer” on page 566 ■ “getting the pointer position” on page 567 ■ “capturing keypresses...

  • Page 567

    Creating interactivity and visual effects 567 4. Select frame 1 of the timeline, and type the following code in the actions panel: mouse.Hide(); cursor_mc.Onmousemove = function() { this._x = _xmouse; this._y = _ymouse; updateafterevent(); }; the mouse.Hide() method hides the pointer when the movie ...

  • Page 568

    568 creating interaction with actionscript each timeline has an _xmouse and _ymouse property that returns the location of the pointer within its coordinate system. The position is always relative to the registration point. For the main timeline ( _level0 ), the registration point is the upper left c...

  • Page 569

    Creating interactivity and visual effects 569 capturing keypresses you can use the global on() handler to intercept the built-in behavior of keypresses in flash player, as shown in the following example: /* when you press the left or right arrow key, the movie clip to which the handler is attached c...

  • Page 570

    570 creating interaction with actionscript to decide which keys to use and determine their virtual key codes, use one of the following approaches: ■ see the list of key codes in appendix c, “keyboard keys and key code values.” ■ use a key class constant. (in the actions toolbox, click actionscript 2...

  • Page 571

    Creating interactivity and visual effects 571 6. To check if the left arrow key is pressed and to move the car movie clip accordingly, add code to the body of the onenterframe event handler. Your code should look like the following example (new code is in boldface): var distance:number = 10; this.Cr...

  • Page 572

    572 creating interaction with actionscript setting color values you can use the methods of the built-in colortransform class (flash.Geom.Colortransform) to adjust the color of a movie clip. The rgb property of the colortransform class assigns hexadecimal red, green, blue (rgb) values to the movie cl...

  • Page 573

    Creating interactivity and visual effects 573 8. Repeat step 7 for the other buttons ( red_btn , green_btn , and black_btn ) to change the color of the movie clip to the corresponding color. Your code should now look like the following example (new code is in bold): import flash.Geom.Colortransform;...

  • Page 574

    574 creating interaction with actionscript 3. Select export for actionscript and export in first frame; then give the sound the identifier a_thousand_ways . 4. Add a button to the stage and name it play_btn . 5. Add a button to the stage and name it stop_btn . 6. Select frame 1 in the main timeline,...

  • Page 575

    Creating interactivity and visual effects 575 8. Select frame 1 of the main timeline, and select window > actions. 9. Enter the following code into the actions panel: this.Createtextfield("volume_txt", 10, 30, 30, 200, 20); volume_mc.Top = volume_mc._y; volume_mc.Bottom = volume_mc._y; volume_mc.Lef...

  • Page 576

    576 creating interaction with actionscript 8. Enter the following code into the actions panel: balance_mc.Top = balance_mc._y; balance_mc.Bottom = balance_mc._y; balance_mc.Left = balance_mc._x; balance_mc.Right = balance_mc._x + 100; balance_mc._x += 50; balance_mc.Handle_btn.Onpress = function() {...

  • Page 577

    Creating interactivity and visual effects 577 to detect a collision between a movie clip and the mouse pointer: 1. Select the first frame on layer 1 in the timeline. 2. Select window > actions to open the actions panel, if it is not already open. 3. Add the following code in the actions panel: this....

  • Page 578

    578 creating interaction with actionscript 5. Select control > test movie, and drag the movie clip to test the collision detection. Whenever the bounding box of the car intersects the bounding box of the area, the status is true . For more information, see hittest (movieclip.Hittest method) in the a...

  • Page 579

    Creating runtime data bindings using actionscript 579 4. In the actions panel, enter the following code: this.Createemptymovieclip("canvas_mc", 999); var isdrawing:boolean = false; // clear_btn.Onrelease = function() { canvas_mc.Clear(); }; // var mouselistener:object = new object(); mouselistener.O...

  • Page 580

    580 creating interaction with actionscript you can use actionscript instead of the bindings tab to create bindings between components. Adding code is often faster and more efficient than relying on the authoring environment. Using actionscript to create bindings is necessary when you use code to add...

  • Page 581

    Creating runtime data bindings using actionscript 581 6. Insert a new layer and name it actions. 7. Add the following actionscript to frame 1 of the actions layer: var src:mx.Data.Binding.Endpoint = new mx.Data.Binding.Endpoint(); src.Component = in_ti; src.Property = "text"; src.Event = "focusout";...

  • Page 582

    582 creating interaction with actionscript if you want to modify the text in the out_ti text input field from the previous exercise, your code can become a lot more complex. If you use the component inspector to set up bindings, by default you create a two-way connection. This means that if you chan...

  • Page 583

    Creating runtime data bindings using actionscript 583 4. Select control > test movie to test the document. Flash changes the second value in the in_ti text input field and updates the value for out_ti . You successfully created a two-way connection. You can use the binding classes with most user int...

  • Page 584

    584 creating interaction with actionscript using components, bindings, and custom formatters custom formatters help you format complex data in a specific way. You can also use custom formatting to help display images, html formatted text, or other components within a component such as the datagrid. ...

  • Page 585

    Creating runtime data bindings using actionscript 585 9. Select control > test movie to test the document again. Now the text field displays the entire date, although it is awkward and lacks formatting. Depending on your own time zone and selected date, the date might appear similar to this: thu nov...

  • Page 586

    586 creating interaction with actionscript the first section of code defines the new class called dateformat, which extends the customformatter class in the mx.Data.Binding package. Remember that flash compiles the binding classes in the databindingclasses component file, so you can’t view them dire...

  • Page 587

    Creating runtime data bindings using actionscript 587 adding and binding components on the stage one of the biggest advantages to using the binding classes with actionscript is that you can create bindings between components that flash has added to the stage at runtime. Imagine creating your own cus...

  • Page 588

    588 creating interaction with actionscript deconstructing a sample script in the sample swf file zapper.Swf (which you can view in using flash help), when a user drags the bug to the electrical outlet, the bug falls and the outlet shakes. The main timeline has only one frame and contains three objec...

  • Page 589

    Deconstructing a sample script 589 the bug’s instance name is bug_mc , and the outlet’s instance name is zapper_mc . In the script, the bug is referred to as this because the script is attached to the bug and the reserved word this refers to the object that contains it. There are event handlers with...

  • Page 590

    590 creating interaction with actionscript.

  • Page 591

    591 15 chapter 15 working with images, sound, and video if you import an image or a sound while you author a document in macromedia flash basic 8 or macromedia flash professional 8, the image and sound are packaged and stored in a swf file when you publish it. In addition to importing media while au...

  • Page 592

    592 working with images, sound, and video about loading and working with external media you can load several types of media files into a flash application at runtime: swf, mp3, jpeg, gif, png, and flv files. However, not all versions of flash player support each kind of media. For more information o...

  • Page 593

    Loading external swf and image files 593 ■ in windows, browse to boot drive\program files\macromedia\flash 8\samples and tutorials\samples\actionscript\galleries. ■ on the macintosh, browse to macintosh hd/applications/macromedia flash 8/samples and tutorials/samples/actionscript/galleries. Loading ...

  • Page 594

    594 working with images, sound, and video for more information about loading external swf and image files, see “about loading swf files and the root timeline” on page 597 . To preload swf and jpeg files into movie clip instances, you can use the moviecliploader class. This class provides an event li...

  • Page 595

    Loading external swf and image files 595 register the listener object with the moviecliploader object in order for the listener object to receive the loading events, you must register it with the moviecliploader object, as shown in the following code: my_mcl.Addlistener(mcllistener); begin loading t...

  • Page 596

    596 working with images, sound, and video 6. Add the following code to the actions panel: var my_pb:mx.Controls.Progressbar; my_pb.Mode = "manual"; this.Createemptymovieclip("img_mc", 999); var my_mcl:moviecliploader = new moviecliploader(); var mcllistener:object = new object(); mcllistener.Onloads...

  • Page 597

    Loading external swf and image files 597 you can find samples of photo gallery applications on your hard disk.These files provide examples of how to use actionscript to control movie clips dynamically while loading image files into a swf file. You can find the sample source files, gallery_tree.Fla a...

  • Page 598

    598 working with images, sound, and video about loading and using external mp3 files to load mp3 files at runtime, use the loadsound() method of the sound class. First, you create a sound object, as shown in the following example: var song1_sound:sound = new sound(); use the new object to call loads...

  • Page 599

    About loading and using external mp3 files 599 loading an mp3 file suppose you’re creating an online game that uses different sounds that depend on what level the user has reached in the game. The following code loads an mp3 file (song2.Mp3) into the game_sound sound object and plays the sound when ...

  • Page 600

    600 working with images, sound, and video the following example uses setinterval() to check the bytes loaded for a sound object at predetermined intervals. To preload an mp3 file: 1. Create a new fla file called preloadmp3.Fla. 2. Select frame 1 on the timeline and type the following code in the act...

  • Page 601

    About loading and using external mp3 files 601 you can find a sample source file that loads mp3 files, jukebox.Fla, in the samples folder on your hard disk. This sample demonstrates how to create a jukebox by using data types, general coding principles, and several components. ■ in windows, browse t...

  • Page 602

    602 working with images, sound, and video because id3 2.0 tags are located at the beginning of an mp3 file (before the sound data), they are available as soon as the file starts downloading. Id3 1.0 tags, however, are located at the end of the file (after the sound data), so they aren’t available un...

  • Page 603

    About using flv video 603 6. Select frame 1 on the timeline, and type the following code in the actions panel: import flash.Display.Bitmapdata; // create imagebmp and attach the bitmap from the library. Var imagebmp:bitmapdata = bitmapdata.Loadbitmap("myimage"); // create movie clip and attach image...

  • Page 604

    604 working with images, sound, and video for information on video fundamentals, such as streaming, progressive download, dimensions, encoding, importing, and bandwidth concerns, see chapter 11, “working with video” in using flash. This section discusses using flv video without components. You can a...

  • Page 605

    About using flv video 605 ■ captioning video content is easier with external flv files because you can use event handlers to access metadata for the video. For more information on flv video, see the following topics: ■ “creating a video object” on page 605 ■ “playing back external flv files dynamica...

  • Page 606

    606 working with images, sound, and video playing back external flv files dynamically you can load flv files at runtime to play in a swf file. You can load them into a video object or into a component such as the flvplayback component. The following example shows how to play back a file named clouds...

  • Page 607

    About using flv video 607 for information on preloading flv files, see “preloading flv files” on page 507 . For information on dynamically loading flv video into components, see “creating an application with the flvplayback component” on page 491 . For information on flv files and the server, and fl...

  • Page 608

    608 working with images, sound, and video 13. Select insert > timeline > layer to create a new layer, and name it button. 14. Select the rectangle tool in the tools panel. 15. In the colors section of the tools panel, click the pencil icon to select the stroke color control. 16. Select no color, whi...

  • Page 609

    About using flv video 609 in this example, you created a banner and resized its dimensions to the established, standardized dimensions that the interactive advertising bureau specifies. For information on standard advertising dimensions (and many other useful guidelines), see the interactive adverti...

  • Page 610

    610 working with images, sound, and video 9. Type the following code in the actions panel: var connection_nc:netconnection = new netconnection(); connection_nc.Connect(null); var stream_ns:netstream = new netstream(connection_nc); my_video.Attachvideo(stream_ns); stream_ns.Play("http://www.Helpexamp...

  • Page 611

    About using flv video 611 working with cue points you can use several different kinds of cue points with flash video. You can use actionscript to interact with cue points that you embed in an flv file (when you create the flv file), or that you create by using actionscript. Navigation cue points you...

  • Page 612

    612 working with images, sound, and video the following code traces cue points in an flv file: var connection_nc:netconnection = new netconnection(); connection_nc.Connect(null); var stream_ns:netstream = new netstream(connection_nc); stream_ns.Onmetadata = function(metaprop:object) { trace("the met...

  • Page 613

    About using flv video 613 trace(indentstring + " " + i + ": " + obj[i]); } } } the following output appears: the metadata: canseektoend: true cuepoints: cuepoints[0]: name: point1 time: 0.418 type: navigation parameters: lights: beginning cuepoints[1]: name: point2 time: 7.748 type: navigation param...

  • Page 614

    614 working with images, sound, and video using embedded cue points with the flvplayback component (flash professional only) you can view cue points for an flv file in the property inspector when you use the flvplayback component. After you set the contentpath property for the flvplayback instance, ...

  • Page 615

    About using flv video 615 7. Select control > test movie to test the swf file. The elapsed time appears in the textarea instance when the playhead passes each cue point embedded in the document. For more information on working with the flvplayback component, see “flvplayback component (flash profess...

  • Page 616

    616 working with images, sound, and video 8. Select frame 1 on the timeline, and type the following code in the actions panel: var my_flvpb:mx.Video.Flvplayback; my_flvpb.Contentpath = "http://www.Helpexamples.Com/flash/video/ clouds.Flv"; // create cuepoint object. Var cuept:object = new object(); ...

  • Page 617

    About using flv video 617 5. Select the parameters tab, and click launch component inspector. 6. In the component inspector, type http://www.Helpexamples.Com/flash/video/clouds.Flv in the url text box. 7. Open the actions panel (window > actions), and type the following code in the script pane: impo...

  • Page 618

    618 working with images, sound, and video alternatively, you can also seek to a specified duration of the flv file, using the seek() method. In the following examples, you add a button that you use to jump between cue points or a specified duration in a flv file that plays in the flvplayback compone...

  • Page 619

    About using flv video 619 3. Select the component and open the property inspector (window > properties > properties). 4. Type my_flvpb in the instance name text box. 5. Drag an instance of the button component from the components panel to the stage. 6. Select the button component and type my_button ...

  • Page 620

    620 working with images, sound, and video when you type the url in the contentpath text box, the cue points appear in the parameters tab (next to cuepoint parameter). Therefore, you can determine the name of the cue point that you want to find in your code. If you click the magnifying glass icon, yo...

  • Page 621

    About using flv video 621 to work with netstream.Onmetadata , you must have flash video that contains metadata. If you encode flv files using flash 8 video encoder, your flv file will have metadata information in it (see the following example for a list of metadata in a flv file encoded with flash 8...

  • Page 622

    622 working with images, sound, and video 9. Type the following code in the actions panel: // create a netconnection object. Var netconn:netconnection = new netconnection(); // create a local streaming connection. Netconn.Connect(null); // create a netstream object and define an onstatus() function....

  • Page 623

    About using flv video 623 about configuring flv files for hosting on a server when you work with flv files, you might have to configure your server to work with the flv file format. Multipurpose internet mail extensions (mime) is a standardized data specification that lets you send non-ascii files o...

  • Page 624

    624 working with images, sound, and video about targeting local flv files on macintosh if you attempt to play a local flv from a non-system drive on a macintosh computer by using a path that uses a relative slash ( / ), the video will not play. Non-system drives include, but are not limited to, cd-r...

  • Page 625

    About creating progress animations for media files 625 for information on creating progress bars to load media files, see the following topics: ■ “creating a progress animation for loading swf and image files” on page 625 ■ “creating a progress bar for loading mp3 files with actionscript” on page 62...

  • Page 626

    626 working with images, sound, and video 3. Select frame 1 of the timeline, and then type the following code in the actions panel: //create clips to hold your content this.Createemptymovieclip("progressbar_mc", 0); progressbar_mc.Createemptymovieclip("bar_mc", 1); progressbar_mc.Createemptymoviecli...

  • Page 627

    About creating progress animations for media files 627 you can change the following url to a swf or another image file. */ image_mcl.Loadclip("http://www.Helpexamples.Com/flash/images/gallery1/ images/pic3.Jpg", image_mc); 4. Select control > test movie to see the image load and watch the progress b...

  • Page 628

    628 working with images, sound, and video to create a progress bar for loading mp3 files: 1. Create a new flash document called loadsound.Fla. 2. Select frame 1 on the timeline and type the following code in the actions panel. Var pb_height:number = 10; var pb_width:number = 100; var pb:movieclip = ...

  • Page 629

    About creating progress animations for media files 629 trace("cleared interval"); } my_sound.Loadsound("http://www.Helpexamples.Com/flash/sound/song2.Mp3", true); my_interval = setinterval(updateprogressbar, 100, my_sound); function updateprogressbar(the_sound:sound):void { var pos:number = math.Rou...

  • Page 630

    630 working with images, sound, and video creating a progress bar for loading flv files with actionscript you can create a progress bar to display the loading progress of an flv file. For information on loading flv files into a swf file, see “preloading flv files” on page 609 . For other information...

  • Page 631

    About creating progress animations for media files 631 8. Select frame 1 in the timeline and type the following code in the actions panel: var connection_nc:netconnection = new netconnection(); connection_nc.Connect(null); var stream_ns:netstream = new netstream(connection_nc); my_video.Attachvideo(...

  • Page 632

    632 working with images, sound, and video 9. Select control > test movie to test your code. The video loads and an animating bar and changing text values communicate the loading progress. If these elements overlap your video, move the video object on the stage. You can customize the color of the pro...

  • Page 633

    633 16 chapter 16 working with external data in macromedia flash basic 8 and macromedia flash professional 8, you can use actionscript to load data from external sources to a swf file. You can also send data, which could be provided by the user or the server, from a swf file to an application server...

  • Page 634

    634 working with external data sending and loading variables a swf file is a window for capturing and displaying information, much like an html page. However, swf files can stay loaded in the browser and continuously update with new information without having to reload the entire page. Using actions...

  • Page 635

    Sending and loading variables 635 before you can use loaded data in a swf file, you must check to see whether it has been loaded. For example, you can’t load variables and manipulate their values in the same script because the data to manipulate doesn’t exist in the file until it is loaded. In the f...

  • Page 636

    636 working with external data creating a progress bar to display data loading progress the following exercise dynamically creates a simple preloader using the drawing application programming interface (api) and displays the loading progress for an xml document. Creating a progress bar using the dra...

  • Page 637

    Sending and loading variables 637 } else { trace("unable to load xml"); } }; my_xml.Load("http://www.Helpexamples.Com/flash/xml/ds.Xml"); pbar_mc.Onenterframe = function() { var pctloaded:number = math.Floor(my_xml.Getbytesloaded() / my_xml.Getbytestotal() * 100); if (!Isnan(pctloaded)) { pbar_mc.Ba...

  • Page 638

    638 working with external data 3. Select control > test movie to test the flash document. As the external xml file loads, the nested bar_mc movie clip resizes to display the download progress of the xml. Once the xml file has completely loaded, the onenterframe event handler gets deleted so it doesn...

  • Page 639

    Using http to connect to server-side scripts 639 ■ variables sets the http method, either get (appends the variables to the end of the url) or post ( sends the variables in a separate http header), by which the variables are sent. When this parameter is omitted, flash player defaults to get , but no...

  • Page 640

    640 working with external data ■ you don’t need to create container movie clips for holding data or clutter existing movie clips with variables specific to client/server communication. ■ the class interface is similar to that of the xml object, which provides some consistency in actionscript. It use...

  • Page 641

    Using http to connect to server-side scripts 641 4. Create four input text fields on the stage, and give them the following instance names: emailfrom_txt, emailto_txt, emailsubject_txt, and emailbody_txt. 5. Create a dynamic text field on the stage with the instance name debug_txt. 6. Create a butto...

  • Page 642

    642 working with external data flash player 8 introduced the onhttpstatus event handler for the loadvars class, xml class, and moviecliploader class to allow users to access the status code from an http request. This allows developers to determine why a particular load operation may have failed inst...

  • Page 643

    Using http to connect to server-side scripts 643 the previous code creates a new text field on the stage and enables text field autosizing. Next, a loadvars object is created and two event handlers: onhttpstatus and onload . The onhttpstatus event handler is new to flash player 8 and is invoked when...

  • Page 644

    644 working with external data about file uploading and downloading the filereference class lets you add the ability to upload and download files between a client and server. Your users can upload or download files between their computer and a server. Users are prompted to select a file to upload or...

  • Page 645

    About file uploading and downloading 645 you can also add download functionality to your flash application. The filereference.Download() method prompts end users for a location on their hard disks to save a file from a server. This method also initiates downloading from a remote url. When using the ...

  • Page 646

    646 working with external data about filereference api functionality and security flash player and the filereference api (see “about file uploading and downloading” on page 644 ) support file uploading and downloading up to 100 mb. The filereference api does not let the flash application that initia...

  • Page 647

    About file uploading and downloading 647 following the example that builds the flash application is an example that details the server- side code. Remember that image files are restricted in size: you can only upload images that are 200k or smaller. To build a fla application using the filereference...

  • Page 648

    648 working with external data import flash.Net.Filereference; imagepane.Setsize(400, 350); imagepane.Move(75, 25); uploadbtn.Move(75, 390); uploadbtn.Label = "upload image"; imagelbl.Move(75, 430); imagelbl.Text = "select image"; statuslbl.Move(210, 390); statuslbl.Text = "status"; imagescb.Move(75...

  • Page 649

    About file uploading and downloading 649 imagepane.Addeventlistener("complete", imagedownloaded); imagescb.Addeventlistener("change", downloadimage); uploadbtn.Addeventlistener("click", uploadimage); /* if the image does not download, the event object's total property will equal -1. In that case, di...

  • Page 650

    650 working with external data 13. Select file > publish settings and then select the formats tab, and make sure that flash and html are both selected. 14. (optional) in the publish settings dialog box, select the flash tab, and then select access network only from the local playback security pop-up...

  • Page 651

    About file uploading and downloading 651 array_push($files, array('./images/'.$file, filectime('./images/ '.$file))); } usort($files, sorter); if (count($files) > $maximum_file_count) { $files_to_delete = array_splice($files, 0, count($files) - $maximum_file_count); for ($i = 0; $i unlink($files_to_...

  • Page 652

    652 working with external data 5. View the remote html document in a web browser, and click the upload image button in the swf file. 6. Locate an image file on your hard disk and select open from the dialog box. The swf file uploads the image file to the remote php document, and displays it in the s...

  • Page 653

    About xml 653 every xml tag is called a node, or an element. Each node has a type (1, which indicates an xml element, or 3, which indicates a text node), and elements might also have attributes. A node nested in a node is called a child node. This hierarchical tree structure of nodes is called the x...

  • Page 654

    654 working with external data a third sample demonstrates how to create a dynamic menu with xml data. The sample calls the actionscript xmlmenu() constructor and passes it two parameters: the path to the xml menu file and a reference to the current timeline. The rest of the functionality resides in...

  • Page 655

    About xml 655 the server-side script that passes information between flash and the database reads and writes the data in xml format. You can use actionscript to convert information collected in the swf file (for example, a user name and password) to an xml object and then send the data to the server...

  • Page 656

    656 working with external data the following actionscript is placed on the timeline and is used to send xml-formatted data to the server. To understand this script, read the commented lines (indicated by the characters //) : // ignore xml white space xml.Prototype.Ignorewhite = true; // construct an...

  • Page 657

    About xml 657 loginxml.Sendandload("http://www.Flash-mx.Com/mm/main.Cfm", loginreplyxml); }; you can test this code by using a user name of jeansmith and the password verysecret . The first section of the script generates the following xml when the user clicks the login button: the server receives t...

  • Page 658

    658 working with external data first, the xml-formatted data is created, using the values that the user inputs in the swf file, and that xml object is sent using the sendandload method. Similar to data from a loadvariables() function, the loginreply xml element arrives asynchronously (that is, it do...

  • Page 659

    About xml 659 the following example shows how you can use the xml class’s onhttpstatus event handler to check whether an xml file successfully downloaded from the server and what the status code returned from the http request was. Checking http status codes using the xml class: 1. Create a new flash...

  • Page 660

    660 working with external data there are several sample files on your hard disk that load xml into a swf file at runtime. One sample demonstrates how to create a web log tracker by loading, parsing, and manipulating xml data. You can find the sample source file, xml_blogtracker.Fla, in the samples f...

  • Page 661

    About xml 661 using the xmlsocket class actionscript provides a built-in xmlsocket class, which lets you open a continuous connection with a server. A socket connection lets the server publish, or push, information to the client as soon as that information is available. Without a continuous connecti...

  • Page 662

    662 working with external data the following example creates an xml socket connection and sends data from the xml object myxml . To understand the script, read the commented lines (indicated by the characters // ): // create xmlsocket object var thesocket:xmlsocket = new xmlsocket(); // connect to a...

  • Page 663

    Sending messages to and from flash player 663 sending messages to and from flash player to send messages from a swf file to its host environment (for example, a web browser, a macromedia director movie, or the stand-alone flash player), you can use the fscommand() function.This function lets you ext...

  • Page 664

    664 working with external data the following table shows the values you can specify for the command and arguments parameters of fscommand() to control the playback and appearance of a swf file playing in the stand-alone player, including projectors. To use fscommand() to send a message to a scriptin...

  • Page 665

    Sending messages to and from flash player 665 4. Select frame 1 of the actions layer, and add the following actionscript in the actions panel: window_btn.Onrelease = function() { fscommand("popup", "http://www.Macromedia.Com/"); }; alert_btn.Onrelease = function() { fscommand("alert", "you clicked t...

  • Page 666

    666 working with external data the fscommand() function can send messages to macromedia director that are interpreted by lingo as strings, events, or executable lingo code. If the message is a string or an event, you must write the lingo code to receive it from the fscommand() function and carry out...

  • Page 667

    About the external api 667 about the external api the externalinterface class is also called the external api, which is a new subsystem that lets you easily communicate from actionscript and the flash player container to an html page with javascript or to a desktop application that embeds flash play...

  • Page 668

    668 working with external data the following sections contain examples that use the external api: ■ “creating interaction with the external api” on page 668 ■ “controlling flash video with the external api” on page 671 creating interaction with the external api you can create interaction between the...

  • Page 669

    About the external api 669 the previous code is split into three sections. The first section imports the externalinterface class so you don’t have to use its fully qualified class name. The second section of code defines a callback function, asfunc() , which is called from javascript in an html docu...

  • Page 670

    670 working with external data this javascript code defines three methods. The first method returns a reference to the embedded swf file based on whether the user’s browser is microsoft internet explorer (ie) or a mozilla browser. The second function, makecall() , calls the asfunc() method that you ...

  • Page 671

    About the external api 671 you can find the sample source file, extint.Fla, in the samples folder on your hard disk. ■ in windows, browse to boot drive\program files\macromedia\flash 8\samples and tutorials\samples\actionscript\externalapi\simple example. ■ on the macintosh, browse to macintosh hd/a...

  • Page 672

    672 working with external data 7. Add the following actionscript to frame 1 of the main timeline: import flash.External.Externalinterface; /* register playvideo() and pauseresume() so that it is possible to call them from javascript in the container html page. */ externalinterface.Addcallback("playv...

  • Page 673

    About the external api 673 8. Save the flash document. 9. Select file > publish settings and then select the formats tab, and make sure that html and flash are both selected. 10. Click publish to publish the swf and html files to your hard disk. When you’re finished, go on to the next procedure to c...

  • Page 674

    674 working with external data osition:absolute;top:162px;left:182px;white-space:nowrap" class="ft01">www.W3.Org/tr/xhtml1/dtd/xhtml1-transitional.Dtd"> /> // use a variable to reference the embedded swf file. Var flashvideoplayer; /* when the html page loads (through the onload event of the tag), i...

  • Page 675

    About the external api 675 codebase="http://fpdownload.Macromedia.Com/pub/shockwave/cabs/flash/ swflash.Cab#version=8,0,0,0" width="320" height="240" id="videoplayer" align="middle"> height="240" name="videoplayer" align="middle" allowscriptaccess="samedomain" type="application/x-shockwave-flash" pl...

  • Page 676

    676 working with external data the final function, updatestatus() , gets called by the swf file whenever the video_ns netstream object’s onstatus event handler is triggered. This html code also defines a form that has a combo box of videos that the user can choose from. Whenever the user selects a v...

  • Page 677

    677 17 chapter 17 understanding security in macromedia flash basic 8 and macromedia flash professional 8, you can use actionscript to load data from external sources into a swf file or send data to a server. When you load data into a swf file, you need to understand and accommodate the flash 8 secur...

  • Page 678

    678 understanding security in flash player 7 and later, if a version 6 (or earlier) swf file attempts to load data from a server that resides in another domain, and that server doesn’t provide a policy file that allows reading from that swf file’s domain, the macromedia flash player settings dialog ...

  • Page 679

    About local file security and flash player 679 about local file security and flash player flash player 8 has made enhancements to the security model, in which flash applications and swf files on a local computer are not allowed to communicate with both the internet and the local file system by defau...

  • Page 680

    680 understanding security access to the local file system and the network a local swf file can read from the local file system where it is installed, read and write to and from servers, and can cross-script other swf files on either the network or the local file system. These files are trusted, and...

  • Page 681

    About local file security and flash player 681 local-with-networking when local swf files are assigned to the local-with-networking sandbox, they forfeit their local file system access. In return, the swf files are allowed to access the network. However, a local-with-networking swf file still is not...

  • Page 682

    682 understanding security when older content runs in a newer version of the player, and flash player needs you to make a decision about enforcing newer rules or not, you may see one of the following pop-up dialog boxes. These dialog boxes ask your permission before allowing the older flash content ...

  • Page 683

    About local file security and flash player 683 if you previously selected remember in the privacy settings panel (see the following figure) to permanently allow or deny access for one or more websites, selecting always ask or always deny has the effect of deselecting remember for all those websites....

  • Page 684

    684 understanding security in addition, a projector file embeds a specific version of flash player inside the projector, which might be older than the latest version of flash player available for download from the macromedia website. The flash player that’s embedded within the projector file might b...

  • Page 685

    About local file security and flash player 685 republish and redeploy republish the file with flash basic 8 or flash professional 8. The authoring tool requires you to specify in the publish settings dialog box whether a local swf file can access the network or the local file system—but not both. If...

  • Page 686

    686 understanding security local swf files swf files that operate with local file systems or unc network paths are placed into one of three sandboxes in flash player 8. By default, local swf files are placed in the local-with-file-system sandbox. Local swf files that are registered as trusted (using...

  • Page 687

    About local file security and flash player 687 access network only to set this permission level, select publish settings > flash, and then select access network only from the local playback security pop-up menu. Local swf files with network access can read from a server if the server contains a cros...

  • Page 688

    688 understanding security testing content locally with flash 8 local file security restrictions as a flash developer, you frequently test flash applications locally, so you might see a dialog box prompt when a local flash application tries to communicate with the internet. You might see this dialog...

  • Page 689

    About local file security and flash player 689 the following example shows how to specify that a local swf file can communicate with the internet. When you test a file in a browser locally (file > publish preview > html), a security dialog box might appear. If you click settings, the settings manage...

  • Page 690

    690 understanding security you can add an individual file or an entire directory. If you add an entire directory, all the files and subdirectories in that directory are trusted. Some flash content consists of multiple related files, and you might need to trust the entire directory where all the rela...

  • Page 691

    About local file security and flash player 691 you might want to provide a flashauthor.Cfg file, with localsecurityprompt set to author , to other developers in your design or development process or to users who test flash applications on their local hard disk and do not have the flash 8 authoring t...

  • Page 692

    692 understanding security if you create applications that install on an end user’s hard disk, you might need to create a configuration file in flashplayertrust to specify a trusted directory for your application. You can create configuration files inside the flashplayertrust directory that specify ...

  • Page 693

    About local file security and flash player 693 localwithnetwork the swf file is a local file that has not been trusted by the user, and was published with access network only selected in the publish settings dialog box (flash tab). The swf file can communicate with the network but cannot read from l...

  • Page 694

    694 understanding security ■ can interact with other local-with-file-system files, but includes restrictions to the following: ■ cross-scripting (such as actionscript access to objects in other swf files). ■ calling system.Security.Allowdomain ■ using localconnection as sender or listener and regard...

  • Page 695

    About domains, cross-domain security, and swf files 695 the following table shows examples of compatible domains: the following table shows examples of incompatible domains: flash player 8 does not allow local swf files to communicate with the internet without a proper configuration. For information...

  • Page 696

    696 understanding security in flash player 7, exact-domain matching rules are used by default. That is, the settings and data for a file hosted at here.Xyz.Com are stored at here.Xyz.Com, the settings and data for a file hosted at there.Xyz.Com are stored at there.Xyz.Com, and so on. System.Exactset...

  • Page 697

    About domains, cross-domain security, and swf files 697 the following issue affects only swf files published for flash player 7. When the receiver is https, and the sender is a local swf file, allowdomain() is called, even though allowinsecuredomain() should be called. However, in flash player 8, wh...

  • Page 698

    698 understanding security the opposite situation can also occur; that is, you might create a child swf file that wants to allow its parent to script it, but doesn’t know what the domain of its parent swf file will be (meaning, it’s a swf file that might be loaded by a variety of domains). In this s...

  • Page 699

    About domains, cross-domain security, and swf files 699 because flash player 7 and later versions implement exact-domain matching rules instead of superdomain matching rules, you might have to modify existing scripts if you want to read them from files that are published for flash player 7 or 8. (yo...

  • Page 700

    700 understanding security ■ the swf files are not in the same domain (for example, one file is at www.Domain.Com and one is at store.Domain.Com). You must make the following changes: ■ if the called swf file is published for flash player 7 or later, include system.Security.Allowdomain or localconne...

  • Page 701

    About domains, cross-domain security, and swf files 701 for further information on system.Security.Allowdomain() , cross-scripting, and cross- domain scripting, see allowdomain (security.Allowdomain method) in the actionscript 2.0 language reference. For example, suppose main.Swf is served from www....

  • Page 702

    702 understanding security server-side policy files for permitting access to data a flash document can load data from an external source by using one of the following data loading calls: xml.Load() , xml.Sendandload() , loadvars.Load() , loadvars.Sendandload() , loadvariables() , loadvariablesnum(),...

  • Page 703

    Server-side policy files for permitting access to data 703 for example, a policy file located at https://www.Macromedia.Com:8080/crossdomain.Xml applies only to data loading calls made to www.Macromedia.Com over https at port 8080. An exception to this rule is the use of an xmlsocket object to conne...

  • Page 704

    704 understanding security if the swf file you are downloading comes from an https server, but the swf file loading it is on an http server, you need to add the secure="false" attribute to the access-from> tag, as shown in the following code: a policy file that contains no tags has the same effect a...

  • Page 705

    Server-side policy files for permitting access to data 705 if you want to use a policy file in a custom location on the server, you must call system.Security.Loadpolicyfile before you make any requests that depend on the policy file, such as the following: system.Security.Loadpolicyfile("http://www....

  • Page 706

    706 understanding security in this example, flash player tries to retrieve a policy file from the specified host and a port. Any port can be used if the policy file is not in the default (root) directory; otherwise the port is limited to 1024 and higher (as with earlier players). When a connection i...

  • Page 707

    Http to https protocol access between swf files 707 http to https protocol access between swf files you must use an allowdomain handler or method to permit a swf file in one domain to be accessed by a swf file in another domain. However, if the swf file being accessed is hosted at a site that uses a...

  • Page 708

    708 understanding security the following code shows an example of the changes you might have to make: // commands in a flash player 6 swf file at https://www.Somesite.Com // to allow access by flash player 7 swf files that are hosted // at http://www.Somesite.Com or at http://www.Someothersite.Com s...

  • Page 709

    Http to https protocol access between swf files 709 ■ if the called file is published for flash player 6 and you want to port the called file to flash player 7, include system.Security.Allowinsecuredomain or localconnection.Allowinsecuredomain in the called file, using exact domain-name matching, as...

  • Page 710

    710 understanding security.

  • Page 711

    711 18 chapter 18 debugging applications macromedia flash basic 8 and macromedia flash professional 8 provide several tools for testing actionscript in your swf files. The debugger lets you find errors in a swf file while it’s running in the flash debug player (see “debugging your scripts” on page 7...

  • Page 712

    712 debugging applications when you use the control > test movie command to test swf files that implement keyboard controls (tabbing, keyboard shortcuts created using key.Addlistener() , and so on), select control > disable keyboard shortcuts. Selecting this option prevents the authoring environment...

  • Page 713

    Debugging your scripts 713 to activate the debugger in test mode: ■ select control > debug movie. This command exports the swf file with debugging information (the swd file) and enables debugging of the swf file. It opens the debugger and opens the swf file in test mode. For more information, see th...

  • Page 714

    714 debugging applications debugging a swf file from a remote location you can debug a remote swf file by using the stand-alone, activex, or plug-in version of flash player. To find these versions of flash player, look in the following directory in windows or macintosh: flash install directory\playe...

  • Page 715

    Debugging your scripts 715 6. In flash, select window > debugger. 7. In the debugger, select enable remote debugging from the pop-up menu (at the upper right of the panel). To activate the debugger from a remote location: 1. Open the flash authoring application. 2. In a browser or in the debug versi...

  • Page 716

    716 debugging applications 4. When a connection is established, a password prompt appears. Enter your debugging password if you set one. The display list of the swf file appears in the debugger. If the swf file doesn’t play, the debugger might be paused, so click continue to start it. Displaying and...

  • Page 717

    Debugging your scripts 717 the display list updates automatically as the swf file plays. If a movie clip is removed from the swf file at a specific frame, that movie clip, along with its variable and variable name, is also removed from the display list in the debugger. However, if you mark a variabl...

  • Page 718

    718 debugging applications if you add a local variable to the watch list, its value appears only when flash player is stopped at a line of actionscript where that variable is in scope. All other variables appear while the swf file is playing. If the debugger can’t find the value of the variable, the...

  • Page 719

    Debugging your scripts 719 displaying movie clip properties and changing editable properties the debugger’s properties tab shows all the property values of any movie clip on the stage. You can change a value and see its effect in the swf file while it runs. Some movie clip properties are read-only a...

  • Page 720

    720 debugging applications to modify a property value: ■ double-click the value, and enter a new value. The value cannot be an expression. For example, you can enter 50 or "clearwater", but you cannot enter x + 50. The value can be a string (any value surrounded by quotation marks [""]), a number, o...

  • Page 721

    Debugging your scripts 721 ■ press control+shift+b (windows) or command+shift+b (macintosh). To set and remove breakpoints in the debugger, do one of the following: ■ click in the left margin. A red dot indicates a breakpoint. ■ click the toggle breakpoint or remove all breakpoints button above the ...

  • Page 722

    722 debugging applications an example of the asbreakpoints.Xml is as follows: the xml file consists of the following tags: flash_breakpoints this node has an attribute, called version , that indicates the version of the xml file. Flash 8 is version 1.0. File a child node of flash_breakpoints . This ...

  • Page 723

    Debugging your scripts 723 when you click the button, the breakpoint is reached and flash player pauses. You can now bring the debugger to the first line of myfunction() wherever it is defined in the document. You can also continue through or exit out of the function. As you step through lines of co...

  • Page 724

    724 debugging applications step out advances the debugger out of a function. This button works only if you are currently stopped in a user-defined function; it moves the yellow arrow to the line after the line where that function was called. In the previous example, if you place a breakpoint at line...

  • Page 725

    Using the output panel 725 to work with the contents of the output panel, click the pop-up menu in the upper right corner to see your options. The following table lists the options available on the output panel’s pop-up menu: menu item what it does word wrap toggles whether long lines wrap automatic...

  • Page 726

    726 debugging applications for more information on the output panel, see the following topics: ■ “listing a swf file’s objects” on page 726 ■ “listing a swf file’s variables” on page 727 ■ “about displaying text field properties for debugging” on page 728 ■ “using the trace statement” on page 728 ■ ...

  • Page 727

    Using the output panel 727 listing a swf file’s variables in test mode, the list variables command shows a list of all the variables currently in the swf file. This list is especially useful for finding the correct variable target path and variable name. Unlike the debugger, the list does not update...

  • Page 728

    728 debugging applications about displaying text field properties for debugging to obtain debugging information about textfield objects, you can use the debug > list variables command in test mode. The output panel uses the following conventions to show textfield objects: ■ if a property is not foun...

  • Page 729

    Using the output panel 729 to use the trace statement in a script: 1. Select frame 1 of the timeline, and add the following code in the actions panel: this.Createemptymovieclip("img_mc", 10); var mcllistener:object = new object(); mcllistener.Onloadinit = function(target_mc:movieclip) { trace(target...

  • Page 730

    730 debugging applications.

  • Page 731

    731 19 chapter 19 best practices and coding conventions for actionscript 2.0 macromedia flash designers and developers must write code and structure applications in a way that is intuitive and beneficial to themselves as well as to the other people who are working on the same project. This is partic...

  • Page 732

    732 best practices and coding conventions for actionscript 2.0 ■ when you are learning or teaching flash and actionscript learning how to build applications by using best practices and following coding conventions reduces the need to relearn particular methodologies. If students learning flash pract...

  • Page 733

    Naming conventions 733 using naming conventions for your variable names can serve the following important functions: ■ they make your code readable so that you can immediately identify a variable’s data type. This can help students, those learning code, or developers unfamiliar with your code. ■ the...

  • Page 734

    734 best practices and coding conventions for actionscript 2.0 general naming guidelines this section reviews naming guidelines for writing actionscript code. Naming conventions are important for writing logical code. The primary purpose is to improve the readability of your actionscript 2.0 code. R...

  • Page 735

    Naming conventions 735 the following table lists reserved keywords in actionscript 2.0 that cause errors in your scripts when used as variable names: the following words are reserved for future use in flash, from the ecmascript (ecma-262) edition 4 draft language specification. Avoid using these wor...

  • Page 736

    736 best practices and coding conventions for actionscript 2.0 naming variables variable names can only contain letters, numbers, and dollar signs ( $ ). Do not begin variable names with numbers. Variables must be unique and they are case-sensitive in flash player 7 and later. For example, avoid the...

  • Page 737

    Naming conventions 737 ■ don’t use variables that are parts of common programming constructs. Don’t use language constructs if you are aware of them in other programming languages, even if flash does not include or support these language constructs. For example, do not use the following keywords as ...

  • Page 738

    738 best practices and coding conventions for actionscript 2.0 ■ don’t use acronyms and abbreviations. The exception to this rule is if acronyms or abbreviations represent the standard way to use a term (such as html or cfm). For commonly used acronyms, use mixed cases for improved readability, such...

  • Page 739

    Naming conventions 739 naming functions and methods use the following guidelines when you name functions and methods in your code. For information on writing functions and methods, see chapter 6, “functions and methods.” ■ use descriptive names. ■ use mixed case for concatenated words. A good exampl...

  • Page 740

    740 best practices and coding conventions for actionscript 2.0 the following guidelines apply to naming classes: ■ begin a class name with an uppercase letter. ■ write class names in mixed case when it’s a compound or concatenated word. Begin with an uppercase letter for a compound or concatenated w...

  • Page 741

    Naming conventions 741 naming packages it’s common for package names to use “reverse domain” naming convention. Examples of reverse domain names include com.Macromedia for macromedia.Com, and org.Yourdomain for yourdomain.Org. Use the following guidelines when you name packages: ■ put the prefix for...

  • Page 742

    742 best practices and coding conventions for actionscript 2.0 naming custom components component names have an uppercase first letter, and any concatenated words are written in mixed case. For example, the following default user-interface component set uses concatenated words and mixed case: ■ chec...

  • Page 743

    Using comments in your code 743 for more information on writing comments in your actionscript code, see the following sections: ■ “writing good comments” on page 743 ■ “adding comments to classes” on page 744 writing good comments using comments consistently in your actionscript 2.0 code allows you ...

  • Page 744

    744 best practices and coding conventions for actionscript 2.0 ■ remove any superfluous comments from the code before you deploy your project. If you find that you have many comments in your actionscript code, consider whether you need to rewrite some of it. If you feel you must include many comment...

  • Page 745

    Actionscript coding conventions 745 use block, single-line, and trailing comments within the body of your class to comment on your actionscript code. For more information on using comments in class files, see “adding comments to classes” on page 744 . Actionscript coding conventions one of the most ...

  • Page 746

    746 best practices and coding conventions for actionscript 2.0 one of the most difficult parts of debugging a fla file is finding all the code. After you find all the code, you must figure out how it interacts with other pieces of code along with the fla file. If you put all your code in a single fr...

  • Page 747

    Actionscript coding conventions 747 however, placing the equivalent actionscript code on a timeline appears as follows: // good code mybtn.Onrelease = function() { // do something. }; for more information on actionscript syntax, see “formatting actionscript syntax” on page 764 . Handling scope scope...

  • Page 748

    748 best practices and coding conventions for actionscript 2.0 avoiding absolute targets (_root) you can use several methods to target instances that let you avoid using _root ; these methods are discussed later in this section. Avoid using _root in actionscript 2.0 because swf files that load into ...

  • Page 749

    Actionscript coding conventions 749 using the this keyword whenever possible, use the this keyword as a prefix instead of omitting the keyword, even if your code works without it. Use the this keyword to learn when a method or property belongs to a particular class. For example, for a function on a ...

  • Page 750

    750 best practices and coding conventions for actionscript 2.0 about scope in classes when you port code to actionscript 2.0 classes, you might have to change how you use the this keyword. For example, if you have a class method that uses a callback function (such as the loadvars class’s onload meth...

  • Page 751

    Actionscript coding conventions 751 structuring a class file you create classes in separate actionscript 2.0 files that are imported into a swf file when it is compiled. You create classes in separate actionscript 2.0 files that are imported into a swf file when you compile an application. To create...

  • Page 752

    752 best practices and coding conventions for actionscript 2.0 guidelines for creating a class remember the following guidelines when you create a class file: ■ place only one declaration per line. ■ don’t place multiple declarations on a single line. For example, format your declarations as shown i...

  • Page 753

    Actionscript coding conventions 753 ■ don’t overuse getter/setter functions in your class file. Getter/setter functions are excellent for a variety of purposes (see “about getter and setter methods” on page 255 ), however overuse might indicate that you could improve upon your application’s architec...

  • Page 754

    754 best practices and coding conventions for actionscript 2.0 about initialization for the initial values for variables, assign a default value or allow the value of undefined , as the following class example shows. When you initialize properties inline, the expression on the right side of an assig...

  • Page 755

    Actionscript coding conventions 755 one of the easiest ways to initialize code by using actionscript 2.0 is to use classes. You can encapsulate all your initialization for an instance within the class’s constructor function, or abstract it into a separate method, which you would explicitly call afte...

  • Page 756

    756 best practices and coding conventions for actionscript 2.0 use trace statements use trace statements in your documents to help you debug your code while authoring the fla file. For example, by using a trace statement and for loop, you can see the values of variables in the output panel, such as ...

  • Page 757

    Actionscript coding conventions 757 about the super prefix if you refer to a method in the parent class, prefix the method with super so that other developers know from where the method is invoked. The following actionscript 2.0 snippet demonstrates the use of proper scoping by using the super prefi...

  • Page 758

    758 best practices and coding conventions for actionscript 2.0 then create a new as or fla file and enter the following actionscript in the document: import socks; var mysock:socks = new socks("maroon"); trace(" -> "+mysock.Getcolor()); mysock.Setcolor("orange"); trace(" -> "+mysock.Getcolor()); the...

  • Page 759

    Actionscript coding conventions 759 in this code, you attach a movie clip instance from the library and use the with statement to modify its properties. When you do not specify a variable’s scope, you do not always know where you are setting properties, so your code can be confusing. In the previous...

  • Page 760

    760 best practices and coding conventions for actionscript 2.0 about using functions reuse blocks of code whenever possible. One way you can reuse code is by calling a function multiple times, instead of creating different code each time. Functions can be generic pieces of code; therefore, you can u...

  • Page 761

    Actionscript coding conventions 761 the following example puts functions into a class file. This is a best practice when you choose to use actionscript 2.0, because it maximizes code reusability. To reuse the functions in other applications, import the existing class rather than rewrite the code fro...

  • Page 762

    762 best practices and coding conventions for actionscript 2.0 about stopping code repetition the onenterframe event handler is useful because flash can use it to repeat code at the frame rate of a swf file. However, limit the amount of repetition that you use in a flash file as much as possible so ...

  • Page 763

    Actionscript and flash player optimization 763 optimizing your code remember the following guidelines when you optimize your code: ■ avoid calling a function multiple times from within a loop. It is better to include the contents of a small function inside the loop. ■ use native functions when possi...

  • Page 764

    764 best practices and coding conventions for actionscript 2.0 formatting actionscript syntax formatting actionscript 2.0 code in a standardized way is essential to writing maintainable code, and it’s easier for other developers to understand and modify. For example, it would be extremely difficult ...

  • Page 765

    Formatting actionscript syntax 765 macromedia recommends the following formatting points to help promote readability in your actionscript code. ■ put one blank line between paragraphs (modules) of actionscript. Paragraphs of actionscript code are groups of logically related code. Adding a blank line...

  • Page 766

    766 best practices and coding conventions for actionscript 2.0 ■ use spaces to separate all operators and their operands. Using spaces makes it is easier to distinguish between method calls and keywords, as the following example shows: //good var sum:number = 7 + 3; //bad var sum:number=7+3; an exce...

  • Page 767

    Formatting actionscript syntax 767 ■ align the second line with the start of the expression on the previous line of code. Writing conditional statements use the following guidelines when you write conditional statements: ■ place conditions on separate lines in if , else..If , and if..Else statements...

  • Page 768

    768 best practices and coding conventions for actionscript 2.0 you can write a conditional statement that returns a boolean value in two ways. The second example is preferable: if (cartarr.Length>0) { return true; } else { return false; } compare this example with the previous one: // better return ...

  • Page 769

    Formatting actionscript syntax 769 place braces around each statement when it is part of a control structure ( if..Else or for ), even if it contains only a single statement. The following example shows code that is written poorly: // bad if (numusers == 0) trace("no users found."); although this co...

  • Page 770

    770 best practices and coding conventions for actionscript 2.0 writing while and do..While statements you can write while statements using the following format: while (condition) { // statements } you can write do-while statements using the following format: do { // statements } while (condition); w...

  • Page 771

    Formatting actionscript syntax 771 you can write switch statements using the following format: switch (condition) { case a : // statements // falls through case b : // statements break; case z : // statements break; default : // statements break; } writing try..Catch and try..Catch..Finally statemen...

  • Page 772

    772 best practices and coding conventions for actionscript 2.0 about using listener syntax you can write listeners for events in several ways in flash 8. Some popular techniques are shown in the following code examples. The first example shows a properly formatted listener syntax, which uses a loade...

  • Page 773

    773 a appendix a error messages macromedia flash basic 8 and macromedia flash professional 8 provide compile-time error reporting when you publish to actionscript 2.0 (the default). The following table contains a list of error messages that the flash compiler can generate: error number message text ...

  • Page 774

    774 error messages 1112 a class may not extend itself. 1113 an interface may not extend itself. 1114 there is no interface defined with this name. 1115 a class may not extend an interface. 1116 an interface may not extend a class. 1117 an interface name is expected after the ‘implements’ keyword. 11...

  • Page 775

    775 1141 the name of this class, ‘’, conflicts with the name of another class that was loaded, ‘’. (this error occurs when the actionscript 2.0 compiler cannot compile a class because of the full name of an existing class is part of the conflicting class' name. For example, compiling class mx.Com.Ut...

  • Page 776

    776 error messages 1166 the class being compiled, ‘’, does not match the class that was imported, ‘’. (this error occurs when a class name is spelled with a different case from an imported class. For example, compiling class mx.Com.Util generates error 1166 if the statement import mx.Com appears in ...

  • Page 777

    777 1188 import statements are not allowed inside class or interface definitions. 1189 the class ‘’ cannot be imported because its leaf name is already resolved to the class that is being defined, ‘’. (for example, compiling class util generates error 1189 if the statement import mx.Util appears in ...

  • Page 778

    778 error messages 1206 member function '' is larger than 32k. 1207 anonymous function around line exceeds 32k span. 1208 code around line exceeds 32k span. 1210 the package name '' cannot also be used as a method name. 1211 the package name '' cannot also be used as a property name. 1212 the aso fi...

  • Page 779

    779 b appendix b deprecated flash 4 operators the following table lists flash 4–only operators, which are deprecated in actionscript 2.0. Do not use these operators unless you are publishing to flash player 4 and earlier. Operator description associativity not logical not right to left and logical a...

  • Page 780

    780 deprecated flash 4 operators.

  • Page 781

    781 c appendix c keyboard keys and key code values the following tables list all the keys on a standard keyboard and the corresponding key code values and ascii key code values that are used to identify the keys in actionscript: ■ “letters a to z and standard numbers 0 to 9” on page 781 ■ “keys on t...

  • Page 782

    782 keyboard keys and key code values c 67 67 d 68 68 e 69 69 f 70 70 g 71 71 h 72 72 i 73 73 j 74 74 k 75 75 l 76 76 m 77 77 n 78 78 o 79 79 p 80 80 q 81 81 r 82 82 s 83 83 t 84 84 u 85 85 v 86 86 w 87 87 x 88 88 y 89 89 z 90 90 0 48 48 1 49 49 2 50 50 3 51 51 4 52 52 5 53 53 letter or number key k...

  • Page 783

    783 6 54 54 7 55 55 8 56 56 9 57 57 a 65 97 b 66 98 c 67 99 d 68 100 e 69 101 f 70 102 g 71 103 h 72 104 i 73 105 j 74 106 k 75 107 l 76 108 m 77 109 n 78 110 o 79 111 p 80 112 q 81 113 r 82 114 s 83 115 t 84 116 u 85 117 v 86 118 w 87 119 x 88 120 y 89 121 z 90 122 letter or number key key code asc...

  • Page 784

    784 keyboard keys and key code values keys on the numeric keypad the following table lists the keys on a numeric keypad, with the corresponding key code values that are used to identify the keys in actionscript: function keys the following table lists the function keys on a standard keyboard, with t...

  • Page 785

    785 other keys the following table lists keys on a standard keyboard other than letters, numbers, numeric keypad keys, or function keys, with the corresponding key code values that are used to identify the keys in actionscript: f6 117 0 f7 118 0 f8 119 0 f9 120 0 f10 this key is reserved by the syst...

  • Page 786

    786 keyboard keys and key code values for additional key code and ascii values, use the actionscript at the beginning of this appendix and press the desired key to trace its key code. Left arrow 37 0 up arrow 38 0 right arrow 39 0 down arrow 40 0 insert 45 0 delete 46 127 num lock 144 0 scrlk 145 0 ...

  • Page 787

    787 d appendix d writing scripts for earlier versions of flash player actionscript has changed considerably with each release of the macromedia flash authoring tools and flash player. When you create content for macromedia flash player 8, you can use the full power of actionscript. You can still use...

  • Page 788

    788 writing scripts for earlier versions of flash player using flash 8 to create content for flash player 4 to use flash 8 to create content for flash player 4, specify flash player 4 on the flash tab of the publish settings dialog box (file > publish settings). Flash player 4 actionscript has only ...

  • Page 789

    Using flash 8 to create content for flash player 4 789 ■ the = operator in flash 4 was used for numeric equality. In flash 5 and later, == is the equality operator and = is the assignment operator. Any = operators in flash 4 files are automatically converted to == . ■ flash automatically performs ty...

  • Page 790

    790 writing scripts for earlier versions of flash player using slash syntax slash syntax ( / ) was used in flash 3 and 4 to indicate the target path of a movie clip or variable. In slash syntax, slashes are used instead of dots and variables are preceded with a colon, as shown in the following examp...

  • Page 791

    791 e appendix e object-oriented programming with actionscript 1.0 the information in this appendix comes from the macromedia flash mx documentation and provides information on using the actionscript 1.0 object model to write scripts. It is included here for the following reasons: ■ if you want to w...

  • Page 792

    792 object-oriented programming with actionscript 1.0 about actionscript 1.0 actionscript is an object-oriented programming language. Object-oriented programming uses objects, or data structures, to group together properties and methods that control the object’s behavior or appearance. Objects let y...

  • Page 793

    About actionscript 1.0 793 in this example, you create a function that needs two pieces of information, or parameters, to do its job: t and d . When you call the function to create new instances of the object, you pass it the parameters. The following code creates instances of the object biker calle...

  • Page 794

    794 object-oriented programming with actionscript 1.0 creating a custom object in actionscript 1.0 to create a custom object, you define a constructor function. A constructor function is always given the same name as the type of object it creates. You can use the keyword this inside the body of the ...

  • Page 795

    Assigning methods to a custom object in actionscript 1.0 795 assigning methods to a custom object in actionscript 1.0 you can define the methods of an object inside the object’s constructor function. However, this technique is not recommended because it defines the method every time you use the cons...

  • Page 796

    796 object-oriented programming with actionscript 1.0 to assign a method to a custom object: 1. Define the constructor function circle() : function circle(radius) { this.Radius = radius; } 2. Define the getarea() method of the circle object. The getarea() method calculates the area of the circle. In...

  • Page 797

    Defining event handler methods in actionscript 1.0 797 to define an event handler method in an object’s prototype object: 1. Create a movie clip symbol and set the linkage identifier to theid by selecting the symbol in the library panel and selecting linkage from the library pop-up menu. 2. In the a...

  • Page 798

    798 object-oriented programming with actionscript 1.0 this step registers the symbol whose linkage identifier is theid with the class myclipclass . All instances of myclipclass have event handler methods that behave as defined in step 4. They also behave the same as all instances of the movieclip cl...

  • Page 799

    Creating inheritance in actionscript 1.0 799 all constructor functions have a prototype property that is created automatically when the function is defined. The prototype property indicates the default property values for objects created with that function. You can use the prototype property to assi...

  • Page 800

    800 object-oriented programming with actionscript 1.0 adding getter/setter properties to objects in actionscript 1.0 you can create getter/setter properties for an object using the object.Addproperty() method. A getter function is a function with no parameters. Its return value can be of any type. I...

  • Page 801

    Using function object properties in actionscript 1.0 801 using function object properties in actionscript 1.0 you can specify the object to which a function is applied and the parameter values that are passed to the function, using the call() and apply() methods of the function object. Every functio...

  • Page 802

    802 object-oriented programming with actionscript 1.0 to invoke a function using the function.Call() method: ■ use the following syntax: myfunction.Call(thisobject, parameter1, ..., parametern) the method takes the following parameters: ■ the parameter thisobject specifies the value of this within t...

  • Page 803

    803 f appendix f terminology as with all scripting languages, actionscript uses its own terminology. Macromedia flash also uses unique terminology. The following list provides an introduction to important actionscript terms, and flash terms that relate to programming with actionscript and that are u...

  • Page 804

    804 terminology caching refers to information that is reused in your application, or information that is stored on your computer so it can be reused. For example, if you download an image from the internet, it’s often cached so you can view it again without downloading the image data. Callback funct...

  • Page 805

    805 data types describe the kind of information a variable or actionscript element can contain. The built-in actionscript data types are string, number, boolean, object, movieclip, function, null, and undefined. For more information, see “about data types” on page 72 . Device fonts are special fonts...

  • Page 806

    806 terminology functions are blocks of reusable code that can be passed parameters and can return a value. For more information, see “about functions and methods” on page 201 . Function literals are unnamed functions that you declare in an expression instead of in a statement. Function literals are...

  • Page 807

    807 methods are functions associated with a class. For example, sorton() is a built-in method associated with the array class. You can also create functions that act as methods, either for objects based on built-in classes or for objects based on classes that you create. For example, in the followin...

  • Page 808

    808 terminology parameters (also called arguments) are placeholders that let you pass values to functions. For example, the following welcome() function uses two values it receives in the parameters firstname and hobby : function welcome(firstname:string, hobby:string):string { var welcometext:strin...

  • Page 809

    809 string is a sequence of characters, and a data type. See “about strings and the string class” on page 450 for more information. String literal is a sequence of characters enclosed by straight quote characters. The characters are themselves a data value, not a reference to data. A string literal ...

  • Page 810

    810 terminology variables are identifiers that hold values of any data type. Variables can be created, changed, and updated. The values they store can be retrieved for use in scripts. In the following example, the identifiers on the left side of the equal signs are variables: var x:number = 5; var n...

  • Page 811

    811 index symbols \" 460 \’ 460 \b 460 \f 460 460 \r 460 \t 460 \unnnn 460 \xnn 460 _lockroot, using 748 _root scope 123 numerics 9-slice scaling about 556 enabling 557 scale9grid property 557 understanding 556 using 558 a actions panel about 35, 36 actions toolbox 36 coding in 38 defined 803 pop...

  • Page 812

    812 index animations continuing 493 that run continuously 494 anonymous function defined 803 using 210 writing 208 anti-alias defined 803 for animation and readability 408 anti-alias text about 406 advanced value 409 creating table 412 flash player support 406 limitations 407 modifying sharpness and...

  • Page 813

    Index 813 bindings creating a one-way binding 580 creating a two-way binding 582 creating with actionscript 580 bitmap graphics 803 text 408 bitmap caching about 369, 480 advantages and disadvantages 371 and alpha channel masking 377 and filters 501 caching a movie clip 373 defined 370 enabling 369 ...

  • Page 814

    814 index classes about built-in 227 accessing built-in properties 297 and aso files 282 and constructor functions 268 and inheritance 301 and instance variables 272 and polymorphism 308 and scope 262, 283 as blueprints 229 as data types 226 assigning to an instance in flash 279 assigning to movie c...

  • Page 815

    Index 815 collisions, detecting 576 between movie clip and stage point 577 between movie clips 577 color matrix filter about 525 using 475, 525 colors in actions toolbox 51 values, setting 572 comments about 131 and syntax coloring 132 best practices 743 cluttered or clustered 132 in class files 274...

  • Page 816

    816 index converting 72 defined 72, 805 determining type 85 movieclip 76 null 77 number 78 object 78 primitive 73 string 79 undefined 80 void 81 data, external 633, 677 access between cross-domain swfs 700, 704 and loadvars object 640 and messages 663 and server-side scripts 638 and xml 652 and xmls...

  • Page 817

    Index 817 e easing about 488 defining 482 with code 490 ecma-262 specification 115 effects blending modes 538 brightness 525 brightness and color 474 brightness tween 476 fading 472 grayscale 475 noise 535 panning an image 478 effects. See filters elements, of an array 163 embedded characters adding...

  • Page 818

    818 index filters adjusting properties 530 and actionscript 505 and error handling 504 and memory usage 504 and out-of-memory error 504 and performance 504 and transparency 505 animating 532 applying to instances 503 array 531 changing brightness level 526 defining 498 getting and setting 501 glow f...

  • Page 819

    Index 819 for..In loops 158 form feed character 460 formatting code 50, 51 formatting text using 415 frame rate about 471 and onenterframe 471 choosing 471 with tween class 492 frame scripts about 33 defined 805 fscommand() function commands and arguments 664 communicating with director 666 using 66...

  • Page 820

    820 index gradient glow filter about 515 using 516 grayscale image 475 grid fit types, using 417 h handlers. See event handlers hittest() method 576 html example of using with styles 431 styling built-in tags 430 supported tags 437 tags enclosed in quotation marks 437 text field 386 using tag to flo...

  • Page 821

    Index 821 j javascript alert statement 728 and actionscript 115 and netscape 666 international standard 115 sending messages to 664 jpeg files embedding in text fields 445 loading into movie clips 357, 593 jumping to a url 564 k key codes, ascii function keys 784 getting 569 letter and number keys 7...

  • Page 822

    822 index m macromedia director, communicating with 666 manipulating numbers 78 masks 376 and alpha channel masking 377 and device fonts 377 scripting to create 554 strokes ignored 376, 540 mediaplayback component using cue points with 616 members (methods and properties) public, private, and static...

  • Page 823

    Index 823 loading into movie clips 598 preloading 599, 609 reading id3 tags 601 multidimensional arrays, about 169 multiple languages, using in scripts 57 n named functions 208 defined 807 naming classes and objects, best practices 739 naming conventions 732 booleans 738 classes and objects 739 func...

  • Page 824

    824 index relational and equality 190 unary 186 using assignment 194 using in flash 199 using with strings 182 order of execution (operator) operator associativity 179 operator precedence 179 organizing scripts actionscript 1.0 and actionscript 2.0 69 attaching to objects 746 coding conventions 745 ...

  • Page 825

    Index 825 reserved words about 139 built-in class names 140 future reserved words 139 listed 139 other recommendations 140 see also keywords resources, additional 14 return statement 770 _root property and loaded movie clips 356 runtime data binding about 579 creating a two-way binding 582 with chec...

  • Page 826

    826 index slash syntax about 124 not supported in actionscript 2.0 124 using 790 socket connections about 661 sample script 662 sounds attaching to timeline 573 balance control 575 controlling 573 see also external media special characters 80 stage, attaching symbols to the 362 statements about 141 ...

  • Page 827

    Index 827 syntax case sensitivity 117 checking 55 slash 124 syntax color options, setting in the actions panel 52 system event, defined 329 requirements, for actionscript 2.0 10 t tab character 460 tab key, and test movie 712 target path and dot syntax 118 and nested instances 120 and targeting an i...

  • Page 828

    828 index transferring variables between movie and server 640 transition class animating brightness level 526 transitionmanager class about 481 and easing 482 using 485 with drawing api 554 with tween class 496 transitions adding with actionscript 485 adding with behaviors 483 defining 484 transpare...

  • Page 829

    Index 829 variables, global 97 vector graphics 810 video about 603 about external flv files 604 adding seek functionality 617 and macintosh 624 configuring the server for flv 623 creating a banner 607 creating a progress bar to load flv 630 creating a video object 605 creating flv files 604 cue poin...

  • Page 830

    830 index.