background image

ActionScript Language Reference

Содержание FLASH MX

Страница 1: ...ActionScript Language Reference ...

Страница 2: ...e then you do so at your own risk Macromedia provides these links only as a convenience and the inclusion of the link does not imply that Macromedia endorses or accepts any responsibility for the content on those third party sites Speech compression and decompression technology licensed from Nellymoser Inc www nellymoser com Sorenson Spark video compression and decompression technology licensed fr...

Страница 3: ...ct inequality 32 modulo 34 modulo assignment 35 bitwise AND 36 logical AND 38 bitwise AND assignment 40 parentheses 41 minus 43 multiplication 44 multiplication assignment 45 comma 46 dot 48 type 50 conditional 52 division 53 comment delimiter 54 comment delimiter 55 division assignment 56 array access 57 bitwise XOR 60 bitwise XOR assignment 61 object initializer 62 bitwise OR 64 logical OR 65 bi...

Страница 4: ...sibility class 92 Accessibility isActive 93 Accessibility updateProperties 94 _accProps 95 arguments object 98 arguments callee 99 arguments caller 100 arguments length 101 Array 102 Array class 103 Array concat 106 Array join 107 Array length 108 Array pop 109 Array push 110 Array reverse 111 Array shift 112 Array slice 113 Array sort 114 Array sortOn 117 Array splice 121 Array toString 123 Array...

Страница 5: ...d 159 Button tabIndex 160 Button _target 161 Button trackAsMenu 162 Button _url 163 Button useHandCursor 164 Button _visible 165 Button _width 166 Button _x 167 Button _xmouse 168 Button _xscale 169 Button _y 170 Button _ymouse 171 Button _yscale 172 Camera class 173 Camera activityLevel 175 Camera bandwidth 176 Camera currentFps 177 Camera fps 178 Camera get 179 Camera height 181 Camera index 182...

Страница 6: ...textMenuItem onSelect 226 ContextMenuItem separatorBefore 227 ContextMenuItem visible 228 continue 229 CustomActions class 231 CustomActions get 232 CustomActions install 233 CustomActions list 235 CustomActions uninstall 236 Date class 237 Date getDate 241 Date getDay 242 Date getFullYear 243 Date getHours 244 Date getMilliseconds 245 Date getMinutes 246 Date getMonth 247 Date getSeconds 248 Date...

Страница 7: ...274 Date setYear 275 Date toString 276 Date UTC 277 default 278 delete 279 do while 281 duplicateMovieClip 283 dynamic 284 else 286 else if 287 endinitclip 288 Error class 289 Error message 291 Error name 292 Error toString 293 escape 294 eval 295 extends 297 false 299 _focusrect 300 for 301 for in 303 fscommand 305 function 308 Function class 310 Function apply 311 Function call 313 get 315 getPr...

Страница 8: ...i 353 Key getCode 354 Key HOME 355 Key INSERT 356 Key isDown 357 Key isToggled 358 Key LEFT 360 Key onKeyDown 361 Key onKeyUp 362 Key PGDN 363 Key PGUP 364 Key removeListener 365 Key RIGHT 366 Key SHIFT 367 Key SPACE 368 Key TAB 369 Key UP 370 _level 371 loadMovie 372 loadMovieNum 374 loadVariables 376 loadVariablesNum 378 LoadVars class 380 LoadVars addRequestHeader 382 LoadVars contentType 384 L...

Страница 9: ... 421 Math acos 422 Math asin 423 Math atan 424 Math atan2 425 Math ceil 426 Math cos 427 Math E 428 Math exp 429 Math floor 430 Math log 431 Math LN2 432 Math LN10 433 Math LOG2E 434 Math LOG10E 435 Math max 436 Math min 437 Math PI 438 Math pow 439 Math random 440 Math round 441 Math sin 442 Math sqrt 443 Math SQRT1_2 444 Math SQRT2 445 Math tan 446 Microphone class 447 Microphone activityLevel 4...

Страница 10: ...beginFill 498 MovieClip beginGradientFill 499 MovieClip clear 503 MovieClip createEmptyMovieClip 504 MovieClip createTextField 505 MovieClip _currentframe 507 MovieClip curveTo 508 MovieClip _droptarget 510 MovieClip duplicateMovieClip 511 MovieClip enabled 512 MovieClip endFill 513 MovieClip focusEnabled 514 MovieClip _focusrect 515 MovieClip _framesloaded 516 MovieClip getBounds 517 MovieClip ge...

Страница 11: ...562 MovieClip onMouseUp 563 MovieClip onPress 564 MovieClip onRelease 565 MovieClip onReleaseOutside 566 MovieClip onRollOut 567 MovieClip onRollOver 568 MovieClip onSetFocus 569 MovieClip onUnload 570 MovieClip _parent 571 MovieClip play 572 MovieClip prevFrame 573 MovieClip _quality 574 MovieClip removeMovieClip 575 MovieClip _rotation 576 MovieClip setMask 577 MovieClip _soundbuftime 578 MovieC...

Страница 12: ...eClipLoader removeListener 617 MovieClipLoader unloadClip 619 NaN 620 Infinity 621 NetConnection class 622 NetConnection connect 624 NetStream class 625 NetStream bufferLength 627 NetStream bufferTime 628 NetStream bytesLoaded 629 NetStream bytesTotal 631 NetStream close 633 NetStream currentFps 634 NetStream onStatus 635 NetStream pause 637 NetStream play 638 NetStream seek 640 NetStream setBuffe...

Страница 13: ...AsBitmap 693 printAsBitmapNum 695 PrintJob class 697 PrintJob addPage 699 PrintJob send 703 PrintJob start 704 printNum 706 private 707 public 709 _quality 710 removeMovieClip 711 return 712 _root 713 Selection class 714 Selection addListener 715 Selection getBeginIndex 716 Selection getCaretIndex 717 Selection getEndIndex 718 Selection getFocus 720 Selection onSetFocus 721 Selection removeListene...

Страница 14: ...dComplete 768 Sound position 769 Sound setPan 770 Sound setTransform 771 Sound setVolume 773 Sound start 774 Sound stop 775 _soundbuftime 776 Stage class 777 Stage addListener 778 Stage align 779 Stage height 780 Stage onResize 781 Stage removeListener 782 Stage scaleMode 783 Stage showMenu 784 Stage width 785 startDrag 786 static 787 stop 789 stopAllSounds 790 stopDrag 791 String 792 String class...

Страница 15: ...language 830 System capabilities localFileReadDisable 832 System capabilities manufacturer 833 System capabilities os 834 System capabilities pixelAspectRatio 835 System capabilities playerType 836 System capabilities screenColor 837 System capabilities screenDPI 838 System capabilities screenResolutionX 839 System capabilities screenResolutionY 840 System capabilities serverString 841 System capa...

Страница 16: ...890 TextField html 891 TextField htmlText 892 TextField length 893 TextField maxChars 894 TextField maxhscroll 895 TextField maxscroll 896 TextField menu 897 TextField mouseWheelEnabled 898 TextField multiline 899 TextField _name 900 TextField onChanged 901 TextField onKillFocus 902 TextField onScroller 903 TextField onSetFocus 905 TextField _parent 906 TextField password 907 TextField _quality 90...

Страница 17: ...ld 947 TextFormat bullet 948 TextFormat color 949 TextFormat font 950 TextFormat getTextExtent 951 TextFormat indent 954 TextFormat italic 955 TextFormat leading 956 TextFormat leftMargin 957 TextFormat rightMargin 958 TextFormat size 959 TextFormat tabStops 960 TextFormat target 961 TextFormat underline 962 TextFormat url 963 TextSnapshot object 964 TextSnapshot findText 965 TextSnapshot getCount...

Страница 18: ... XML cloneNode 1017 XML contentType 1019 XML createElement 1020 XML createTextNode 1021 XML docTypeDecl 1023 XML firstChild 1024 XML getBytesLoaded 1026 XML getBytesTotal 1027 XML hasChildNodes 1028 XML ignoreWhite 1029 XML insertBefore 1031 XML lastChild 1032 XML load 1034 XML loaded 1036 XML nextSibling 1037 XML nodeName 1038 XML nodeType 1040 XML nodeValue 1042 XML onData 1044 XML onLoad 1045 X...

Страница 19: ...string specific 1077 ge greater than or equal to string specific 1078 gt greater than string specific 1079 _highquality 1080 inequality 1081 ifFrameLoaded 1082 int 1083 le less than or equal to string specific 1084 length 1085 lt less than string specific 1086 maxscroll 1087 mbchr 1088 mblength 1089 mbord 1090 mbsubstring 1091 MovieClip _highquality 1092 ne not equal string specific 1093 not 1094 ...

Страница 20: ...20 Contents ...

Страница 21: ...LA file s Publish Settings dialog box There are two types of entries in this manual Individual entries for operators keywords functions variables properties methods and statements Class entries which provide general information about built in classes Use the information in the sample entries to interpret the structure and conventions used in these types of entries This chapter contains the followi...

Страница 22: ...de The required portion of the syntax is in code font Both the code that you provide and data type information are in italicized code font Data types can be distinguished from code that you provide by the colon that always precedes data type information Brackets indicate optional parameters Parameters This section describes any parameters listed in the syntax Returns This section identifies what i...

Страница 23: ...e standard elements usage description and so on of other entries Method property and event handler listings The methods properties and event handlers of a class are listed alphabetically after the class entry Examples Folder A set of ActionScript example files can be found in the HelpExamples folder in the Flash installation directory Typical paths to this folder are Windows Program Files Macromed...

Страница 24: ...24 Chapter 1 Introduction ...

Страница 25: ...erator expression subtracts 1 from expression and returns the result The post decrement form of the operator expression subtracts 1 from the expression and returns the initial value of expression the value prior to the subtraction For more information see Operator precedence and associativity in Using ActionScript in Flash Example The pre decrement form of the operator decrements x to 2 x 1 2 and ...

Страница 26: ...26 Chapter 2 ActionScript Language Reference The following example loops from 10 to 1 and each iteration of the loop decreases the counter variable i by 1 for var i 10 i 0 i trace i ...

Страница 27: ...itial value of expression the value prior to the addition The pre increment form of the operator increments x to 2 x 1 2 and returns the result as y var x Number 1 var y Number x trace x x traces x 2 trace y y traces y 2 The post increment form of the operator increments x to 2 x 1 2 and returns the original value of x as the result y var x Number 1 var y Number x trace x x traces x 2 trace y y tr...

Страница 28: ...8 9 10 This script shows the following result in the Output panel 1 2 3 4 5 6 7 8 9 10 The following example uses as a post increment operator in a while loop using a while loop var a Array var a Array new Array var i Number 0 while i 10 a push i trace a toString traces 0 1 2 3 4 5 6 7 8 9 The following example uses as a post increment operator in a for loop using a for loop var a Array var a Arra...

Страница 29: ...o true The following expressions illustrate the result of using the logical NOT operator true returns false false returns true For more information see Operator precedence and associativity in Using ActionScript in Flash Example In the following example the variable happy is set to false The if condition evaluates the condition happy and if the condition is true the trace statement sends a string ...

Страница 30: ...e the expression 2 3 is equal to the expression 1 4 when compared by value Comparison by reference means that two expressions are equal only if they both refer to the same object array or function Values inside the object array or function are not compared When comparing by value if expression1 and expression2 are different data types ActionScript will attempt to convert the data type of expressio...

Страница 31: ...o foo false The following example illustrates comparison by reference with two arrays var a Array 1 2 3 var b Array 1 2 3 trace a 1 2 3 trace b 1 2 3 trace a b true a b trace a 1 2 3 trace b 1 2 3 trace a b false trace statement output 1 2 3 1 2 3 true 1 2 3 1 2 3 false See also logical NOT strict inequality logical AND logical OR equality strict equality ...

Страница 32: ...tion of equal depends on the data types being compared as illustrated in the following list Numbers strings and Boolean values are compared by value Objects arrays and functions are compared by reference A variable is compared by value or by reference depending on its type For more information see Operator precedence and associativity in Using ActionScript in Flash Example The comments in the foll...

Страница 33: ... strict inequality 33 trace s1 n true trace s1 b true See also logical NOT inequality logical AND logical OR equality strict equality ...

Страница 34: ...perator attempts to convert them to numbers The expression can be a number or string that converts to a numeric value For more information see Automatic data typing and Operator precedence and associativity in Using ActionScript in Flash Example The following numeric example uses the modulo operator trace 12 5 traces 2 trace 4 3 2 1 traces 0 0999999999999996 trace 4 4 traces 0 The first trace retu...

Страница 35: ...ic compound assignment assigns expression1 the value of expression1 expression2 The following two expressions are equivalent x y x x y For more information see Operator precedence and associativity in Using ActionScript in Flash Example The following example assigns the value 4 to the variable x var x Number 14 var y Number 5 trace x y output 4 See also modulo ...

Страница 36: ...rded when they are converted so the value is still 32 bit Negative numbers are converted to an unsigned hex value using the two s complement notation with the minimum being 2147483648 or 0x800000000 numbers less than the minimum are converted to two s complement with greater precision and then have the most significant digits discarded as well The return value is interpreted as a two s complement ...

Страница 37: ... bitwise AND 37 trace 0xFFFFFFFF 1 1 trace 4294967295 1 1 trace 4294967295 4294967295 1 See Also bitwise AND assignment bitwise XOR bitwise XOR assignment bitwise OR bitwise OR assignment bitwise NOT ...

Страница 38: ...s to true the final result is true otherwise it is false For more information see Operator precedence and associativity in Using ActionScript in Flash Example The following example uses the logical AND operator to perform a test to determine if a player has won the game The turns variable and the score variable are updated when a player takes a turn or scores points during the game The script show...

Страница 39: ... logical AND 39 See also logical NOT inequality strict inequality logical OR equality strict equality ...

Страница 40: ...r assigns expression1 the value of expression1 expression2 For example the following two expressions are equivalent x y x x y For more information see Operator precedence and associativity in Using ActionScript in Flash Example The following example assigns the value 9 to x var x Number 15 var y Number 9 trace x y output 9 See also bitwise AND bitwise XOR bitwise XOR assignment bitwise OR bitwise ...

Страница 41: ... the normal precedence order and cause the expressions within the parentheses to be evaluated first When parentheses are nested the contents of the innermost parentheses are evaluated before the contents of the outer ones Usage 2 Evaluates a series of expressions separated by commas in sequence and returns the result of the final expression Usage 3 Surrounds one or more parameters and passes them ...

Страница 42: ...n bar b 10 trace foo bar a b outputs 23 Usage 3 The following example shows the use of parentheses with functions var today Date new Date trace today getFullYear traces current year function traceParameter param Void trace param traceParameter 2 2 traces 4 See also with ...

Страница 43: ...hen both expressions are integers the difference is an integer When either or both expressions are floating point numbers the difference is a floating point number For more information see Operator precedence and associativity in Using ActionScript in Flash Example Usage 1 The following statement reverses the sign of the expression 2 3 trace 2 3 output 5 Usage 2 The following statement subtracts t...

Страница 44: ...e product is an integer If either or both expressions are floating point numbers the product is a floating point number For more information see Operator precedence and associativity in Using ActionScript in Flash Example Usage 1 The following statement multiplies the integers 2 and 3 trace 2 3 output 6 The result 6 is an integer Usage 2 This statement multiplies the floating point numbers 2 0 and...

Страница 45: ...on1 expression2 For example the following two expressions are equivalent x y x x y For more information see Operator precedence and associativity in Using ActionScript in Flash Example Usage 1 The following example assigns the value 50 to the variable x var x Number 5 var y Number 10 trace x y output 50 Usage 2 The second and third lines of the following example calculate the expressions on the ri...

Страница 46: ...i 1 j 2 The following example uses the comma operator without the parentheses operator and illustrates that the comma operator returns only the value of the first expression without the parentheses operator var v Number 0 v 4 5 6 trace v output 4 The following example uses the comma operator with the parentheses operator and illustrates that the comma operator returns the value of the last express...

Страница 47: ...us example except for the addition of the parentheses operator and illustrates once again that when used with the parentheses operator the comma operator returns the value of the last expression in the series var v Number 0 var z Number 0 v v 4 z v 6 trace v output 6 trace z output 1 See also parentheses ...

Страница 48: ...ot operator Returns The method property or movie clip named on the right side of the dot Description Operator used to navigate movie clip hierarchies to access nested child movie clips variables or properties The dot operator is also used to test or set the properties of an object or top level class execute a method of an object or top level class or create a data structure For more information se...

Страница 49: ...er_mc createTextField date_txt this getNextHighestDepth 0 0 100 22 this container_mc date_txt autoSize true this container_mc date_txt text new Date The dot operator is used when targeting instances within the SWF file and when you need to set properties and values for those instances ...

Страница 50: ... a function parameter in a function definition this operator specifies the variable type expected for that parameter Types are a compile time only feature All types are checked at compile time and errors are generated when there is a mismatch For more information see Appendix A Error Messages in Using ActionScript in Flash Mismatches can occur during assignment operations function calls and class ...

Страница 51: ...mber function randomInt integer Number Number return Math round Math random integer trace randomInt 8 Usage 3 The following example defines a function named squareRoot that takes a parameter named val of the Number type and returns the square root of val also a Number type function squareRoot val Number Number return Math sqrt val trace squareRoot 121 See Also var function ...

Страница 52: ...of expression2 otherwise it returns the value of expression3 For more information see Operator precedence and associativity in Using ActionScript in Flash Example The following statement assigns the value of variable x to variable z because expression1 evaluates to true var x Number 5 var y Number 10 var z x 6 x y trace z returns 5 The following example shows a conditional statement written in sho...

Страница 53: ...ssion2 The result of the division operation is a double precision floating point number For more information see Operator precedence and associativity in Using ActionScript in Flash Example The following statement divides the current width and height of the Stage and then displays the result in the Output panel trace Stage width 2 trace Stage height 2 For a default Stage width and height of 550 x ...

Страница 54: ...the ActionScript interpreter For more information see Deprecated Flash 4 operators in Using ActionScript in Flash Example The following script uses comment delimiters to identify the first third fifth and seventh lines as comments record the X position of the ball movie clip var ballX Number ball_mc _x record the Y position of the ball movie clip var ballY Number ball_mc _y record the X position o...

Страница 55: ...mpting to nest comments also returns an error message After an opening comment tag is used the first closing comment tag will end the comment regardless of the number of opening comment tags placed between them For more information see Operator precedence and associativity in Using ActionScript in Flash Example The following script uses comment delimiters at the beginning of the script records the...

Страница 56: ...ion Operator arithmetic compound assignment assigns expression1 the value of expression1 expression2 For example the following two statements are equivalent x y x x y For more information see Operator precedence and associativity in Using ActionScript in Flash Example The following code illustrates using the division assignment operator with variables and numbers var x Number 10 var y Number 2 x y...

Страница 57: ...accesses elements in an array The array access operator lets you dynamically set and retrieve instance variable and object names It also lets you access object properties Usage 1 An array is an object whose properties are called elements which are each identified by a number called an index When you create an array you surround the elements with the array access operator or brackets An array can c...

Страница 58: ...llowing line of code sends the number 6 to the Output panel name mc i left_corner For more information see Operator precedence and associativity in Using ActionScript in Flash Example The following example shows two ways to create a new empty Array object the first line uses brackets var my_array Array var my_array Array new Array The following example creates an array called employee_array and us...

Страница 59: ...nScript slash syntax you can use the eval function to accomplish the same result eval name_mc A i You can use the following ActionScript to loop over all objects in the _root scope which is useful for debugging for i in _root trace i _root i You can also use the array access operator on the left side of an assignment statement to dynamically set instance variable and object names employee_array 2 ...

Страница 60: ...y are converted so the value is still 32 bit Negative numbers are converted to an unsigned hex value via the two s complement notation with the minimum being 2147483648 or 0x800000000 numbers less than the minimum are converted to two s complement with greater precision and also have the most significant digits discarded The return value is interpreted as a two s complement number with sign so the...

Страница 61: ...s expression1 the value of expression1 expression2 For example the following two statements are equivalent x y x x y For more information see Operator precedence and associativity in Using ActionScript in Flash Example The following example shows a bitwise XOR assignment operation 15 decimal 1111 binary var x Number 15 9 decimal 1001 binary var y Number 9 trace x y returns 6 decimal 0110 binary Se...

Страница 62: ... pairs using the assignment operator The prototype of the newly created object is generically named the Object object This operator is also used to mark blocks of contiguous code associated with flow control statements for while if else switch and functions For more information see Operator precedence and associativity in Using ActionScript in Flash Example The first line of the following code cre...

Страница 63: ...ious example and produces the same result using constructor functions var person Object new Object person name Gina Vechio person children new Array person children 0 Ruby person children 1 Chickie person children 2 Puppa The previous ActionScript example can also be written in the following format var person Object new Object person name Gina Vechio person children new Array Ruby Chickie Puppa Se...

Страница 64: ...converted so the value is still 32 bit Negative numbers are converted to an unsigned hex value via the two s complement notation with the minimum being 2147483648 or 0x800000000 numbers less than the minimum are converted to two s complement with greater precision and also have the most significant digits discarded The return value is interpreted as a two s complement number with sign so the retur...

Страница 65: ...OR operator with any number of operands if any operand evaluates to true the result is true For more information see Operator precedence and associativity in Using ActionScript in Flash Example The following example uses the logical OR operator in an if statement The second expression evaluates to true so the final result is true var x Number 10 var y Number 250 var start Boolean false if x 25 y 2...

Страница 66: ...unction fx2 Boolean trace fx2 called return true if fx1 fx2 trace IF statement entered The following is sent to the Output panel fx1 called IF statement entered See also logical NOT inequality strict inequality logical AND equality strict equality ...

Страница 67: ...2 For example the following two statements are equivalent x y x x y For more information see Operator precedence and associativity in Using ActionScript in Flash Example The following example uses the bitwise OR assignment operator 15 decimal 1111 binary var x Number 15 9 decimal 1001 binary var y Number 9 1111 1001 1111 trace x y returns 15 decimal 1111 binary See also bitwise AND bitwise AND ass...

Страница 68: ...each Floating point numbers are converted to integers by discarding any digits after the decimal point Positive integers are converted to an unsigned hex value with a maximum value of 4294967295 or 0xFFFFFFFF values larger than the maximum have their most significant digits discarded when they are converted so the value is still 32 bit Negative numbers are converted to an unsigned hex value via th...

Страница 69: ...truct a mask by using bitwise NOT on ReadOnlyFlag In the mask every bit is a 1 except for the read only flag Then use bitwise AND with the mask to clear the read only flag The following code constructs the mask and performs the bitwise AND flags ReadOnlyFlag trace flags output 0 1 0 See also bitwise AND bitwise AND assignment bitwise XOR bitwise XOR assignment bitwise OR bitwise OR assignment ...

Страница 70: ...scription Operator adds numeric expressions or concatenates combines strings If one expression is a string all other expressions are converted to strings and concatenated If both expressions are integers the sum is an integer if either or both expressions are floating point numbers the sum is a floating point number For more information see Operator precedence and associativity in Using ActionScri...

Страница 71: ...them var oldBalance Number 1345 23 var currentBalance deposit_txt text oldBalance trace currentBalance For example if a user enters 475 in the deposit text field the trace statement sends the value 4751345 23 to the Output panel To correct this use the Number function to convert the string to a number as in the following var oldBalance Number 1345 23 var currentBalance Number Number deposit_txt te...

Страница 72: ...y x x y This operator also performs string concatenation All the rules of the addition operator apply to the addition assignment operator For more information see Operator precedence and associativity in Using ActionScript in Flash Example Usage 1 This example uses the operator with a string expression and sends My name is Gilbert to the Output panel var x1 String My name is x1 Gilbert trace x1 ou...

Страница 73: ...xpression1 expression2 A number or string Returns A Boolean value Description Operator comparison compares two expressions and determines whether expression1 is less than expression2 if so the operator returns true If expression1 is greater than or equal to expression2 the operator returns false String expressions are evaluated using alphabetical order all capital letters come before lowercase let...

Страница 74: ...ger than the maximum have their most significant digits discarded when they are converted so the value is still 32 bit Negative numbers are converted to an unsigned hex value via the two s complement notation with the minimum being 2147483648 or 0x800000000 numbers less than the minimum are converted to two s complement with greater precision and also have the most significant digits discarded The...

Страница 75: ...at the bits have been pushed two spaces to the left 2 binary 0010 8 binary 1000 trace 2 2 output 8 See also bitwise right shift and assignment bitwise right shift bitwise left shift and assignment bitwise unsigned right shift bitwise unsigned right shift and assignment ...

Страница 76: ... performs a bitwise left shift operation and stores the contents as a result in expression1 The following two expressions are equivalent A B A A B For more information see Operator precedence and associativity in Using ActionScript in Flash Example In the following example you use the bitwise left shift and assignment operator to shift all bits one space to the left var x Number 4 shift all bits o...

Страница 77: ...xpression1 expression2 A number or string Returns A Boolean value Description Operator comparison compares two expressions and determines whether expression1 is less than or equal to expression2 if it is the operator returns true If expression1 is greater than expression2 the operator returns false String expressions are evaluated using alphabetical order all capital letters come before lowercase ...

Страница 78: ...ter on the right to the variable array element or property in expression1 Assignment can be either by value or by reference Assignment by value copies the actual value of expression2 and stores it in expression1 Assignment by value is used when a variable is assigned a number or string literal Assignment by reference stores a reference to expression2 in expression1 Assignment by reference is commo...

Страница 79: ...une Assignment by value is then used to assign the value of 49528 to the size property of the myObject object var mercury Object new Object mercury diameter 3030 in miles trace mercury diameter output 3030 The following example builds upon the previous example by creating a variable named merkur the German word for mercury and assigning it the value of mercury This creates two variables that refer...

Страница 80: ...the following two statements are equivalent x y x x y String expressions must be converted to numbers otherwise NaN not a number is returned For more information see Operator precedence and associativity in Using ActionScript in Flash Example The following example uses the subtraction assignment operator to subtract 10 from 5 and assign the result to the variable x var x Number 5 var y Number 10 x...

Страница 81: ...ns are compared by reference Two such variables are equal if they refer to the same object array or function Two separate arrays are never considered equal even if they have the same number of elements When comparing by value if expression1 and expression2 are different data types ActionScript will attempt to convert the data type of expression2 to match that of expression1 For more information se...

Страница 82: ...nd example creates the thirdArray variable which points to the same array as the variable firstArray The equality operator will return true for these two arrays because the two variables refer to the same array var firstArray Array new Array one two three var secondArray Array new Array one two three trace firstArray secondArray will output false Arrays are only considered equal if the variables r...

Страница 83: ...tical Variables representing objects arrays and functions are compared by reference Two such variables are equal if they refer to the same object array or function Two separate arrays are never considered equal even if they have the same number of elements For more information see Operator precedence and associativity in Using ActionScript in Flash Example The comments in the following code show t...

Страница 84: ...o avoid the use of the new operator with the String class Create a string variable using a literal value var str String asdf Create a variable that is a reference var stringRef String new String asdf The equality operator does not distinguish among literals variables and references trace stringRef asdf true trace stringRef str true trace asdf str true The strict equality operator considers variabl...

Страница 85: ... Parameters expression1 expression2 A number or string Returns A Boolean value Description Operator comparison compares two expressions and determines whether expression1 is greater than expression2 if it is the operator returns true If expression1 is less than or equal to expression2 the operator returns false String expressions are evaluated using alphabetical order all capital letters come befo...

Страница 86: ... Flash 4 file x y Converted Flash 5 or later file Number x Number y Usage expression1 expression2 Parameters expression1 expression2 A string integer or floating point number Returns A Boolean value Description Operator comparison compares two expressions and determines whether expression1 is greater than or equal to expression2 true or expression1 is less than expression2 false For more informati...

Страница 87: ...erted to an unsigned hex value with a maximum value of 4294967295 or 0xFFFFFFFF values larger than the maximum have their most significant digits discarded when they are converted so the value is still 32 bit Negative numbers are converted to an unsigned hex value via the two s complement notation with the minimum being 2147483648 or 0x800000000 numbers less than the minimum are converted to two s...

Страница 88: ...vious example var x Number 1 This is because 1 decimal equals 11111111111111111111111111111111 binary thirty two 1 s shifting right by one bit causes the least significant bit farthest to the right to be discarded and the most significant bit to be filled in with 1 The result is 11111111111111111111111111111111 thirty two 1 s binary which represents the 32 bit integer 1 See also bitwise right shif...

Страница 89: ...uivalent A B A A B For more information see Operator precedence and associativity in Using ActionScript in Flash Example The following commented code uses the bitwise right shift and assignment operator function convertToBinary numberToConvert Number String var result String for var i 0 i 32 i Extract least significant bit using bitwise AND var lsb Number numberToConvert 1 Add this bit to the resu...

Страница 90: ...nificant digits discarded when they are converted so the value is still 32 bit Negative numbers are converted to an unsigned hex value via the two s complement notation with the minimum being 2147483648 or 0x800000000 numbers less than the minimum are converted to two s complement with greater precision and also have the most significant digits discarded For more information see Operator precedenc...

Страница 91: ...ession that converts to an integer from 0 to 31 Returns A 32 bit integer Description Operator bitwise compound assignment performs an unsigned bitwise right shift operation and stores the contents as a result in expression1 The following two expressions are equivalent A B A A B For more information see Operator precedence and associativity in Using ActionScript in Flash See also bitwise unsigned r...

Страница 92: ...o get and set accessible properties for a specific object such as a button movie clip or text field use the _accProps property To determine whether the player is running in an environment that supports accessibility aids use System capabilities hasAccessibility For information on creating accessible content see Accessibility overview in Using Flash Method summary for the Accessibility class Method...

Страница 93: ...d within one or two seconds of the first appearance of the Flash window in which your document is playing you might get a return value of false even if there is an active Microsoft Active Accessibility MSAA client This is because of an asynchronous communication mechanism between Flash and MSAA clients You can work around this limitation by ensuring a delay of one to two seconds after loading your...

Страница 94: ...odify the accessibility properties for multiple objects only one call to Accessibility updateProperties is necessary multiple calls can result in reduced performance and unintelligible screen reader results Example If you change an image and want to update its accessible description you could use the following ActionScript code my_mc gotoAndStop 2 if my_mc _accProps undefined my_mc _accProps new O...

Страница 95: ...el see The Flash Accessibility panel in Using Flash To determine whether the player is running in an environment that supports accessibility aids use System capabilities hasAccessibility The following table lists the name and data type of each _accProps property its equivalent setting in the Accessibility panel and the kinds of objects to which the property can be applied The term inverse logic me...

Страница 96: ...ops name Pet Store Accessibility updateProperties In contrast the following code sets the name property for a movie clip with the instance name price_mc to the string Price price_mc _accProps name Price Accessibility updateProperties If you are specifying several accessibility properties make as many changes as you can before calling Accessibility updateProperties instead of calling it after each ...

Страница 97: ... other code here delete my_mc _accProps silent revert to default value The value of _accProps must be an object This means that if no _accProps object already exists you must create one before you can assign clues to the properties of the _accProps object if _accProps undefined _accProps new Object _accProps name My movie Example If you change an image and want to update its accessibility descript...

Страница 98: ...tion is called in ActionScript an arguments object is automatically created for that function A local variable arguments is also created and lets you refer to the arguments object Property summary for the arguments object Property Description arguments callee A reference to the function being called arguments caller A reference to the calling function arguments length The number of parameters pass...

Страница 99: ... can use the arguments callee property to make an anonymous function that is recursive as shown in the following example factorial function x Number if x 1 return 1 else return x arguments callee x 1 trace factorial 3 output 6 The following example is a named recursive function function factorial x Number Number if x 1 return 1 else return x factorial x 1 trace factorial 4 output 24 ...

Страница 100: ...llowing example defines two functions a caller function named function1 which calls a another function named function2 define the caller function named function1 var function1 Function function function2 hello from function1 define the callee function named function2 var function2 Function function aString String if arguments caller function1 trace function2 was called by function1 trace aString c...

Страница 101: ... param_arg2 String param_arg3 String return arguments length trace getArgLength one two three output 3 trace getArgLength one two output 2 trace getArgLength one two three four output 4 In the following example the function called listSum adds the values passed to it and returns the sum The function uses a for loop to examine each argument passed If the value is a number the value is added to the ...

Страница 102: ...sing the array s index and then by using the Array class s push method var myArray Array Array myArray push 12 trace myArray traces 12 myArray 4 7 trace myArray traces 12 undefined undefined undefined 7 Usage 2 The following example creates an array of length 4 but with no elements defined var myArray Array Array 4 trace myArray length traces 4 trace myArray traces undefined undefined undefined un...

Страница 103: ...y for the Array class Method Description Array concat Concatenates the parameters and returns them as a new array Array join Joins all elements of an array into a string Array pop Removes the last element of an array and returns its value Array push Adds one or more elements to the end of an array and returns the array s new length Array reverse Reverses the direction of an array Array shift Remov...

Страница 104: ... different types of arrays an empty array an array with a specific length but whose elements have undefined values or an array whose elements have specific values Usage 1 If you don t specify any parameters an array with a length of 0 is created Usage 2 If you specify only a length an array is created with length number of elements Each element s value is set to undefined Usage 3 If you use the el...

Страница 105: ...ements The initial elements of the go_gos_array array are identified as shown in the following example go_gos_array 0 Belinda go_gos_array 1 Gina go_gos_array 2 Kathy go_gos_array 3 Charlotte go_gos_array 4 Jane The following code adds a sixth element to the go_gos_array array and changes the second element go_gos_array 5 Donna go_gos_array 1 Nina trace go_gos_array join returns Belinda Nina Kathy...

Страница 106: ... Array new Array a b c var numeric_array Array new Array 1 2 3 var alphaNumeric_array Array alpha_array concat numeric_array trace alphaNumeric_array creates array a b c 1 2 3 The following code concatenates three arrays var num1_array Array 1 3 5 var num2_array Array 2 4 6 var num3_array Array 7 8 9 var nums_array Array num1_array concat num2_array num3_array trace nums_array creates array 1 3 5 ...

Страница 107: ...array with three elements Earth Moon and Sun It then joins the array three times first using the default separator a comma and a space then using a dash and then using a plus sign var a_array Array new Array Earth Moon Sun trace a_array join displays Earth Moon Sun trace a_array join displays Earth Moon Sun trace a_array join displays Earth Moon Sun The following example creates a nested array con...

Страница 108: ...property that is shorter than the existing length the array will be truncated Example The following code explains how the length property is updated var my_array Array new Array trace my_array length initial length is 0 my_array 0 a trace my_array length my_array length is updated to 1 my_array 1 b trace my_array length my_array length is updated to 2 my_array 9 c trace my_array length my_array le...

Страница 109: ...he last element from an array and returns the value of that element Example The following code creates the myPets_array array containing four elements and then removes its last element var myPets_array Array new Array cat dog bird fish var popped String myPets_array pop trace popped displays fish trace myPets_array displays cat dog bird See Also Array push Array shift Array unshift ...

Страница 110: ...f an array and returns the array s new length Example The following example creates the array myPets_array with two elements cat and dog The second line adds two elements to the array Because the push method returns the new length of the array the trace statement in the last line sends the new length of myPets_array 4 to the Output panel var myPets_array Array new Array cat dog var pushed Number m...

Страница 111: ... None Returns Nothing Description Method reverses the array in place Example The following example uses this method to reverse the array numbers_array var numbers_array Array new Array 1 2 3 4 5 6 trace numbers_array displays 1 2 3 4 5 6 numbers_array reverse trace numbers_array displays 6 5 4 3 2 1 ...

Страница 112: ...first element from an array and returns that element Example The following code creates the array myPets_array and then removes the first element from the array and assigns it to the variable shifted var myPets_array Array new Array cat dog bird fish var shifted String myPets_array shift trace shifted displays cat trace myPets_array displays dog bird fish See also Array pop Array push Array unshif...

Страница 113: ... you don t pass any parameters a duplicate of my_array is created Example The following example creates an array of five pets and uses slice to populate a new array comprising only four legged pets var myPets_array Array new Array cat dog fish canary parrot var myFourLeggedPets_array Array new Array var myFourLeggedPets_array myPets_array slice 0 2 trace myFourLeggedPets_array returns cat dog trac...

Страница 114: ...values are acceptable for option 1 or Array CASEINSENSITIVE 2 or Array DESCENDING 4 or Array UNIQUESORT 8 or Array RETURNINDEXEDARRAY 16 or Array NUMERIC For information on this parameter see Array sortOn Note Array sort is defined in ECMA 262 but the array sorting options introduced in Flash Player 7 are Flash specific extensions to the ECMA 262 specification Returns The return value depends on w...

Страница 115: ...le Usage 1 The following example shows the use of Array sort with and without a value passed for option var fruits_array Array new Array oranges apples strawberries pineapples cherries trace fruits_array displays oranges apples strawberries pineapples cherries fruits_array sort trace fruits_array displays apples cherries oranges pineapples strawberries fruits_array sort Array DESCENDING trace frui...

Страница 116: ...116 Chapter 2 ActionScript Language Reference trace Sorted displays Sorted trace passwords_array displays ana ring anne home jay mag mom glam regina silly See also bitwise OR Array sortOn ...

Страница 117: ...ut each option see Description on page 117 Returns The return value depends on whether you pass any parameters as described in the following list If you specify a value of 4 or Array UNIQUESORT for option and two or more elements being sorted have identical sort fields Flash returns a value of 0 and does not modify the array If you specify a value of 8 or Array RETURNINDEXEDARRAY for option Flash ...

Страница 118: ...twise OR operator or add the values of the flags together The following code shows three ways to specify a numeric descending sort my_array sortOn someFieldName 2 16 my_array sortOn someFieldName 18 my_array sortOn someFieldName Array DESCENDING Array NUMERIC Code hinting see Using code hints in Using ActionScript in Flash is enabled if you use the string form of the flag for example DESCENDING ra...

Страница 119: ... 2 age 35 my_array 3 age 4 After any sort that doesn t pass a value of 8 for option my_array sortOn age Array NUMERIC my_array 0 age 3 my_array 1 age 4 my_array 2 age 29 my_array 3 age 35 Performing a sort that returns an index array doesn t change the elements in the array as shown in the following example Before sorting my_array 0 age 29 my_array 1 age 3 my_array 2 age 35 my_array 3 age 4 After ...

Страница 120: ...ay push name john city omaha zip 68144 rec_array push name john city kansas city zip 72345 rec_array push name bob city omaha zip 94010 for i 0 i rec_array length i trace rec_array i name rec_array i city results john omaha john kansas city bob omaha rec_array sortOn name city for i 0 i rec_array length i trace rec_array i name rec_array i city results bob omaha john kansas city john omaha rec_arr...

Страница 121: ...ments that were removed from the array Description Method adds and removes elements from an array This method modifies the array without making a copy Example The following example creates an array and splices it using element index 1 for the start parameter This removes all elements from the array starting with the second element leaving only the element at index 0 in the original array var myPet...

Страница 122: ...umber 0 for the deleteCount parameter and the string chair for the value parameter This does not remove anything from the original array and adds the string chair at index 1 var myFurniture_array Array new Array couch bed desk lamp trace myFurniture_array splice 1 0 chair displays empty array trace myFurniture_array displays couch chair bed desk lamp ...

Страница 123: ...index my_array length 1 is converted to a concatenated string and separated by commas To specify a custom separator use Array join Example The following example creates my_array and converts it to a string The following example creates my_array converts it to a string and outputs 1 2 3 4 5 as a result of the trace statement my_array Array new Array my_array 0 1 my_array 1 2 my_array 2 3 my_array 3...

Страница 124: ... the beginning of the array Returns An integer representing the new length of the array Description Method adds one or more elements to the beginning of an array and returns the array s new length Example The following example shows the use of Array unshift var pets_array Array new Array dog cat fish trace pets_array dog cat fish pets_array unshift ferrets gophers engineers trace pets_array ferret...

Страница 125: ...lowing example the playMP3 function is defined The TextField object list_txt is created and set so HTML text can be rendered The text Track 1 and Track 2 are links inside the text field The playMP3 function is called when the user clicks either link and plays the MP3 that is passed as a parameter of the asfunction call var myMP3 Sound new Sound function playMP3 mp3 String myMP3 loadSound mp3 true ...

Страница 126: ...s published for Flash Player 7 or later the result is true if the string has a length greater than zero the value is false for an empty string If expression is undefined or NaN not a number the return value is false If expression is a movie clip or an object the return value is true Note Unlike the Boolean class constructor the Boolean function does not use the keyword new Moreover the Boolean cla...

Страница 127: ... This example shows a significant difference between use of the Boolean function and the Boolean class The Boolean function creates a Boolean value and the Boolean class creates a Boolean object Boolean values are compared by value and Boolean objects are compared by reference Variables representing Boolean values are compared by value var a Boolean Boolean a a is true var b Boolean Boolean 1 b is...

Страница 128: ...ty Flash Player 5 Usage new Boolean x Boolean Parameters x Any expression This parameter is optional Returns A reference to a Boolean object Description Constructor creates a Boolean object If you omit the x parameter the Boolean object is initialized with a value of false If you specify a value for the x parameter the method evaluates it and returns the result as a Boolean value according to the ...

Страница 129: ...hod returns the string representation true or false of the Boolean object Example This example creates a variable of type Boolean and uses toString to convert the value to a string for use in the trace statement var myBool Boolean true trace The value of the Boolean myBool is myBool toString myBool false trace The value of the Boolean myBool is myBool toString ...

Страница 130: ...s A Boolean value Description Method returns true if the primitive value type of the specified Boolean object is true false otherwise Example The following example shows how this method works and also shows that the primitive value type of a new Boolean object is false var x Boolean new Boolean trace x valueOf false x 6 3 3 trace x valueOf true ...

Страница 131: ...he break statement instructs Flash to skip the rest of the statements in that case block and jump to the first statement following the enclosing switch statement In nested loops the break statement only skips the rest of the immediate loop and does not break out of the entire series of nested loops For breaking out of an entire series of nested loops see try catch finally Example The following exa...

Страница 132: ...132 Chapter 2 ActionScript Language Reference See also for for in do while while switch case continue throw try catch finally ...

Страница 133: ...us has a yellow rectangle around it Button _height The height of a button instance in pixels Button _quality The level of anti aliasing applied to the current SWF file Button menu A reference to an associated ContextMenu object Button _name The instance name of a button instance Button _parent A reference to the movie clip or object that contains the current movie clip or object Button _quality A ...

Страница 134: ...tically scaling a button instance Event handler Description Button onDragOut Invoked when the mouse button is pressed over the button and the pointer then rolls outside the button Button onDragOver Invoked when the user presses and drags the mouse button outside and then over the button Button onKeyUp Invoked when a key is released Button onKillFocus Invoked when focus is removed from a button But...

Страница 135: ...alue is 100 Objects in a button with _alpha set to 0 are active even though they are invisible Example The following code sets the _alpha property of a button named myBtn_btn to 50 when the user clicks the button add a Button instance on the Stage give it an instance name of myBtn_btn with frame 1 selected place the following code using the Actions panel myBtn_btn onRelease function this _alpha 50...

Страница 136: ...cked and the page cannot be reloaded Example The following example demonstrates how you can disable and enable buttons from being clicked Two buttons myBtn1_btn and myBtn2_btn are on the Stage and the following ActionScript is added so that the myBtn2_btn button cannot be clicked add two button instances on the Stage give them instance names of myBtn1_btn and myBtn2_btn place the following code on...

Страница 137: ...t property controls the global _focusrect property It is a Boolean value This behavior was changed in Flash Player 6 and later to permit customizing the _focusrect property on an individual movie clip Example This example demonstrates how to hide the yellow rectangle around a specified button instance in a SWF file when it has focus in a browser window Create three buttons called myBtn1_btn myBtn2...

Страница 138: ...epth You might notice that two of these buttons have the same depth value one in the main SWF file and one in the loaded SWF file This is misleading because buttonMovie swf was loaded at depth 999 which means that the button it contains will also have a depth of 999 relative to the buttons in the main SWF file Keep in mind that each movie clip has its own internal z order which means that each mov...

Страница 139: ...Flash Player 6 Usage my_btn _height Number Description Property the height of the button in pixels Example The following example sets the height and width of a button called my_btn to a specified width and height my_btn _width 500 my_btn _height 200 ...

Страница 140: ...med myBtn_btn The ContextMenu object contains a single menu item labeled Save with an associated callback handler function named doSave Add the button instance to the Stage and name it myBtn_btn var menu_cm ContextMenu new ContextMenu menu_cm customItems push new ContextMenuItem Save doSave function doSave menu Object obj Object Void trace You selected the Save menu item myBtn_btn menu menu_cm Sel...

Страница 141: ...btn _name String Description Property instance name of the button specified by my_btn Example The following example traces all instance names of any Button instances within the current Timeline of a SWF file for i in this if this i instanceof Button trace this i _name ...

Страница 142: ...tton and the pointer then dragged outside of the button You must define a function that executes when the event handler is invoked Example The following example demonstrates how you can execute statements when the pointer is dragged off a button Create a button called my_btn on the Stage and enter the following ActionScript in a frame on the Timeline my_btn onDragOut function trace onDragOut this ...

Страница 143: ...ed Example The following example defines a function for the onDragOver handler that sends a trace statement to the Output panel Create a button called my_btn on the Stage and enter the following ActionScript on the Timeline my_btn onDragOut function trace onDragOut this _name my_btn onDragOver function trace onDragOver this _name When you test the SWF file drag the pointer off the button instance ...

Страница 144: ... the Output panel is defined for the onKeyDown handler Create a button called my_btn on the Stage and enter the following ActionScript in a frame on the Timeline my_btn onKeyDown function trace onKeyDown this _name Key getKeyPressed function getKeyPressed String var theKey String switch Key getAscii case Key BACKSPACE theKey BACKSPACE break case Key SPACE theKey SPACE break default theKey chr Key ...

Страница 145: ...Button onKeyDown 145 See also Button onKeyUp ...

Страница 146: ...define a function that executes when the event handler is invoked Example In the following example a function that sends text to the Output panel is defined for the onKeyDown handler Create a button called my_btn on the Stage and enter the following ActionScript in a frame on the Timeline my_btn onKeyDown function trace onKeyDown this _name Key getKeyPressed my_btn onKeyUp function trace onKeyUp t...

Страница 147: ...ou select Control Disable Keyboard Shortcuts in the test environment Then press the Tab key until the button has focus a yellow rectangle appears around the my_btn instance and start pressing keys on your keyboard When you press keys they are displayed in the Output panel ...

Страница 148: ...s newFocus contains the value null Example The following example demonstrates how statements can be executed when a button loses focus Create a button instance on the Stage called my_btn and add the following ActionScript to Frame 1 of the Timeline this createTextField output_txt this getNextHighestDepth 0 0 300 200 output_txt wordWrap true output_txt multiline true output_txt border true my_btn o...

Страница 149: ...s None Returns Nothing Description Event handler invoked when a button is pressed You must define a function that executes when the event handler is invoked Example In the following example a function that sends a trace statement to the Output panel is defined for the onPress handler my_btn onPress function trace onPress called ...

Страница 150: ...re Parameters None Returns Nothing Description Event handler invoked when a button is released You must define a function that executes when the event handler is invoked Example In the following example a function that sends a trace statement to the Output panel is defined for the onRelease handler my_btn onRelease function trace onRelease called ...

Страница 151: ...d when the mouse is released while the pointer is outside the button after the button is pressed while the pointer is inside the button You must define a function that executes when the event handler is invoked Example In the following example a function that sends a trace statement to the Output panel is defined for the onReleaseOutside handler my_btn onReleaseOutside function trace onReleaseOuts...

Страница 152: ...ers None Returns Nothing Description Event handler invoked when the pointer moves outside a button area You must define a function that executes when the event handler is invoked Example In the following example a function that sends a trace statement to the Output panel is defined for the onRollOut handler my_btn onRollOut function trace onRollOut called ...

Страница 153: ...turns Nothing Description Event handler invoked when the pointer moves over a button area You must define a function that executes when the event handler is invoked Example In the following example a function that sends a trace statement to the Output panel is defined for the onRollOver handler my_btn onRollOver function trace onRollOver called ...

Страница 154: ...instance If there is no previously focused object oldFocus contains a null value Example The following example demonstrates how you can execute statements when the user of a SWF file moves focus from one button to another Create two buttons btn1_btn and btn2_btn and enter the following ActionScript in Frame 1 of the Timeline Selection setFocus btn1_btn trace Selection getFocus btn2_btn onSetFocus ...

Страница 155: ... specify a relative path to movie clips or objects that are above the current movie clip or object You can use _parent to move up multiple levels in the display list as in the following this _parent _parent _alpha 20 Example In the following example a button named my_btn is placed inside a movie clip called my_mc The following code shows how to use the _parent property to get a reference to the mo...

Страница 156: ...ed using a 2 x 2 pixel grid but bitmaps are not smoothed This is suitable for movies that do not contain text HIGH High rendering quality Graphics are anti aliased using a 4 x 4 pixel grid and bitmaps are smoothed if the movie is static This is the default rendering quality setting used by Flash BEST Very high rendering quality Graphics are anti aliased using a 4 x 4 pixel grid and bitmaps are alw...

Страница 157: ...ple rotates two buttons on the Stage Create two buttons on the Stage called control_btn and my_btn Make sure that my_btn is not perfectly round so you can see it rotating Then enter the following ActionScript in Frame 1 of the Timeline var control_btn Button var my_btn Button control_btn onRelease function my_btn _rotation 10 Now create another button on the Stage called myOther_btn making sure it...

Страница 158: ...r Description Property global an integer that specifies the number of seconds a sound prebuffers before it starts to stream Note Although you can specify this property for a Button object it is actually a global property and you can specify its value simply as _soundbuftime For more information and an example see _soundbuftime ...

Страница 159: ...cript is used to set the tabEnabled property for one of four buttons to false However all four buttons one_btn two_btn three_btn and four_btn are placed in a custom tab order using tabIndex Although tabIndex is set for three_btn three_btn is not included in a custom or automatic tab order because tabEnabled is set to false for that instance To set the tab ordering for the four buttons add the foll...

Страница 160: ...tention is paid to the hierarchical relationships of objects in the SWF file All objects in the SWF file with tabIndex properties are placed in the tab order and the tab order is determined by the order of the tabIndex values If two objects have the same tabIndex value the one that goes first is undefined You shouldn t use the same tabIndex value for multiple objects Example The following ActionSc...

Страница 161: ...ive the new movie clip an instance name my_mc Delete the existing ActionScript in Frame 1 of the Timeline and replace it with my_mc my_btn onRelease function trace this _target displays my_mc my_btn To convert the notation from slash notation to dot notation modify the previous code example to the following my_mc my_btn onRelease function trace eval this _target displays _level0 my_mc my_btn This ...

Страница 162: ... trackAsMenu property at any time the modified button immediately takes on the new behavior Example The following example demonstrates how to track two buttons as a menu Place two button instances on the Stage called one_btn and two_btn Enter the following ActionScript in the Timeline var one_btn Button var two_btn Button one_btn trackAsMenu true two_btn trackAsMenu true one_btn onRelease function...

Страница 163: ...nScript in Frame 1 of the Timeline var one_btn Button var two_btn Button this createTextField output_txt 999 0 0 100 22 output_txt autoSize true one_btn onRelease function trace clicked one_btn trace this _url two_btn onRelease function trace clicked this _name var url_array Array this _url split var my_str String String url_array pop output_txt text unescape my_str When you click each button the ...

Страница 164: ...or property at any time the modified button immediately takes on the new cursor behavior The useHandCursor property can be read out of a prototype object Example Create two buttons on the Stage with the instance names myBtn1_btn and myBtn2_btn Enter the following ActionScript in Frame 1 of the Timeline myBtn1_btn useHandCursor false myBtn1_btn onRelease buttonClick myBtn2_btn onRelease buttonClick...

Страница 165: ...rty set to false are disabled Example Create two buttons on the Stage with the instance names myBtn1_btn and myBtn2_btn Enter the following ActionScript in Frame 1 of the Timeline myBtn1_btn onRelease function this _visible false trace clicked this _name myBtn2_btn onRelease function this _alpha 0 trace clicked this _name Notice how you can still click myBtn2_btn after the alpha is set to 0 See al...

Страница 166: ...ption Property the width of the button in pixels Example The following example increases the width property of a button called my_btn and displays the width in the Output panel Enter the following ActionScript in Frame 1 of the Timeline my_btn onRelease function trace this _width this _width 1 1 See also MovieClip _width ...

Страница 167: ... clip that has transformations the button is in the local coordinate system of the enclosing movie clip Thus for a movie clip rotated 90º counterclockwise the enclosed button inherits a coordinate system that is rotated 90º counterclockwise The button s coordinates refer to the registration point position Example The following example sets the coordinates of my_btn to 0 on the Stage Create a butto...

Страница 168: ... following ActionScript in Frame 1 of the Timeline this createTextField mouse_txt 999 5 5 150 40 mouse_txt html true mouse_txt wordWrap true mouse_txt border true mouse_txt autoSize true mouse_txt selectable false var mouseListener Object new Object mouseListener onMouseMove function var table_str String textformat tabstops 50 100 table_str b Stage b t x _xmouse t y _ymouse newline table_str b But...

Страница 169: ..._y property settings which are defined in pixels For example if the parent movie clip is scaled to 50 setting the _x property moves an object in the button by half the number of pixels that it would if the SWF file were at 100 Example The following example scales a button called my_btn When you click and release the button it grows 10 on the x and y axis Enter the following ActionScript in Frame 1...

Страница 170: ...r movie clip that has transformations the button is in the local coordinate system of the enclosing movie clip Thus for a movie clip rotated 90º counterclockwise the enclosed button inherits a coordinate system that is rotated 90º counterclockwise The button s coordinates refer to the registration point position Example The following example sets the coordinates of my_btn to 0 on the Stage Create ...

Страница 171: ...tionScript in Frame 1 of the Timeline this createTextField mouse_txt 999 5 5 150 40 mouse_txt html true mouse_txt wordWrap true mouse_txt border true mouse_txt autoSize true mouse_txt selectable false var mouseListener Object new Object mouseListener onMouseMove function var table_str String textformat tabstops 50 100 table_str b Stage b t x _xmouse t y _ymouse newline table_str b Button b t x my_...

Страница 172: ... registration point of the button expressed as a percentage The default registration point is 0 0 Example The following example scales a button called my_btn When you click and release the button it grows 10 on the x and y axis Enter the following ActionScript in Frame 1 of the Timeline my_btn onRelease function this _xscale 1 1 this _yscale 1 1 See also Button _y Button _x Button _xscale ...

Страница 173: ...Camera class Property summary for the Camera class Method Description Camera get Returns a default or specified Camera object or null if the camera is not available Camera setMode Sets aspects of the camera capture mode including height width and frames per second Camera setMotionLevel Specifies how much motion is required to invoke Camera onActivity true and how much time should elapse without mo...

Страница 174: ...nied access to the camera Camera name The name of the camera as specified by the camera hardware Camera names Class property in an array of strings reflecting the names of all available video capture devices including video cards and cameras Camera quality An integer specifying the required level of picture quality as determined by the amount of compression being applied to each video frame Camera...

Страница 175: ...amount of motion the camera detects using the activityLevel property The following example detects the amount of motion the camera detects using the activityLevel property and a ProgressBar instance Create a new video instance by selecting New Video from the Library options menu Add an instance to the Stage and give it the instance name my_video Add a ProgressBar component instance to the Stage an...

Страница 176: ...e instance name my_video Add a NumericStepper component instance to the Stage and give it the instance name bandwidth_nstep Then add the following ActionScript to Frame 1 of the Timeline var bandwidth_nstep mx controls NumericStepper var my_video Video var my_cam Camera Camera get my_video attachVideo my_cam this createTextField bandwidth_txt this getNextHighestDepth 0 0 100 22 bandwidth_txt autoS...

Страница 177: ...frames per second that the camera captures data using the currentFps property and a ProgressBar instance Create a new video instance by selecting New Video from the Library options menu Add an instance to the Stage and give it the instance name my_video Add a ProgressBar component instance to the Stage and give it the instance name fps_pb Then add the following ActionScript to Frame 1 of the Timel...

Страница 178: ... rate in frames per second that the camera captures data using the currentFps property and a ProgressBar instance Create a new video instance by selecting New Video from the Library options menu Add an instance to the Stage and give it the instance name my_video Add a ProgressBar component instance to the Stage and give it the instance name fps_pb Then add the following ActionScript to Frame 1 of ...

Страница 179: ...objects that you create using the new constructor multiple calls to Camera get reference the same camera Thus if your script contains the lines first_cam Camera get and second_cam Camera get both first_cam and second_cam reference the same default camera In general you shouldn t pass a value for index simply use Camera get to return a reference to the default camera By means of the Camera settings...

Страница 180: ...era get is called This is helpful if a user has forgotten to connect the camera if your SWF file provides a Try Again button that calls Camera get Flash can find the camera without the user having to restart the SWF file Example The following example lets you select an active camera to use from a ComboBox instance The current active camera is displayed in a Label instance Create a new video instan...

Страница 181: ...options menu Add an instance to the Stage and give it the instance name my_video Add a Label component instance to the Stage and give it the instance name dimensions_lbl Then add the following ActionScript to Frame 1 of the Timeline var my_cam Camera Camera get var my_video Video my_video attachVideo my_cam var dimensions_lbl mx controls Label dimensions_lbl setStyle fontSize 9 dimensions_lbl setS...

Страница 182: ...y_video Add a Label component instance to the Stage and give it the instance name camera_lbl Then add the following ActionScript to Frame 1 of the Timeline var camera_lbl mx controls Label var my_cam Camera Camera get var my_video Video my_video attachVideo my_cam camera_lbl text my_cam index my_cam name this createTextField cameras_txt this getNextHighestDepth 25 160 160 80 cameras_txt html true ...

Страница 183: ...it the instance name motionLevel_lbl a NumericStepper with the instance name motionLevel_nstep and a ProgressBar with the instance name motion_pb Then add the following ActionScript to Frame 1 of the Timeline var my_cam Camera Camera get var my_video Video my_video attachVideo my_cam configure the ProgressBar component instance var motion_pb mx controls ProgressBar motion_pb mode manual motion_pb ...

Страница 184: ...am onActivity function isActive Boolean If isActive equals true set the themeColor variable to haloGreen Otherwise set the themeColor to haloOrange var themeColor String isActive haloGreen haloOrange motion_pb setStyle themeColor themeColor function changeMotionLevel Set the motionLevel property for my_cam Camera instance to the value of the NumericStepper component instance Maintain the current m...

Страница 185: ...e it the instance name motionLevel_lbl a NumericStepper with the instance name motionTimeOut_nstep and a ProgressBar with the instance name motion_pb Then add the following ActionScript to Frame 1 of the Timeline var motionLevel_lbl mx controls Label var motion_pb mx controls ProgressBar var motionTimeOut_nstep mx controls NumericStepper var my_cam Camera Camera get var my_video Video my_video att...

Страница 186: ...186 Chapter 2 ActionScript Language Reference See also Camera onActivity Camera setMotionLevel ...

Страница 187: ... my_cam muted evaluates to true Create a new video instance by selecting New Video from the Library options menu Add an instance to the Stage and give it the instance name my_video Then add the following ActionScript to Frame 1 of the Timeline var my_cam Camera Camera get var my_video Video my_video attachVideo my_cam my_cam onStatus function infoObj Object if my_cam muted If user is denied access...

Страница 188: ...dows this name is the same as the device name listed in the Scanners and Cameras Control Panel Create a new video instance by selecting New Video from the Library options menu Add an instance to the Stage and give it the instance name my_video Then add the following ActionScript to Frame 1 of the Timeline var my_cam Camera Camera get var my_video Video my_video attachVideo my_cam this createTextFi...

Страница 189: ...n see the Array class entry Calling the Camera names property requires an extensive examination of the hardware and it may take several seconds to build the array In most cases you can just use the default camera Example The following example uses the default camera unless more than one camera is available in which case the user can choose which camera to set as the default camera If only one came...

Страница 190: ...r you must create a function to process its activity value To specify the amount of motion required to invoke Camera onActivity true and the amount of time that must elapse without activity before invoking Camera onActivity false use Camera setMotionLevel Example The following example displays true or false in the Output panel when the camera starts or stops detecting motion Assumes a Video object...

Страница 191: ...uted and whose level property is Status If the user denies access the Camera muted property is set to true and this handler is invoked with an information object whose code property is Camera Muted and whose level property is Status To determine whether the user has denied or allowed access to the camera without processing this event handler use the Camera muted property Note If the user chooses t...

Страница 192: ...192 Chapter 2 ActionScript Language Reference trace Camera access granted break See also Camera get Camera muted System showSettings System onStatus ...

Страница 193: ...epper instance to specify the amount of compression applied to the camera feed Create a new video instance by selecting New Video from the Library options menu Add an instance to the Stage and give it the instance name my_video Add a NumericStepper with the instance name quality_nstep Then add the following ActionScript to Frame 1 of the Timeline var quality_nstep mx controls NumericStepper var my...

Страница 194: ...rameter This parameter is optional Returns Nothing Description Method sets the camera capture mode to the native mode that best meets the specified requirements If the camera does not have a native mode that matches all the parameters you pass Flash selects a capture mode that most closely synthesizes the requested mode This manipulation may involve cropping the image and dropping frames By defaul...

Страница 195: ...xtInput component instance with the instance name fps_ti Then add the following ActionScript to Frame 1 of the Timeline var my_cam Camera Camera get var my_video Video my_video attachVideo my_cam fps_ti maxChars 2 fps_ti restrict 0 9 fps_lbl text Current my_cam fps fps function changeFps Void my_cam setMode my_cam width my_cam height fps_ti text fps_lbl text Current my_cam fps fps fps_ti text my_c...

Страница 196: ...To prevent the camera from detecting motion at all pass a value of 100 for sensitivity Camera onActivity is never invoked You would probably use this value only for testing purposes for example to temporarily disable any actions set to occur when Camera onActivity is invoked To determine the amount of motion the camera is currently detecting use the Camera activityLevel property Motion sensitivity...

Страница 197: ...er number to see how different values affect motion detection Assumes a Video object named myVideoObject is on the Stage active_cam Camera get x 0 function motion mode trace x mode x active_cam onActivity function mode motion mode active_cam setMotionLevel 30 500 myVideoObject attachVideo active_cam See also Camera activityLevel Camera motionLevel Camera motionTimeOut Camera onActivity ...

Страница 198: ...d is generally applicable only if you are transmitting video using Flash Communication Server Use this method to specify which element of the outgoing video feed is more important to your application bandwidth use or picture quality To indicate that bandwidth use takes precedence pass a value for bandwidth and 0 for frameQuality Flash will transmit video at the highest quality possible within the ...

Страница 199: ...o more than 8192 8K second is used to send video active_cam setQuality 8192 0 Ensure that no more than 8192 8K second is used to send video with a minimum quality of 50 active_cam setQuality 8192 50 Ensure a minimum quality of 50 no matter how much bandwidth it takes active_cam setQuality 0 50 See also Camera bandwidth Camera get Camera quality ...

Страница 200: ...rom the Library options menu Add an instance to the Stage and give it the instance name my_video Add a Label component instance to the Stage and give it the instance name dimensions_lbl Then add the following ActionScript to Frame 1 of the Timeline var my_cam Camera Camera get var my_video Video my_video attachVideo my_cam var dimensions_lbl mx controls Label dimensions_lbl setStyle fontSize 9 dim...

Страница 201: ...ide a switch statement it produces an error and the script doesn t compile Note You should always end the statement s parameter with a break statement If you omit the break statement from the statement s parameter it continues executing with the next case statement instead of exiting the switch statement Example The following example defines conditions for the switch statement thisMonth If thisMon...

Страница 202: ...202 Chapter 2 ActionScript Language Reference See also break default strict equality switch ...

Страница 203: ...he class must match the name of the external file that contains the class The name of the external file must be the name of the class with the file extension as appended For example if you name a class Student the file that defines the class must be named Student as If a class is within a package the class declaration must use the fully qualified class name of the form base sub1 sub2 MyClass for m...

Страница 204: ...ing var bloomSeason String Following line is constructor because it has the same name as the class function Plant param_leafType String param_bloomSeason String Assign passed values to properties when new Plant object is created this leafType param_leafType this bloomSeason param_bloomSeason Create methods to return property values because best practice recommends against directly referencing a pr...

Страница 205: ...l use the new operator to create a ImageLoader object var jakob_mc MovieClip this createEmptyMovieClip jakob_mc this getNextHighestDepth var jakob ImageLoader new ImageLoader http www macromedia com devnet mx blueprint articles nielsen spotlight_jnielsen jpg jakob_mc _x 10 _y 10 _alpha 70 _rotation 5 See also dynamic extends implements import interface new Object registerClass ...

Страница 206: ...o setInterval Example The following example first sets and then clears an interval call function callback trace interval called getTimer ms var intervalID Number setInterval callback 1000 You need to clear the interval when you have finished using the function Create a button called clearInt_btn and use the following ActionScript to clear setInterval clearInt_btn onRelease function clearInterval i...

Страница 207: ...uctor creates a Color object for the movie clip specified by the target_mc parameter You can then use the methods of that Color object to change the color of the entire target movie clip Example The following example creates a Color object called my_color for the movie clip my_mc and sets its RGB value to orange var my_color Color new Color my_mc my_color setRGB 0xff9933 Method Description Color g...

Страница 208: ...last setRGB call Example The following code retrieves the RGB value for the Color object my_color converts the value to a hexadecimal string and assigns it to the myValue variable To see this code work add a movie clip instance to the Stage and give it the instance name my_mc var my_color Color new Color my_mc set the color my_color setRGB 0xff9933 var myValue String my_color getRGB toString 16 tr...

Страница 209: ...transform object and then sets new percentages for colors and alpha of my_mc relative to their current values To see this code work place a multicolored movie clip on the Stage with the instance name my_mc Then place the following code on Frame 1 in the main Timeline and select Control Test Movie var my_color Color new Color my_mc var myTransform Object my_color getTransform myTransform ra 50 ba 5...

Страница 210: ...t the number is a hexadecimal value Description Method specifies an RGB color for a Color object Calling this method overrides any previous Color setTransform settings Returns Nothing Example This example sets the RGB color value for the movie clip my_mc To see this code work place a movie clip on the Stage with the instance name my_mc Then place the following code on Frame 1 in the main Timeline ...

Страница 211: ...r a color transform object correspond to the settings in the Advanced Effect dialog box and are defined as follows ra is the percentage for the red component 100 to 100 rb is the offset for the red component 255 to 255 ga is the percentage for the green component 100 to 100 gb is the offset for the green component 255 to 255 ba is the percentage for the blue component 100 to 100 bb is the offset f...

Страница 212: ...ment place it on Frame 1 on the main Timeline and place a movie clip on the Stage with the instance name my_mc as in the following code Create a color object called my_color for the target my_mc var my_color Color new Color my_mc Create a color transform object called myColorTransform using Set the values for myColorTransform var myColorTransform Object ra 50 rb 244 ga 40 gb 112 ba 12 bb 90 aa 40 ...

Страница 213: ...dard menu which appears when you right click in Flash Player the edit menu which appears when you right click over a selectable or editable text field and an error menu which appears when a SWF file has failed to load into Flash Player Only the standard and edit menus can be modified with the ContextMenu class Custom menu items always appear at the top of the Flash Player context menu above any vi...

Страница 214: ...state or based on the type of object movie clip text field or button or the Timeline that the user right clicks or Control clicks For an example of creating an event handler see ContextMenu onSelect Example The following example hides all the built in objects in the Context menu However the Settings and About items still appear because they cannot be disabled var newMenu ContextMenu new ContextMen...

Страница 215: ...Handler obj menuObj if showItem false menuObj customItems 0 enabled false else menuObj customItems 0 enabled true function itemHandler obj item put code here trace selected this menu my_cm When the user right clicks or Control clicks the Stage the custom menu is displayed See also Button menu ContextMenu onSelect ContextMenu customItems ContextMenu hideBuiltInItems MovieClip menu TextField menu ...

Страница 216: ...is example the built in Quality and Print menu items are disabled for the ContextMenu object my_cm which is attached to the current Timeline of the SWF file var my_cm ContextMenu new ContextMenu my_cm builtInItems quality false my_cm builtInItems print false this menu my_cm Note You cannot disable the Settings or About menu items from the context menu In the next example a for in loop enumerates t...

Страница 217: ...menu item with the text Save It then creates a copy of my_cm and assigns it to the variable clone_cm which inherits all the properties of the original menu var my_cm ContextMenu new ContextMenu my_cm hideBuiltInItems var menuItem_cmi ContextMenuItem new ContextMenuItem Save saveHandler my_cm customItems push menuItem_cmi function saveHandler obj menuItem saveDocument custom function not shown trac...

Страница 218: ...For more information about creating new menu items see the ContextMenuItem class entry Example The following example creates a new custom menu item called menuItem_cm with a caption of Send e mail and a callback handler named emailHandler The new menu item is then added to the ContextMenu object my_cm using the customItems array Finally the new menu is attached to a movie clip named email_mc var m...

Страница 219: ... it does not affect items that appear in the edit or error menus For more information about the different menu types see the ContextMenu class entry This method works by setting all the Boolean members of my_cm builtInItems to false You can selectively make a built in item visible by setting its corresponding member in my_cm builtInItems to true as demonstrated in the following example Example The...

Страница 220: ...dler called when a user invokes the Flash Player context menu but before the menu is actually displayed This lets you customize the contents of the context menu based on the current application state You can also specify the callback handler for a ContextMenu object when you construct a new ContextMenu object For more information see the ContextMenu class entry Example The following example determ...

Страница 221: ...wlines and other white space characters are ignored No item can be more than 100 characters long Items that are identical to any built in menu item or to another custom item are ignored whether the matching item is visible or not Menu items are compared without regard to case punctuation or white space None of the following words can appear in a custom item Macromedia Flash Player or Settings Meth...

Страница 222: ...The default value is true This parameter is optional visible A Boolean value that indicates whether the menu item is visible or invisible The default value is true This parameter is optional Returns A reference to a ContextMenuItem object Description Constructor creates a new ContextMenuItem object that can be added to the ContextMenu customItems array Example This example adds Start and Stop menu...

Страница 223: ...aption text displayed in the context menu Example The following example displays the caption for the selected menu item Pause Game in the Output panel var my_cm ContextMenu new ContextMenu var menuItem_cmi ContextMenuItem new ContextMenuItem Pause Game onPause my_cm customItems push menuItem_cmi function onPause obj menuItem trace You chose menuItem caption this menu my_cm ...

Страница 224: ...e creates a new ContextMenuItem object named original_cmi with the caption Pause and a callback handler set to the function onPause The example then creates a copy of the ContextMenuItem object and assigns it to the variable copy_cmi var original_cmi ContextMenuItem new ContextMenuItem Pause onPause function onPause obj Object menu ContextMenu trace pause me var copy_cmi ContextMenuItem original_c...

Страница 225: ...mber of milliseconds that have elapsed since the SWF file started is traced The Start menu item is re enabled and the Stop menu item is disabled var my_cm ContextMenu new ContextMenu var startMenuItem ContextMenuItem new ContextMenuItem Start startHandler startMenuItem enabled true my_cm customItems push startMenuItem var stopMenuItem ContextMenuItem new ContextMenuItem Stop stopHandler true stopM...

Страница 226: ...andler receives two parameters obj a reference to the object under the mouse when the user invoked the Flash Player context menu and item a reference to the ContextMenuItem object that represents the selected menu item Example The following example assigns a function to the onSelect handler for a ContextMenuItem object named my_cmi The function displays the caption of the selected menu item var my...

Страница 227: ...en Save and Print A separator bar divides the Save and Print items The menu items are then added to the ContextMenu object s customItems array Finally the menu is attached to the current Timeline of the SWF file var my_cm ContextMenu new ContextMenu var open_cmi ContextMenuItem new ContextMenuItem Open itemHandler var save_cmi ContextMenuItem new ContextMenuItem Save itemHandler var print_cmi Cont...

Страница 228: ...en Stop is selected the number of milliseconds that have elapsed since the SWF file started is displayed The Start menu item is made visible and the Stop menu item is made invisible var my_cm ContextMenu new ContextMenu var startMenuItem ContextMenuItem new ContextMenuItem Start startHandler startMenuItem visible true my_cm customItems push startMenuItem var stopMenuItem ContextMenuItem new Contex...

Страница 229: ...ple In the following while loop continue causes the Flash interpreter to skip the rest of the loop body and jump to the top of the loop where the condition is tested trace example 1 var i Number 0 while i 10 if i 3 0 i continue trace i i In the following do while loop continue causes the Flash interpreter to skip the rest of the loop body and jump to the bottom of the loop where the condition is t...

Страница 230: ...quals 0 then the trace i statement is skipped trace example 3 for var i 0 i 10 i if i 3 0 continue trace i In the following for in loop continue causes the Flash interpreter to skip the rest of the loop body and jump back to the top of the loop where the next value in the enumeration is processed for i in _root if i version continue trace i See also do while for for in while ...

Страница 231: ...se methods to build SWF files that are extensions of the Flash authoring tool Such an extension could for example use the Flash Application Protocol to navigate a UDDI repository and download web services into the Actions toolbox Method summary for the CustomActions class Method Description CustomActions get Reads the contents of a custom action XML definition file CustomActions install Installs a...

Страница 232: ...eter is located it is read in its entirety and returned as a string Example The following example lists the custom actions in a ComboBox instance and gets the custom action when a Button instance is clicked Drag an instance of a ComboBox Button and TextArea onto the Stage Give the ComboBox an instance name of customActionName_cb the TextArea an instance name of customActionXml_ta and the Button an...

Страница 233: ...efinition file must be a simple filename without the xml file extension and without any directory separators or If a custom actions file already exists with the name customName it is overwritten If the Configuration ActionsPanel CustomActions directory does not exist when this method is invoked the directory is created Example The following example installs information into the Actions panel from ...

Страница 234: ... trace success CustomActions install dogclass this firstChild trace CustomActions list my_xml load dogclass xml Select Control Test Movie and if the XML loads successfully you will see true and an array containing the names of all the custom actions that are registered with the Flash authoring tool in the Output panel Close the SWF file and open the Actions panel You will see a new item in the Act...

Страница 235: ... a ComboBox instance and gets the custom action when a Button instance is clicked Drag an instance of a ComboBox Button and TextArea onto the Stage Give the ComboBox an instance name of customActionName_cb the TextArea an instance name of customActionXml_ta and the Button an instance name of view_button Enter the following ActionScript on Frame 1 of the Timeline import mx controls var customAction...

Страница 236: ...xample installs a new custom action and displays an array containing the names of all the custom actions that are registered with the Flash authoring tool in the Output panel When the uninstall_btn is clicked the custom action is then uninstalled An array containing names of the custom actions installed is displayed and dogclass should then be removed from the array Create a button called uninstal...

Страница 237: ...omatically adjusts its output for daylight saving time The time zone information database in Mac OS X is used to determine whether any date or time in the present or past should have a daylight saving time bias applied Mac OS 9 the operating system provides only enough information to determine whether the current date and time should have a daylight saving time bias applied Accordingly the date ob...

Страница 238: ...Month Returns the month according to universal time Date getUTCSeconds Returns the seconds according to universal time Date getYear Returns the year according to local time Date setDate Sets the day of the month according to local time Returns the new time in milliseconds Date setFullYear Sets the full year according to local time Returns the new time in milliseconds Date setHours Sets the hour ac...

Страница 239: ...is parameter is optional Returns A reference to a Date object Date setUTCHours Sets the hour according to universal time Returns the new time in milliseconds Date setUTCMilliseconds Sets the milliseconds according to universal time Returns the new time in milliseconds Date setUTCMinutes Sets the minutes according to universal time Returns the new time in milliseconds Date setUTCMonth Sets the mont...

Страница 240: ...new Date object for Mary s birthday August 12 1974 because the month parameter is zero based the example uses 7 for the month not 8 var maryBirthday Date new Date 74 7 12 The following example creates a new Date object and concatenates the returned values of Date getMonth Date getDate and Date getFullYear var today_date Date new Date var date_str String today_date getMonth 1 today_date getDate tod...

Страница 241: ...cording to local time Local time is determined by the operating system on which Flash Player is running Example The following example creates a new Date object and concatenates the returned values of Date getMonth Date getDate and Date getFullYear var today_date Date new Date var date_str String today_date getDate today_date getMonth 1 today_date getFullYear trace date_str displays current date in...

Страница 242: ... and so on of the specified Date object according to local time Local time is determined by the operating system on which Flash Player is running Example The following example creates a new Date object and uses getDay to determine the current day of the week var dayOfWeek_array Array new Array Sunday Monday Tuesday Wednesday Thursday Friday Saturday var today_date Date new Date var day_str String ...

Страница 243: ... number such as 2000 of the specified Date object according to local time Local time is determined by the operating system on which Flash Player is running Example The following example uses the constructor to create a Date object The trace statement shows the value returned by the getFullYear method var my_date Date new Date trace my_date getYear displays 104 trace my_date getFullYear displays cu...

Страница 244: ...is running Example The following example uses the constructor to create a Date object based on the current time and uses the getHours method to display hour values from that object var my_date Date new Date trace my_date getHours var my_date Date new Date var hourObj Object getHoursAmPm my_date getHours trace hourObj hours trace hourObj ampm function getHoursAmPm hour24 Number Object var returnObj...

Страница 245: ...teger from 0 to 999 of the specified Date object according to local time Local time is determined by the operating system on which Flash Player is running Example The following example uses the constructor to create a Date object based on the current time and uses the getMilliseconds method to return the milliseconds value from that object var my_date Date new Date trace my_date getMilliseconds ...

Страница 246: ...nutes an integer from 0 to 59 of the specified Date object according to local time Local time is determined by the operating system on which Flash Player is running Example The following example uses the constructor to create a Date object based on the current time and uses the getMinutes method to return the minutes value from that object var my_date Date new Date trace my_date getMinutes ...

Страница 247: ...current time and uses the getMonth method to return the month value from that object var my_date Date new Date trace my_date getMonth The following example uses the constructor to create a Date object based on the current time and uses the getMonth method to display the current month as a numeric value and display the name of the month var my_date Date new Date trace my_date getMonth trace getMont...

Страница 248: ...conds an integer from 0 to 59 of the specified Date object according to local time Local time is determined by the operating system on which Flash Player is running Example The following example uses the constructor to create a Date object based on the current time and uses the getSeconds method to return the seconds value from that object var my_date Date new Date trace my_date getSeconds ...

Страница 249: ...uary 1 1970 universal time for the specified Date object Use this method to represent a specific instant in time when comparing two or more Date objects Example The following example uses the constructor to create a Date object based on the current time and uses the getTime method to return the number of milliseconds since midnight January 1 1970 var my_date Date new Date trace my_date getTime ...

Страница 250: ... following example returns the difference between the local daylight saving time for San Francisco and universal time Daylight saving time is factored into the returned result only if the date defined in the Date object occurs during daylight saving time var my_date Date new Date trace my_date getTimezoneOffset 420 is displayed in the Output panel 7 hours 60 minutes hour 420 minutes This example i...

Страница 251: ...to 31 in the specified Date object according to universal time Example The following example creates a new Date object and uses Date getUTCDate and Date getDate The value returned by Date getUTCDate can differ from the value returned by Date getDate depending on the relationship between your local time zone and universal time var my_date Date new Date 2004 8 25 trace my_date getUTCDate output 25 ...

Страница 252: ...e object according to universal time Example The following example creates a new Date object and uses Date getUTCDay and Date getDay The value returned by Date getUTCDay can differ from the value returned by Date getDay depending on the relationship between your local time zone and universal time var today_date Date new Date trace today_date getDay output will be based on local timezone trace toda...

Страница 253: ...lowing example creates a new Date object and uses Date getUTCFullYear and Date getFullYear The value returned by Date getUTCFullYear may differ from the value returned by Date getFullYear if today s date is December 31 or January 1 depending on the relationship between your local time zone and universal time var today_date Date new Date trace today_date getFullYear display based on local timezone ...

Страница 254: ...cording to universal time Example The following example creates a new Date object and uses Date getUTCHours and Date getHours The value returned by Date getUTCHours may differ from the value returned by Date getHours depending on the relationship between your local time zone and universal time var today_date Date new Date trace today_date getHours display based on local timezone trace today_date g...

Страница 255: ...ns An integer Description Method returns the milliseconds an integer from 0 to 999 of the specified Date object according to universal time Example The following example creates a new Date object and uses getUTCMilliseconds to return the milliseconds value from the Date object var today_date Date new Date trace today_date getUTCMilliseconds ...

Страница 256: ...ters None Returns An integer Description Method returns the minutes an integer from 0 to 59 of the specified Date object according to universal time Example The following example creates a new Date object and uses getUTCMinutes to return the minutes value from the Date object var today_date Date new Date trace today_date getUTCMinutes ...

Страница 257: ...e following example creates a new Date object and uses Date getUTCMonth and Date getMonth The value returned by Date getUTCMonth can differ from the value returned by Date getMonth if today s date is the first or last day of a month depending on the relationship between your local time zone and universal time var today_date Date new Date trace today_date getMonth output based on local timezone tra...

Страница 258: ...ters None Returns An integer Description Method returns the seconds an integer from 0 to 59 of the specified Date object according to universal time Example The following example creates a new Date object and uses getUTCSeconds to return the seconds value from the Date object var today_date Date new Date trace today_date getUTCSeconds ...

Страница 259: ... the operating system on which Flash Player is running The year is the full year minus 1900 For example the year 2000 is represented as 100 Example The following example creates a Date object with the month and year set to May 2004 The Date getYear method returns 104 and Date getFullYear returns 2004 var today_date Date new Date 2004 4 trace today_date getYear output 104 trace today_date getFullYe...

Страница 260: ...ate object according to local time and returns the new time in milliseconds Local time is determined by the operating system on which Flash Player is running Example The following example initially creates a new Date object setting the date to May 15 2004 and uses Date setDate to change the date to May 25 2004 var today_date Date new Date 2004 4 15 trace today_date getDate displays 15 today_date s...

Страница 261: ...g to local time and returns the new time in milliseconds If the month and date parameters are specified they are set to local time Local time is determined by the operating system on which Flash Player is running Calling this method does not modify the other fields of the specified Date object but Date getUTCDay and Date getDay can report a new value if the day of the week changes as a result of c...

Страница 262: ...ate object according to local time and returns the new time in milliseconds Local time is determined by the operating system on which Flash Player is running Example The following example initially creates a new Date object setting the time and date to 8 00 a m on May 15 2004 and uses Date setHours to change the time to 4 00 p m var my_date Date new Date 2004 4 15 8 trace my_date getHours output 8...

Страница 263: ...eturns the new time in milliseconds Local time is determined by the operating system on which Flash Player is running Example The following example initially creates a new Date object setting the date to 8 30 a m on May 15 2004 with the milliseconds value set to 250 and then uses Date setMilliseconds to change the milliseconds value to 575 var my_date Date new Date 2004 4 15 8 30 0 250 trace my_da...

Страница 264: ...ct according to local time and returns the new time in milliseconds Local time is determined by the operating system on which Flash Player is running Example The following example initially creates a new Date object setting the time and date to 8 00 a m on May 15 2004 and then uses Date setMinutes to change the time to 8 30 a m var my_date Date new Date 2004 4 15 8 0 trace my_date getMinutes outpu...

Страница 265: ...ethod sets the month for the specified Date object in local time and returns the new time in milliseconds Local time is determined by the operating system on which Flash Player is running Example The following example initially creates a new Date object setting the date to May 15 2004 and uses Date setMonth to change the date to June 15 2004 var my_date Date new Date 2004 4 15 trace my_date getMon...

Страница 266: ...object in local time and returns the new time in milliseconds Local time is determined by the operating system on which Flash Player is running Example The following example initially creates a new Date object setting the time and date to 8 00 00 a m on May 15 2004 and uses Date setSeconds to change the time to 8 00 45 a m var my_date Date new Date 2004 4 15 8 0 0 trace my_date getSeconds output 0...

Страница 267: ...s Example The following example initially creates a new Date object setting the time and date to 8 00 a m on May 15 2004 and uses Date setTime to change the time to 8 30 a m var my_date Date new Date 2004 4 15 8 0 0 var myDate_num Number my_date getTime convert my_date to milliseconds myDate_num 30 60 1000 add 30 minutes in milliseconds my_date setTime myDate_num set my_date Date object 30 minutes...

Страница 268: ...iseconds Calling this method does not modify the other fields of the specified Date object but Date getUTCDay and Date getDay can report a new value if the day of the week changes as a result of calling this method Example The following example initially creates a new Date object with today s date uses Date setUTCDate to change the date value to 10 and changes it again to 25 var my_date Date new D...

Страница 269: ...nds Optionally this method can also set the month and date represented by the specified Date object Calling this method does not modify the other fields of the specified Date object but Date getUTCDay and Date getDay can report a new value if the day of the week changes as a result of calling this method Example The following example initially creates a new Date object with today s date uses Date ...

Страница 270: ...0 to 999 This parameter is optional Returns An integer Description Method sets the hour for the specified Date object in universal time and returns the new time in milliseconds Example The following example initially creates a new Date object with today s date uses Date setUTCHours to change the time to 8 30 a m and changes the time again to 5 30 47 p m var my_date Date new Date my_date setUTCHour...

Страница 271: ...ied Date object in universal time and returns the new time in milliseconds Example The following example initially creates a new Date object setting the date to 8 30 a m on May 15 2004 with the milliseconds value set to 250 and uses Date setUTCMilliseconds to change the milliseconds value to 575 var my_date Date new Date 2004 4 15 8 30 0 250 trace my_date getUTCMilliseconds output 250 my_date setU...

Страница 272: ...rom 0 to 999 This parameter is optional Returns An integer Description Method sets the minute for the specified Date object in universal time and returns the new time in milliseconds Example The following example initially creates a new Date object setting the time and date to 8 00 a m on May 15 2004 and uses Date setUTCMinutes to change the time to 8 30 a m var my_date Date new Date 2004 4 15 8 0...

Страница 273: ...nd returns the new time in milliseconds Calling this method does not modify the other fields of the specified Date object but Date getUTCDay and Date getDay might report a new value if the day of the week changes as a result of specifying a value for the date parameter Example The following example initially creates a new Date object setting the date to May 15 2004 and uses Date setMonth to change...

Страница 274: ... Returns An integer Description Method sets the seconds for the specified Date object in universal time and returns the new time in milliseconds Example The following example initially creates a new Date object setting the time and date to 8 00 00 a m on May 15 2004 and uses Date setSeconds to change the time to 8 30 45 a m var my_date Date new Date 2004 4 15 8 0 0 trace my_date getUTCSeconds outp...

Страница 275: ... and returns the new time in milliseconds Local time is determined by the operating system on which Flash Player is running Example The following example creates a new Date object with the date set to May 25 2004 uses setYear to change the year to 1999 and changes the year to 2003 var my_date Date new Date 2004 4 25 trace my_date getYear output 104 trace my_date getFullYear output 2004 my_date set...

Страница 276: ... Example The following example returns the information in the dateOfBirth_date Date object as a string var dateOfBirth_date Date new Date 74 7 12 18 15 trace dateOfBirth_date trace dateOfBirth_date toString The output from the trace statements will be in local time and will vary accordingly For Pacific Daylight Time the output will be seven hours earlier than universal time Mon Aug 12 18 15 00 GMT...

Страница 277: ...ption Method returns the number of milliseconds between midnight on January 1 1970 universal time and the time specified in the parameters This is a static method that is invoked through the Date object constructor not through a specific Date object This method lets you create a Date object that assumes universal time whereas the Date constructor assumes local time Example The following example cr...

Страница 278: ...have a default case statement A default case statement does not have to be last in the list If you use a default statement outside a switch statement it produces an error and the script doesn t compile Example In the following example the expression A does not equal the expressions B or D so the statement following the default keyword is run and the trace statement is sent to the Output panel var ...

Страница 279: ...cally used as a statement as shown in the following example delete x The delete operator can fail and return false if the reference parameter does not exist or cannot be deleted Predefined objects and properties and variables declared with var cannot be deleted You cannot use the delete operator to remove movie clips Example Usage 1 The following example creates an object uses it and deletes it af...

Страница 280: ...ndefined Usage 4 The following example shows the behavior of delete on object references var ref1 Object new Object ref1 name Jody copy the reference variable into a new variable and delete ref1 ref2 ref1 delete ref1 trace ref1 name ref1 name output undefined trace ref2 name ref2 name output Jody If ref1 had not been copied into ref2 the object would have been deleted when ref1 was deleted because...

Страница 281: ...he statements to be executed before the while loop begins many programmers believe that do while loops are easier to read If the condition always evaluates to true the do while loop is infinite If you enter an infinite loop you encounter problems with Flash Player and eventually get a warning message or crash the player Whenever possible you should use a for loop if you know the number of times yo...

Страница 282: ...282 Chapter 2 ActionScript Language Reference See also break continue while ...

Страница 283: ... original movie clip are not copied into the duplicate movie clip Use the removeMovieClip function or method to delete a movie clip instance created with duplicateMovieClip Example In the following example a new movie clip instance is created called img_mc An image is loaded into the movie clip and then the img_mc clip is duplicated The duplicated clip is called newImg_mc and this new clip is move...

Страница 284: ...functions however can still be type checked for return type and parameter types This behavior is especially useful when you work with MovieClip objects because there are many different ways of adding properties and objects to a movie clip dynamically such as MovieClip createEmptyMovieClip and MovieClip createTextField Subclasses of dynamic classes are also dynamic For more information see Creating...

Страница 285: ...raig i output Error Scene Scene 1 layer Layer 1 frame 1 Line 14 There is no property with the name dance craig dance true Total ActionScript Errors 1 Reported Errors 1 Add the dynamic keyword to the Person2 class so that the first line appears as follows dynamic class Person2 Test the code again and you see the following output craig dance true craig age 32 craig name Craiggers See also class exte...

Страница 286: ...e curly braces used to enclose the block of statements to be executed by the else statement are not necessary if only one statement will execute Example In the following example the else condition is used to check whether the age_txt variable is greater than or less than 18 if age_txt text 18 trace welcome user else trace sorry junior userObject minor true userObject accessAllowed false In the fol...

Страница 287: ...ndition returns true the Flash interpreter runs the statements that follow the condition inside curly braces If the else if condition is false Flash skips the statements inside the curly braces and runs the statements following the curly braces Use the else if statement to create branching logic in your scripts If there are multiple branches you should consider using a switch statement Example The...

Страница 288: ... Flash Player 6 Usage endinitclip Parameters None Returns Nothing Description Compiler directive indicates the end of a block of initialization actions Example initclip initialization actions go here endinitclip See also initclip CHAPTER 2 ActionScript Language Reference ...

Страница 289: ...meters message A string associated with the Error object this parameter is optional Returns A reference to an Error object Description Constructor creates a new Error object If message is specified its value is assigned to the object s Error message property Example In the following example a function throws an error with a specified message if the two strings that are passed to it are not identic...

Страница 290: ...Chapter 2 ActionScript Language Reference throw new Error Strings to not match try compareStrings Dog dog output Strings to not match catch e_err Error trace e_err toString See also throw try catch finally ...

Страница 291: ... numbers can be divided SUCCESS and the number are shown Specific errors are shown if you try to divide by 0 or enter only 1 parameter function divideNum num1 Number num2 Number Number if isNaN num1 isNaN num2 throw new Error divideNum function requires two numeric parameters else if num2 0 throw new Error cannot divide by zero return num1 num2 try var theNum Number divideNum 1 0 trace SUCCESS the...

Страница 292: ...rror divideNum function requires two numeric parameters else if denominator 0 throw new DivideByZeroError return numerator denominator try var theNum Number divideNumber 1 0 trace SUCCESS theNum output DivideByZeroError Unable to divide by zero catch e_err DivideByZeroError divide by zero error occurred trace e_err name e_err toString catch e_err Error generic error occurred trace e_err name e_err...

Страница 293: ...fined Example In the following example a function throws an error with a specified message if the two strings that are passed to it are not identical function compareStrings str1_str String str2_str String Void if str1_str str2_str throw new Error Strings to not match try compareStrings Dog dog output Strings to not match catch e_err Error trace e_err toString See also Error message throw try catc...

Страница 294: ... symbol is used to introduce escape characters and is not equivalent to the modulo operator Example The following code produces the result someuser 40somedomain 2Ecom var email String someuser somedomain com trace escape email In this example the at symbol was replaced with 40 and the dot symbol was replaced with 2E This is useful if you re trying to pass information to a remote server and the dat...

Страница 295: ...t named in expression cannot be found undefined is returned In Flash 4 eval was used to simulate arrays in Flash 5 or later you should use the Array class to simulate arrays In Flash 4 you can also use eval to dynamically set and retrieve the value of a variable or instance name However you can also do this with the array access operator In Flash 5 or later you cannot use eval to dynamically set a...

Страница 296: ...296 Chapter 2 ActionScript Language Reference You can also use the following ActionScript for var i 1 i 3 i this square i _mc _rotation 5 See also Array class set variable ...

Страница 297: ... The subclass inherits all the methods properties functions and so on that are defined in the superclass For more information see Creating subclasses in Using ActionScript in Flash Interfaces can also be extended using the extends keyword An interface that extends another interface includes all the original interface s method declarations Example In the following example the Car class extends the ...

Страница 298: ... var fullSizeSpare Boolean function Car param_numDoors Number param_color String param_fullSizeSpare Boolean this numDoors param_numDoors this color param_color this fullSizeSpare param_fullSizeSpare function activateCarAlarm Void trace Car activateCarAlarm function stop Void trace Car stop with anti lock brakes The following example instantiates a Car object calls a method defined in the Vehicle ...

Страница 299: ...erts false to a string it becomes false For more information see Automatic data typing in Using ActionScript in Flash Example This example shows how automatic data typing converts false to a number and to a string var bool1 Boolean Boolean false converts it to the number 0 trace 1 bool1 outputs 1 converts it to a string trace String bool1 outputs String false See also true CHAPTER 2 ActionScript L...

Страница 300: ...sManager overrides Flash Player s focus handling including use of this global property Example The following example demonstrates how to hide the yellow rectangle around any instances in a SWF file when they have focus in a browser window Create some buttons or movie clips and add the following ActionScript in frame 1 of the Timeline _focusrect false Change the publish settings to Flash Player 6 a...

Страница 301: ...and then starts a looping sequence The looping sequence begins by evaluating the condition expression If the condition expression evaluates to true statement is executed and the next expression is evaluated The looping sequence then begins again with the evaluation of the condition expression The curly braces used to enclose the block of statements to be executed by the for statement are not neces...

Страница 302: ... Reference The following example shows that curly braces are not necessary if only one statement will execute var sum Number 0 for var i Number 1 i 100 i sum i trace sum output 5050 See also increment decrement for in var while do while ...

Страница 303: ... Properties of the object are enumerated first then properties of its immediate prototype then properties of the prototype s prototype and so on The for in statement does not enumerate the same property name twice If the object child has prototype parent and both contain the property prop the for in statement called on child enumerates prop from child but ignores the one in parent The curly braces...

Страница 304: ...es the typeof operator with for in to iterate over a particular type of child for var name in this if typeof this name movieclip trace I have a movie clip child named name Note If you have several movie clips the output consists of the instance names of those clips The following example enumerates the children of a movie clip and sends each to Frame 2 in their respective Timelines The RadioButtonG...

Страница 305: ...r the command and parameters parameters of the fscommand function to control a SWF file playing in Flash Player including projectors Command Parameters Purpose quit None Closes the projector fullscreen true or false Specifying true sets Flash Player to full screen mode Specifying false returns the player to normal menu view allowscale true or false Specifying false sets the player so that the SWF ...

Страница 306: ...ation see the Director Support Center at www macromedia com support director Usage 4 In Visual Basic Visual C and other programs that can host ActiveX controls the fscommand function sends a VB event with two strings that can be handled in the environment s programming language For more information use the keywords Flash method to search the Flash Support Center at www macromedia com support flash...

Страница 307: ...and parameters as in the following example fscommand messagebox Hello name welcome to our website To test the SWF file select File Publish Preview HTML Note If you publish your SWF file using the Flash with FSCommand template in the HTML tab of the Publish Settings dialog box the myDocument_DoFSCommand function is inserted automatically The SWF file s NAME and ID attributes will be the filename Fo...

Страница 308: ...erent parameters to a function each time you call it so you can reuse a function in different situations Use the return statement in a function s statement s to cause a function to generate or return a value You can use this statement to define a function with the specified functionname parameters and statement s When a script calls a function the statements in the function s definition are execut...

Страница 309: ...n is defined and used in the same script the function definition may appear after using the function var y Number sqr 3 trace y output 9 function sqr x Number return Math pow x 2 The following function creates a LoadVars object and loads params txt into the SWF file When the file successfully loads variables loaded traces var myLV LoadVars new LoadVars myLV load params txt myLV onLoad function suc...

Страница 310: ...t are represented by Function objects which are instances of the Function class Method summary for the Function class Method Description Function apply Invokes the function represented by a Function object with parameters passed in through an array Function call Invokes the function represented by a Function object CHAPTER 2 ActionScript Language Reference ...

Страница 311: ...ied as an Array object unlike Function call which specifies parameters as a comma delimited list This is often useful when the number of parameters to be passed is not known until the script actually executes Example The following function invocations are equivalent Math atan2 1 0 Math atan2 apply null 1 0 The following simple example shows how apply passes an array of parameters function theFunct...

Страница 312: ...o apply var firstArray Array new Array 1 2 3 var secondArray Array new Array a b c use apply to set the value of this to be myObj and send firstArray theFunction apply myObj firstArray output this myObj true arguments 1 2 3 use apply to set the value of this to be myObj and send secondArray theFunction apply myObj secondArray output this myObj true arguments a b c See also Function call ...

Страница 313: ...r of the function invocation needs to be explicitly controlled Normally if a function is invoked as a method of an object within the body of the function this is set to myObject as shown in the following example myObject myMethod 1 2 3 In some situations you might want this to point somewhere else for example if a function must be invoked as a method of an object but is not actually stored as a me...

Страница 314: ...314 Chapter 2 ActionScript Language Reference var obj Object new myObject myMethod call obj obj The trace statement displays this obj true See also Function apply ...

Страница 315: ... you have defined in external class files Using implicit get methods lets you access properties of objects without accessing the property directly Implicit get set methods are syntactic shorthand for the Object addProperty method in ActionScript 1 For more information see Implicit getter setter methods in Using ActionScript in Flash Example In the following example you define a Team class The Team...

Страница 316: ...pt in a frame on the Timeline var giants Team new Team San Fran SFO trace giants name giants name San Francisco trace giants name output San Fran San Francisco When you trace giants name you use the get method to return the value of the property See also Object addProperty set ...

Страница 317: ...ns The value of the specified property Description Function returns the value of the specified property for the movie clip my_mc Example The following example creates a new movie clip someClip_mc and shows the alpha value _alpha for the movie clip someClip_mc in the Output panel this createEmptyMovieClip someClip_mc 999 trace The alpha of getProperty someClip_mc _name is getProperty someClip_mc _a...

Страница 318: ...ption Function returns the number of milliseconds that have elapsed since the SWF file started playing Example In the following example the getTimer and setInterval functions are used to create a simple timer this createTextField timer_txt this getNextHighestDepth 0 0 100 22 function updateTimer Void timer_txt text getTimer var intervalID Number setInterval updateTimer 100 CHAPTER 2 ActionScript L...

Страница 319: ...bles The POST method sends the variables in a separate HTTP header and is used for sending long strings of variables Returns Nothing Description Function loads a document from a specific URL into a window or passes variables to another application at a defined URL To test this function make sure the file to be loaded is at the specified location To use an absolute URL for example http www myserver...

Страница 320: ...POST for sending variables The following example uses GET to append variables to a URL var firstName String Gus var lastName String Richardson var age Number 92 myBtn_btn onRelease function getURL http www macromedia com _blank GET The following ActionScript uses POST to send variables in the HTTP header Make sure you test your documents in a browser window because otherwise your variables are sen...

Страница 321: ...The following examples trace the version number of the Flash Player playing the SWF file var flashVersion String getVersion trace flashVersion output WIN 7 0 19 0 trace version output WIN 7 0 19 0 trace System capabilities version output WIN 7 0 19 0 The following string is returned by the getVersion function WIN 7 0 19 0 This returned string indicates that the platform is Microsoft Windows and th...

Страница 322: ...similar to the Math or Date object Unlike Timeline declared or locally declared variables and functions global variables and functions are visible to every Timeline and scope in the SWF file provided they are not obscured by identifiers with the same names in inner scopes Example The following example creates a top level function factorial that is available to every Timeline and scope in a SWF fil...

Страница 323: ...e current scene You can use the scene parameter only on the root Timeline not within Timelines for movie clips or other objects in the document Example In the following example a document has two scenes sceneOne and sceneTwo Scene one contains a frame label on Frame 10 called newFrame and two buttons myBtn_btn and myOtherBtn_btn This ActionScript is placed on Frame 1 Scene 1 of the main Timeline s...

Страница 324: ...e frame in the current scene You can use the scene parameter only on the root Timeline not within Timelines for movie clips or other objects in the document Example In the following example a document has two scenes sceneOne and sceneTwo Scene one contains a frame label on Frame 10 called newFrame and two buttons myBtn_btn and myOtherBtn_btn This ActionScript is placed on Frame 1 Scene 1 of the ma...

Страница 325: ...wing example the condition inside the parentheses evaluates the variable name to see if it has the literal value Erica If it does the play function inside the curly braces runs if name Erica play The following example uses an if statement to evaluate how long it takes a user to click the submit_btn instance in a SWF file If a user clicks the button more than 10 seconds after the SWF file plays the...

Страница 326: ...326 Chapter 2 ActionScript Language Reference else this _parent message_txt text Very good you hit the button in difference seconds See also else ...

Страница 327: ...Settings dialog box This keyword is supported only when used in external script files not in scripts written in the Actions panel Description Keyword specifies that a class must define all the methods declared in the interface or interfaces being implemented For more information see Interfaces as data types in Using ActionScript in Flash Example See interface See also class extends interface CHAPT...

Страница 328: ...class files in the package working_directory macr utils users that you want to access you can import them all in a single statement as shown in the following example import macr util users You must issue the import statement before you try to access the imported class without fully specifying its name If you import a class but don t use it in your script the class isn t exported as part of the SWF...

Страница 329: ...import 329 For more information on importing see Importing classes and Using packages in Using ActionScript in Flash ...

Страница 330: ...ass files You can specify no path a relative path or an absolute path for the file to be included If you don t specify a path the AS file must be in one of the following locations The same directory as the FLA file The same directory as the script containing the include statement The global Include directory which is one of the following Windows 2000 or Windows XP C Documents and Settings user Loc...

Страница 331: ...h for a file to be included in your script Note that include statements do not end with a semicolon AS file is in same directory as FLA file or script or is in the global Include directory or the First Run Include directory include init_script as AS file is in a subdirectory of one of the above directories The subdirectory is named FLA_includes include FLA_includes init_script as AS file is in a d...

Страница 332: ...ce Infinity Availability Flash Player 5 Usage Infinity Description Constant specifies the IEEE 754 value representing positive infinity The value of this constant is the same as Number POSITIVE_INFINITY CHAPTER 2 ActionScript Language Reference ...

Страница 333: ...ns on Frame 1 of the SWF file Otherwise they execute immediately before the frame actions of the frame that contains the first instance of the associated movie clip symbol Initialization actions execute only once when a SWF file plays use them for one time initializations such as class definition and registration Example In the following example ActionScript is placed on Frame 1 inside a movie cli...

Страница 334: ...ongs to a specified class Tests whether object is an instance of class The instanceof operator does not convert primitive types to wrapper objects For example the following code returns true new String Hello instanceof String The following code returns false Hello instanceof String Example In the following example a for loop is used to loop through the SWF file and trace only TextInput component i...

Страница 335: ... the interface Only public members are allowed in an interface definition instance and class members are not permitted The get and set statements are not allowed in interface definitions For more information see Creating and using interfaces in Using ActionScript in Flash Example The following example shows several ways to define and implement interfaces in top level package as files Ia B C Ib D I...

Страница 336: ...x Number Number return x x function o Void trace o external script or Actions panel mvar new D trace mvar k 15 trace mvar n 7 49 trace mvar o o interface Ic extends Ia function p Void class E implements Ib Ic function k Number return 25 function n x Number Number return x 5 function o Void trace o function p Void trace p See also class extends implements ...

Страница 337: ...ic keyword was created specifically to enable compile time type checking for built in classes and objects and global variables and functions This keyword was not meant for general purpose use but may be of some value to developers seeking to enable compile time type checking with previously defined classes especially if the classes are defined using ActionScript 1 0 Example The following example s...

Страница 338: ... function return 2 this radius this setRadius function param_radius this radius param_radius ActionScript 2 0 code that uses the Circle class var myCircle Circle new Circle 5 trace myCircle getArea trace myCircle getDiameter myCircle setRadius 10 trace myCircle radius trace myCircle getArea trace myCircle getDiameter See also class implements ...

Страница 339: ...on Function evaluates expression and returns true if it is a finite number or false if it is infinity or negative infinity The presence of infinity or negative infinity indicates a mathematical error condition such as division by 0 Example The following example shows return values for isFinite isFinite 56 returns true isFinite Number POSITIVE_INFINITY returns false CHAPTER 2 ActionScript Language ...

Страница 340: ...r the isNaN function trace isNaN Tree returns true trace isNaN 56 returns false trace isNaN Number POSITIVE_INFINITY returns false The following example shows how you can use isNAN to check whether a mathematical expression contains an error var dividend Number var divisor Number divisor 1 trace isNaN dividend divisor output true The output is true because the variable dividend is undefined Do not...

Страница 341: ...essed Key getCode Returns the virtual key code of the last key pressed Key isDown Returns true if the key specified in the parameter is pressed Key isToggled Returns true if the Num Lock or Caps Lock key is activated Key removeListener Removes an object that was previously registered with Key addListener Property Description Key code Key BACKSPACE The key code value for the Backspace key 8 Key CAP...

Страница 342: ...e for the Right Arrow key 39 Key SHIFT The key code value for the Shift key 16 Key SPACE The key code value for the Spacebar 32 Key TAB The key code value for the Tab key 9 Key UP The key code value for the Up Arrow key 38 Method Description Key onKeyDown Notified when a key is pressed Key onKeyUp Notified when a key is released Property Description Key code ...

Страница 343: ...efines a function for onKeyDown and onKeyUp The last line uses addListener to register the listener with the Key object so that it can receive notification from the key down and key up events var myListener Object new Object myListener onKeyDown function trace You pressed a key myListener onKeyUp function trace You released a key Key addListener myListener The following example assigns the keyboar...

Страница 344: ... Reference myListener onKeyDown myOnKeyDown Key addListener myListener my_btn onPress myOnPress my_btn _accProps shortcut Ctrl 7 Accessibility updateProperties See also Key getCode Key isDown Key onKeyDown Key onKeyUp Key removeListener ...

Страница 345: ...for onKeyDown The last line uses addListener to register the listener with the Key object so that it can receive notification from the key down event var keyListener Object new Object keyListener onKeyDown function if Key isDown Key BACKSPACE trace you pressed the Backspace key else trace you DIDN T press the Backspace key Key addListener keyListener When using this example make sure that you sele...

Страница 346: ...ses addListener to register the listener with the Key object so that it can receive notification from the key down event var keyListener Object new Object keyListener onKeyDown function if Key isDown Key CAPSLOCK trace you pressed the Caps Lock key trace tCaps Lock Key isToggled Key CAPSLOCK Key addListener keyListener Information displays in the Output panel when you press the Caps Lock key The O...

Страница 347: ... about the shortcut available to screen readers see _accProps In this example when you press Control 7 the myOnPress function displays the text hello in the Output panel function myOnPress trace hello function myOnKeyDown 55 is key code for 7 if Key isDown Key CONTROL Key getCode 55 Selection setFocus my_btn my_btn onPress var myListener Object new Object myListener onKeyDown myOnKeyDown Key addLi...

Страница 348: ...tNextHighestDepth var mouseListener Object new Object mouseListener onMouseDown function this drawing true canvas_mc moveTo _xmouse _ymouse canvas_mc lineStyle 3 0x99CC00 100 mouseListener onMouseUp function this drawing false mouseListener onMouseMove function if this drawing canvas_mc lineTo _xmouse _ymouse updateAfterEvent Mouse addListener mouseListener var keyListener Object new Object keyLis...

Страница 349: ...ou press the Spacebar Give a sound in the library a linkage identifier of horn_id for this example var DISTANCE Number 10 var horn_sound Sound new Sound horn_sound attachSound horn_id var keyListener_obj Object new Object keyListener_obj onKeyDown function switch Key getCode case Key SPACE horn_sound start break case Key LEFT car_mc _x DISTANCE break case Key UP car_mc _y DISTANCE break case Key R...

Страница 350: ...350 Chapter 2 ActionScript Language Reference Key END Availability Flash Player 5 Usage Key END Number Description Property constant associated with the key code value for the End key 35 ...

Страница 351: ...nt var DISTANCE Number 5 var keyListener Object new Object keyListener onKeyDown function switch Key getCode case Key LEFT car_mc onEnterFrame function this _x DISTANCE break case Key UP car_mc onEnterFrame function this _y DISTANCE break case Key RIGHT car_mc onEnterFrame function this _x DISTANCE break case Key DOWN car_mc onEnterFrame function this _y DISTANCE break case Key ENTER delete car_mc...

Страница 352: ...displays information that includes how long it took you to press the key var keyListener Object new Object keyListener onKeyDown function if Key isDown Key ESCAPE get the current timer convert the value to seconds and round it to two decimal places var timer Number Math round getTimer 10 100 trace you pressed the Esc key getTimer ms timer s Key addListener keyListener When using this example make ...

Страница 353: ...in Flash The keyListener object is then registered to the Key object which broadcasts the onKeyDown message whenever a key is pressed while the SWF file plays var keyListener Object new Object keyListener onKeyDown function trace The ASCII code for the last key typed is Key getAscii Key addListener keyListener When using this example make sure that you select Control Disable Keyboard Shortcuts in ...

Страница 354: ... The keyListener object is then registered to the Key object which broadcasts the onKeyDown message whenever a key is pressed while the SWF file plays var keyListener Object new Object keyListener onKeyDown function trace The ASCII code for the last key typed is Key getAscii Key addListener keyListener When using this example make sure that you select Control Disable Keyboard Shortcuts in the test...

Страница 355: ...ates of 0 0 When you press the Home key car_mc returns to 0 0 Create a movie clip that has a linkage ID car_id and add the following ActionScript to Frame 1 of the Timeline this attachMovie car_id car_mc this getNextHighestDepth _x 0 _y 0 car_mc onPress function this startDrag car_mc onRelease function this stopDrag var keyListener Object new Object keyListener onKeyDown function if Key isDown Key...

Страница 356: ...lowing example creates a new listener object and defines a function for onKeyDown The last line uses addListener to register the listener with the Key object so that it can receive notification from the key down event and display information in the Output panel var keyListener Object new Object keyListener onKeyDown function if Key isDown Key INSERT trace You pressed the Insert key Key addListener...

Страница 357: ...d keyboard see Appendix C Keyboard Keys and Key Code Values in Using ActionScript in Flash Returns A Boolean value Description Method returns true if the key specified in keycode is pressed false otherwise On the Macintosh the key code values for the Caps Lock and Num Lock keys are identical Example The following script lets the user control a movie clip s car_mc location car_mc onEnterFrame funct...

Страница 358: ...t responds to the onKeyDown event by calling Key isToggled For more information see Using event listeners in Using ActionScript in Flash The keyListener object is then registered to the Key object which broadcasts the onKeyDown message whenever a key is pressed while the SWF file plays var keyListener Object new Object keyListener onKeyDown function if Key isDown Key CAPSLOCK trace you pressed the...

Страница 359: ...ze true numLock_txt html true var keyListener Object new Object keyListener onKeyDown function capsLock_txt htmlText b Caps Lock b Key isToggled Key CAPSLOCK numLock_txt htmlText b Num Lock b Key isToggled 144 Key addListener keyListener ...

Страница 360: ...ound plays when you press the Spacebar Give a sound in the library a linkage identifier of horn_id for this example var DISTANCE Number 10 var horn_sound Sound new Sound horn_sound attachSound horn_id var keyListener_obj Object new Object keyListener_obj onKeyDown function switch Key getCode case Key SPACE horn_sound start break case Key LEFT car_mc _x DISTANCE break case Key UP car_mc _y DISTANCE...

Страница 361: ...istener with the Key object as shown in the following example var keyListener Object new Object keyListener onKeyDown function trace DOWN Code Key getCode tACSII Key getAscii tKey chr Key getAscii keyListener onKeyUp function trace UP Code Key getCode tACSII Key getAscii tKey chr Key getAscii Key addListener keyListener Listeners enable different pieces of code to cooperate because multiple listen...

Страница 362: ...ister the listener with the Key object as shown in the following example var keyListener Object new Object keyListener onKeyDown function trace DOWN Code Key getCode tACSII Key getAscii tKey chr Key getAscii keyListener onKeyUp function trace UP Code Key getCode tACSII Key getAscii tKey chr Key getAscii Key addListener keyListener Listeners enable different pieces of code to cooperate because mult...

Страница 363: ...code value for the Page Down key 34 Example The following example rotates a movie clip called car_mc when you press the Page Down and Page Up keys var keyListener Object new Object keyListener onKeyDown function if Key isDown Key PGDN car_mc _rotation 5 else if Key isDown Key PGUP car_mc _rotation 5 Key addListener keyListener ...

Страница 364: ...ted with the key code value for the Page Up key 33 Example The following example rotates a movie clip called car_mc when you press the Page Down and Page Up keys var keyListener Object new Object keyListener onKeyDown function if Key isDown Key PGDN car_mc _rotation 5 else if Key isDown Key PGUP car_mc _rotation 5 Key addListener keyListener ...

Страница 365: ...ject s listener list the method returns false Description Method removes an object previously registered with Key addListener Example The following example moves a movie clip called car_mc using the Left and Right arrow keys The listener is removed when you press Escape and car_mc no longer moves var keyListener Object new Object keyListener onKeyDown function switch Key getCode case Key LEFT car_...

Страница 366: ...sound plays when you press the Spacebar Give a sound in the library a linkage identifier of horn_id for this example var DISTANCE Number 10 var horn_sound Sound new Sound horn_sound attachSound horn_id var keyListener_obj Object new Object keyListener_obj onKeyDown function switch Key getCode case Key SPACE horn_sound start break case Key LEFT car_mc _x DISTANCE break case Key UP car_mc _y DISTANC...

Страница 367: ... the key code value for the Shift key 16 Example The following example scales car_mc when you press Shift var keyListener Object new Object keyListener onKeyDown function if Key isDown Key SHIFT car_mc _xscale 2 car_mc _yscale 2 else if Key isDown Key CONTROL car_mc _xscale 2 car_mc _yscale 2 Key addListener keyListener ...

Страница 368: ...nd plays when you press the Spacebar Give a sound in the library a linkage identifier of horn_id for this example var DISTANCE Number 10 var horn_sound Sound new Sound horn_sound attachSound horn_id var keyListener_obj Object new Object keyListener_obj onKeyDown function switch Key getCode case Key SPACE horn_sound start break case Key LEFT car_mc _x DISTANCE break case Key UP car_mc _y DISTANCE b...

Страница 369: ...e date in the text field when you press Tab this createTextField date_txt this getNextHighestDepth 0 0 100 22 date_txt autoSize true var keyListener Object new Object keyListener onKeyDown function if Key isDown Key TAB var today_date Date new Date date_txt text today_date toString Key addListener keyListener When using this example make sure that you select Control Disable Keyboard Shortcuts in t...

Страница 370: ...d plays when you press the Spacebar Give a sound in the library a linkage identifier of horn_id for this example var DISTANCE Number 10 var horn_sound Sound new Sound horn_sound attachSound horn_id var keyListener_obj Object new Object keyListener_obj onKeyDown function switch Key getCode case Key SPACE horn_sound start break case Key LEFT car_mc _x DISTANCE break case Key UP car_mc _y DISTANCE br...

Страница 371: ...WF file that you load into the Flash Player using loadMovieNum You can assign levels in any order If you assign a level that already contains a SWF file including _level0 the SWF file at that level is unloaded and replaced by the new SWF file Example The following example stops the playhead in the main Timeline of the SWF file sub swf that is loaded into _level9 The sub swf file contains animation...

Страница 372: ...variables Returns Nothing Description Function loads a SWF or JPEG file into Flash Player while the original SWF file plays Tip If you want to monitor the progress of the download use MovieClipLoader loadClip instead of this function The loadMovie function lets you display several SWF files at once and switch among SWF files without loading another HTML document Without the loadMovie function Flas...

Страница 373: ...he following loadMovie statement loads the SWF file sub swf from the same directory into a new movie clip called logo_mc that s created using createEmptyMovieClip this createEmptyMovieClip logo_mc 999 loadMovie sub swf logo_mc You could add the following code to load a JPEG image called image1 jpg from the same directory as the SWF file loading sub swf The JPEG is loaded when you click a button ca...

Страница 374: ...file into a level in Flash Player while the originally loaded SWF file plays Tip If you want to monitor the progress of the download use MovieClipLoader loadClip instead of this function Normally Flash Player displays a single SWF file and then closes The loadMovieNum action lets you display several SWF files at once and switch among SWF files without loading another HTML document If you want to s...

Страница 375: ... Also in both cases the loaded file inherits rotation and scaling and the original content is overwritten in the specified level Use unloadMovieNum to remove SWF files or images that were loaded with loadMovieNum Example The following example loads the JPEG image tim jpg into level 2 of Flash Player loadMovieNum http www macromedia com devnet mx coldfusion articles basic_chart tim jpg 2 See also l...

Страница 376: ...ate variables in the active SWF file with new values The text at the specified URL must be in the standard MIME format application x www form urlencoded a standard format used by CGI scripts Any number of variables can be specified For example the following phrase defines several variables company Macromedia address 600 Townsend city San Francisco zip 94103 In SWF files running in a version earlie...

Страница 377: ...le in the params txt file named done this createEmptyMovieClip target_mc this getNextHighestDepth loadVariables params txt target_mc function checkParamsLoaded if target_mc done undefined trace not yet else trace finished loading killing interval trace for i in target_mc trace i target_mc i trace clearInterval param_interval var param_interval setInterval checkParamsLoaded 100 params txt includes ...

Страница 378: ...evel You can also use this function to update variables in the active SWF file with new values The text at the specified URL must be in the standard MIME format application x www form urlencoded a standard format used by CGI scripts Any number of variables can be specified For example the following phrase defines several variables company Macromedia address 600 Townsend city San Francisco zip 9410...

Страница 379: ...used to check the progress of the data being loaded into the SWF The script checks for a variable in the params txt file named done loadVariablesNum params txt 2 function checkParamsLoaded if _level2 done undefined trace not yet else trace finished loading killing interval trace for i in _level2 trace i _level2 i trace clearInterval param_interval var param_interval setInterval checkParamsLoaded 1...

Страница 380: ...nScript name and value pairs rather than an XML DOM tree stored in the XML object The LoadVars class follows the same security restrictions as the XML class For information about using the LoadVars class and example code see Using the LoadVars class in Using ActionScript in Flash Method summary for the LoadVars class Method Description LoadVars addRequestHeader Adds or changes HTTP headers for POS...

Страница 381: ... send and load data Example The following example creates a LoadVars object called my_lv var my_lv LoadVars new LoadVars Property Description LoadVars contentType A string that indicates the MIME type of the data LoadVars loaded A Boolean value that indicates whether a load or sendAndLoad operation has completed Event handler Description LoadVars onData Invoked when data has been completely downlo...

Страница 382: ... added or changed with this method Accept Ranges Age Allow Allowed Connection Content Length Content Location Content Range ETag Host Last Modified Locations Max Forwards Proxy Authenticate Proxy Authorization Public Range Retry After Server TE Trailer Transfer Encoding Upgrade URI Vary Via Warning and WWW Authenticate Example The following example adds a custom HTTP header named SOAPAction with a...

Страница 383: ...LoadVars addRequestHeader 383 See also XML addRequestHeader ...

Страница 384: ... call LoadVars send or LoadVars sendAndLoad The default is application x www form urlencoded Example The following example creates a LoadVars object and displays the default content type of the data that is sent to the server var my_lv LoadVars new LoadVars trace my_lv contentType output application x www form urlencoded See also LoadVars send LoadVars sendAndLoad ...

Страница 385: ...oadVars onData event handler Most users do not need to call this method directly If you override the LoadVars onData event handler you can explicitly call LoadVars decode to parse a string of variables Example The following example traces the three variables Create a new LoadVars object var my_lv LoadVars new LoadVars Convert the variable string to properties my_lv decode name Mort score 250000 tr...

Страница 386: ...al file that resides on your hard disk this example will not work properly because in test movie mode Flash Player loads local files in their entirety To see this code work add a ProgressBar instance called loadvars_pb to the Stage Then add the following ActionScript to Frame 1 of the Timeline var loadvars_pb mx controls ProgressBar var my_lv LoadVars new LoadVars loadvars_pb mode manual this crea...

Страница 387: ...Vars load command so that the parameter refers to a valid text file using HTTP If you attempt to use this example to load a local file that resides on your hard disk this example will not work properly because in test movie mode Flash Player loads local files in their entirety To see this code work add a ProgressBar instance called loadvars_pb to the Stage Then add the following ActionScript to Fr...

Страница 388: ...388 Chapter 2 my_lv load place a valid URL pointing to a text file here ...

Страница 389: ... this call A superdomain is derived by removing the left most component of a file s URL For example a SWF file at www someDomain com can load data from sources at store someDomain com because both files are in the same superdomain named someDomain com In SWF files of any version running in Flash Player 7 or later url must be in exactly the same domain see Flash Player security features in Using Ac...

Страница 390: ... and the Macromedia DevNet article Macromedia Flash MX and PHP at www macromedia com devnet mx flash articles flashmx_php html An example is also in the guestbook fla file in the HelpExamples folder The following list gives typical paths to this folder Windows Program Files Macromedia Flash MX 2004 Samples HelpExamples Macintosh HD Applications Macromedia Flash MX 2004 Samples HelpExamples LoadVar...

Страница 391: ... to false when the operation completes the loaded property is set to true If the operation has not completed or has failed with an error the loaded property remains set to false This property is similar to the XML loaded property Example The following example loads a text file and displays information in the Output panel when the operation completes var my_lv LoadVars new LoadVars my_lv onLoad fun...

Страница 392: ... either undefined or a string that contains the URL encoded name value pairs downloaded from the server If the src parameter is undefined an error occurred while downloading the data from the server The default implementation of LoadVars onData invokes LoadVars onLoad You can override this default implementation by assigning a custom function to LoadVars onData but LoadVars onLoad is not called un...

Страница 393: ...sult_ta and a Button instance called submit_button to the Stage When the user clicks the Login button instance in the following example two LoadVars objects are created send_lv and result_lv The send_lv object copies the name from the name_ti instance and sends the data to greeting cfm The result from this script loads into the result_lv object and the server response displays in the TextArea inst...

Страница 394: ...le in the HelpExamples folder Typical paths to the HelpExamples folder are Windows Program Files Macromedia Flash MX 2004 Samples HelpExamples Macintosh HD Applications Macromedia Flash MX 2004 Samples HelpExamples LoadVars loaded LoadVars load LoadVars sendAndLoad ...

Страница 395: ... This is the same format used by loadVariables The MIME content type sent in the HTTP request headers is the value of my_lv contentType or the default application x www form urlencoded The POST method is used unless GET is specified You must specify the target parameter to ensure that the script or application at the specified URL will be executed If you omit the target parameter the function will...

Страница 396: ...used to handle the information For example the script might check if the user got a high score and then insert that data into a database table var my_lv LoadVars new LoadVars my_lv playerName playerName_txt text my_lv playerScore playerScore_txt text my_lv send setscore cfm _blank POST See also LoadVars sendAndLoad XML send ...

Страница 397: ...es are downloaded into targetObject in the same manner as LoadVars load In SWF files running in a version of the player earlier than Flash Player 7 url must be in the same superdomain as the SWF file that is issuing this call A superdomain is derived by removing the left most component of a file s URL For example a SWF file at www someDomain com can load data from sources at store someDomain com b...

Страница 398: ...t to Frame 1 of the Timeline var submitListener Object new Object submitListener click function evt Object var result_lv LoadVars new LoadVars result_lv onLoad function success Boolean if success result_ta text result_lv welcomeMessage else result_ta text Error connecting to server var send_lv LoadVars new LoadVars send_lv name name_ti text send_lv sendAndLoad http www flash mx com mm greeting cfm...

Страница 399: ... all enumerable variables in my_lv in the MIME content encoding application x www form urlencoded Example The following example instantiates a new LoadVars object creates two properties and uses toString to return a string containing both properties in URL encoded format var my_lv LoadVars new LoadVars my_lv name Gary my_lv age 26 trace my_lv toString output age 26 name Gary ...

Страница 400: ...0 22 result_txt border true var receiving_lc LocalConnection new LocalConnection receiving_lc methodToExecute function param1 Number param2 Number result_txt text param1 param2 receiving_lc connect lc_name Code in the sending SWF file var sending_lc LocalConnection new LocalConnection sending_lc send lc_name methodToExecute 5 7 The simplest way to use a LocalConnection object is to allow communica...

Страница 401: ...c methodToExecute function param1 Number param2 Number result_txt text param1 param2 receiving_lc connect lc_name The following SWF file sends the request to the first SWF file Code in the sending SWF file var sending_lc LocalConnection new LocalConnection sending_lc send lc_name methodToExecute 5 7 Event handler Description LocalConnection allowDomain Invoked whenever the current receiving LocalC...

Страница 402: ...402 Chapter 2 ActionScript Language Reference See also LocalConnection connect LocalConnection send ...

Страница 403: ...ngDomain this domain Use LocalConnection allowDomain to explicitly permit LocalConnection objects from specified domains or from any domain to execute methods of the receiving LocalConnection object If you don t declare the sendingDomain parameter you probably want to accept commands from any domain and the code in your handler would be simply return true If you do declare sendingDomain you probab...

Страница 404: ...the file is completely loaded The best way to determine when a child SWF file finishes loading is to use MovieClipLoader onLoadComplete The opposite situation can also occur You might create a child SWF file that wants to accept LocalConnection calls from its parent but doesn t know the domain of its parent In this situation implement this method by checking whether the domain argument matches the...

Страница 405: ... an error break sending_lc send _mylc sayHello name_ti text send_button addEventListener click sendListener In the following example the receiving SWF file which resides in thisDomain com accepts commands only from SWF files located in thisDomain com or thatDomain com var aLocalConn LocalConnection new LocalConnection aLocalConn Trace function aString aTextField aString newline aLocalConn allowDom...

Страница 406: ...y by other SWF files hosted using the HTTPS protocol This implementation maintains the integrity provided by the HTTPS protocol Using this method to override the default behavior is not recommended as it compromises HTTPS security However you might need to do so for example if you need to permit access to HTTPS files published for Flash Player 7 or later from HTTP files published for Flash Player ...

Страница 407: ...07 my_lc allowInsecureDomain function sendingDomain String return sendingDomain this domain my_lc sayHello function name String welcome_txt text Hello name my_lc connect lc_name See also LocalConnection allowDomain LocalConnection connect ...

Страница 408: ... The following example closes a connection called receiving_lc when you click a Button component instance called close_button this createTextField welcome_txt this getNextHighestDepth 10 10 100 22 this createTextField status_txt this getNextHighestDepth 10 42 100 44 var receiving_lc LocalConnection new LocalConnection receiving_lc sayHello function name String welcome_txt text Hello name receiving...

Страница 409: ...the examples in this section By default Flash Player resolves connectionName into a value of superdomain connectionName where superdomain is the superdomain of the SWF file containing the LocalConnection connect command For example if the SWF file containing the receiving LocalConnection object is located at www someDomain com connectionName resolves to someDomain com connectionName If a SWF file ...

Страница 410: ...from any domain will be accepted the SWF with the receiving LocalConnection object can be moved to another domain without altering any sending LocalConnection objects For more information see the discussion of connectionName in LocalConnection send and also the LocalConnection allowDomain and LocalConnection domain entries Note Colons are used as special characters to separate the superdomain from...

Страница 411: ...s a button called play_btn When you click the button it connects to SWF 1 and passes two variables The first variable contains the MP3 file to stream and the second variable is the filename that you display in the Label component instance in SWF 1 play_btn onRelease function var sending_lc LocalConnection new LocalConnection sending_lc send lc_name playMP3 song1 mp3 Album 01 Song SWF 3 contains a ...

Страница 412: ...t The most common way to use this command is to include the domain name of the sending LocalConnection object as a parameter to the method you plan to invoke in the receiving LocalConnection object or with LocalConnection allowDomain to accept commands from a specified domain If you are enabling communication only between LocalConnection objects that are located in the same domain you probably don...

Страница 413: ...that it will accept commands only from SWF files at mydomain com lines 51 to 53 The sending SWF file invokes the aSum method of a connection named mydomain com sum line 68 and passes the following parameters its superdomain the name of the connection to receive the reply result and the values to be used by aSum 123 and 456 The aSum method line 6 is invoked with the following values sender mydomain...

Страница 414: ... domain 58 if getVersion 7 this getSWFVersion 7 59 split domain name into elements 60 var domainArray Array channelDomain split if more than two elements are found chop off first element to create superdomain 61 if domainArray length 2 62 63 domainArray shift 64 channelDomain domainArray join 65 66 67 lc connect result 68 lc send mydomain com sum aSum channelDomain result aResult 123 456 See also ...

Страница 415: ... the method does not exist The only way to know for sure if the method was invoked is to have the receiving object send a reply to the sending object If the information object returned by this event handler contains a level value of error Flash cannot send the command to a receiving LocalConnection object most likely because there is no receiving LocalConnection object connected whose name corresp...

Страница 416: ...ect Object switch infoObject level case status status_ta text LocalConnection connected successfully break case error status_ta text LocalConnection encountered an error break sending_lc send lc_name sayHello name_ti text send_button addEventListener click sendListener See also LocalConnection send System onStatus ...

Страница 417: ...Connection connect connectionName command the receiving LocalConnection object The object used with this command is called the sending LocalConnection object The SWF files that contain the sending and receiving objects must be running on the same client computer There is a limit to the amount of data you can pass as parameters to this command If the command returns false but your syntax is correct...

Страница 418: ... connectionName in the receiving LocalConnection object you can only do this in the sending LocalConnection object Example For an example of communicating between LocalConnection objects located in the same domain see LocalConnection connect For an example of communicating between LocalConnection objects located in any domain see LocalConnection allowDomain For an example of communicating between ...

Страница 419: ...values before calling the method and then provide the calculated value as the parameter or you can provide the entire right side of the equation with the angle s measure in degrees in place of degrees as the radian parameter To calculate a radian value use the following formula radians degrees Math PI 180 The following is an example of passing the equation as a parameter to calculate the sine of a...

Страница 420: ... a tangent Property Description Math E Euler s constant and the base of natural logarithms approximately 2 718 Math LN2 The natural logarithm of 2 approximately 0 693 Math LOG2E The base 2 logarithm of e approximately 1 442 Math LN2 The natural logarithm of 10 approximately 2 302 Math LOG10E The base 10 logarithm of e approximately 0 434 Math PI The ratio of the circumference of a circle to its di...

Страница 421: ...s Usage Math abs x Number Number Parameters x A number Returns A number Description Method computes and returns an absolute value for the number specified by the parameter x Example The following example shows how Math abs returns the absolute value of a number and does not affect the value of the x parameter called num in this example var num Number 12 var numAbsolute Number Math abs num trace nu...

Страница 422: ...age Math acos x Number Number Parameters x A number from 1 0 to 1 0 Returns A number the arc cosine of the parameter x Description Method computes and returns the arc cosine of the number specified in the parameter x in radians Example The following example displays the arc cosine for several values trace Math acos 1 output 3 14159265358979 trace Math acos 0 output 1 5707963267949 trace Math acos ...

Страница 423: ...r Parameters x A number from 1 0 to 1 0 Returns A number between negative pi divided by 2 and positive pi divided by 2 Description Method computes and returns the arc sine for the number specified in the parameter x in radians Example The following example displays the arc sine for several values trace Math asin 1 output 1 5707963267949 trace Math asin 0 output 0 trace Math asin 1 output 1 5707963...

Страница 424: ...tangent of an angle Returns A number between negative pi divided by 2 and positive pi divided by 2 Description Method computes and returns the value in radians of the angle whose tangent is specified in the parameter tangent The return value is between negative pi divided by 2 and positive pi divided by 2 Example The following example displays the angle value for several tangents trace Math atan 1...

Страница 425: ...dinate of the point x A number specifying the x coordinate of the point Returns A number Description Method computes and returns the angle of the point y x in radians when measured counterclockwise from a circle s x axis where 0 0 represents the center of the circle The return value is between positive pi and negative pi Example The following example displays the following radians from the specifi...

Страница 426: ...s that Flash Player 5 supports Usage Math ceil x Number Number Parameters x A number or expression Returns An integer that is both closest to and greater than or equal to parameter x Description Method returns the ceiling of the specified number or expression The ceiling of a number is the closest integer that is greater than or equal to the number Example The following code returns a value of 13 ...

Страница 427: ...le measured in radians Returns A number from 1 0 to 1 0 Description Method computes and returns the cosine of the specified angle in radians To calculate a radian see Description on page 419 of the Math class entry Example The following example displays the cosine for several different angles trace Math cos 0 output 1 trace Math cos 90 output 0 44807361612917 trace Math cos 180 output 0 5984600690...

Страница 428: ...lue of e is 2 71828182845905 Example This example shows how Math E is used to compute continuously compounded interest for a simple case of 100 percent interest over a one year period var principal Number 100 var simpleInterest Number 100 var continuouslyCompoundedInterest Number 100 Math E principal trace Beginning principal principal trace Simple interest after one year simpleInterest trace Cont...

Страница 429: ...rts Usage Math exp x Number Number Parameters x The exponent a number or expression Returns A number Description Method returns the value of the base of the natural logarithm e to the power of the exponent specified in the parameter x The constant Math E can provide the value of e Example The following example displays the logarithm for two number values trace Math exp 1 output 2 71828182845905 tr...

Страница 430: ...pports Usage Math floor x Number Number Parameters x A number or expression Returns The integer that is both closest to and less than or equal to parameter x Description Method returns the floor of the number or expression specified in the parameter x The floor is the closest integer that is less than or equal to the specified number or expression Example The following code returns a value of 12 M...

Страница 431: ...nctions that Flash Player 5 supports Usage Math log x Number Number Parameters x A number or expression with a value greater than 0 Returns The logarithm of parameter x Description Method returns the logarithm of parameter x Example The following example displays the logarithm for three numerical values trace Math log 0 output Infinity trace Math log 1 output 0 trace Math log 2 output 0 6931471805...

Страница 432: ...roperties of the Math class are emulated using approximations and might not be as accurate as the non emulated math functions that Flash Player 5 supports Usage Math LN2 Number Description Constant a mathematical constant for the natural logarithm of 2 expressed as loge2 with an approximate value of 0 6931471805599453 ...

Страница 433: ...and might not be as accurate as the non emulated math functions that Flash Player 5 supports Usage Math LN10 Number Description Constant a mathematical constant for the natural logarithm of 10 expressed as loge10 with an approximate value of 2 302585092994046 Example This example traces the value of Math LN10 trace Math LN10 output 2 30258509299405 ...

Страница 434: ...ot be as accurate as the non emulated math functions that Flash Player 5 supports Usage Math LOG2E Number Parameters None Returns Nothing Description Constant a mathematical constant for the base 2 logarithm of the constant e Math E expressed as log2e with an approximate value of 1 442695040888963387 Example This example traces the value of Math LOG2E trace Math LOG2E Output 1 44269504088896 ...

Страница 435: ...ot be as accurate as the non emulated math functions that Flash Player 5 supports Usage Math LOG10E Number Description Constant a mathematical constant for the base 10 logarithm of the constant e Math E expressed as log10e with an approximate value of 0 4342944819032518 Example This example traces the value of Math LOG10E trace Math LOG10E Output 0 434294481903252 ...

Страница 436: ...ge Math max x Number y Number Number Parameters x A number or expression y A number or expression Returns A number Description Method evaluates x and y and returns the larger value Example The following example displays Thu Dec 30 00 00 00 GMT 0700 2004 which is the larger of the evaluated expressions var date1 Date new Date 2004 11 25 var date2 Date new Date 2004 11 30 var maxDate Number Math max...

Страница 437: ...er y Number Number Parameters x A number or expression y A number or expression Returns A number Description Method evaluates x and y and returns the smaller value Example The following example displays Sat Dec 25 00 00 00 GMT 0700 2004 which is the smaller of the evaluated expressions var date1 Date new Date 2004 11 25 var date2 Date new Date 2004 11 30 var minDate Number Math min date1 getTime d...

Страница 438: ...raws a circle using the mathematical constant pi and the Drawing API drawCircle this 100 100 50 function drawCircle mc MovieClip x Number y Number r Number Void mc lineStyle 2 0xFF0000 100 mc moveTo x r y mc curveTo r x Math tan Math PI 8 r y Math sin Math PI 4 r x Math sin Math PI 4 r y mc curveTo Math tan Math PI 8 r x r y x r y mc curveTo Math tan Math PI 8 r x r y Math sin Math PI 4 r x Math s...

Страница 439: ...eClip canvas_mc this getNextHighestDepth var mouseListener Object new Object mouseListener onMouseDown function this origX _xmouse this origY _ymouse mouseListener onMouseUp function this newX _xmouse this newY _ymouse var minY Math min this origY this newY var nextDepth Number canvas_mc getNextHighestDepth var line_mc MovieClip canvas_mc createEmptyMovieClip line nextDepth _mc nextDepth line_mc m...

Страница 440: ...ndom Number Parameters None Returns A number Description Method returns a pseudo random number n where 0 n 1 The number returned is a pseudo random number because it is not generated by a truly random natural phenomenon such as radioactive decay Example The following example returns a random number between two specified integers function randRange min Number max Number Number var randomNum Number ...

Страница 441: ... Description Method rounds the value of the parameter x up or down to the nearest integer and returns the value If parameter x is equidistant from its two nearest integers that is the number ends in 5 the value is rounded up to the next higher integer Example The following example returns a random number between two specified integers function randRange min Number max Number Number var randomNum N...

Страница 442: ...ng example draws a circle using the mathematical constant pi the sine of an angle and the Drawing API drawCircle this 100 100 50 function drawCircle mc MovieClip x Number y Number r Number Void mc lineStyle 2 0xFF0000 100 mc moveTo x r y mc curveTo r x Math tan Math PI 8 r y Math sin Math PI 4 r x Math sin Math PI 4 r y mc curveTo Math tan Math PI 8 r x r y x r y mc curveTo Math tan Math PI 8 r x ...

Страница 443: ...ne this createEmptyMovieClip canvas_mc this getNextHighestDepth var mouseListener Object new Object mouseListener onMouseDown function this origX _xmouse this origY _ymouse mouseListener onMouseUp function this newX _xmouse this newY _ymouse var minY Math min this origY this newY var nextDepth Number canvas_mc getNextHighestDepth var line_mc MovieClip canvas_mc createEmptyMovieClip line nextDepth ...

Страница 444: ... using approximations and might not be as accurate as the non emulated math functions that Flash Player 5 supports Usage Math SQRT1_2 Number Description Constant a mathematical constant for the square root of one half with an approximate value of 0 7071067811865476 Example This example traces the value of Math SQRT1_2 trace Math SQRT1_2 Output 0 707106781186548 ...

Страница 445: ...g approximations and might not be as accurate as the non emulated math functions that Flash Player 5 supports Usage Math SQRT2 Description Constant a mathematical constant for the square root of 2 with an approximate value of 1 4142135623730951 Example This example traces the value of Math SQRT2 trace Math SQRT2 Output 1 4142135623731 ...

Страница 446: ... a circle using the mathematical constant pi the tangent of an angle and the Drawing API drawCircle this 100 100 50 function drawCircle mc MovieClip x Number y Number r Number Void mc lineStyle 2 0xFF0000 100 mc moveTo x r y mc curveTo r x Math tan Math PI 8 r y Math sin Math PI 4 r x Math sin Math PI 4 r y mc curveTo Math tan Math PI 8 r x r y x r y mc curveTo Math tan Math PI 8 r x r y Math sin ...

Страница 447: ... class Method Description Microphone get Returns a default or specified Microphone object or null if the microphone is not available Microphone setGain Specifies the amount by which the microphone should boost the signal Microphone setRate Specifies the rate at which the microphone should capture sound in kHz Microphone setSilenceLevel Specifies the amount of sound required to activate the microph...

Страница 448: ...crophone silenceLevel The amount of sound required to activate the microphone Microphone silenceTimeOut The number of milliseconds between the time the microphone stops detecting sound and Microphone onActivity false is called Microphone useEchoSuppression A Boolean value that specifies whether echo suppression is being used Event handler Description Microphone onActivity Invoked when the micropho...

Страница 449: ...operty is set to 1 Example The following example displays the activity level of the current microphone in a ProgressBar instance called activityLevel_pb var activityLevel_pb mx controls ProgressBar activityLevel_pb mode manual activityLevel_pb label Activity Level 3 activityLevel_pb setStyle themeColor 0xFF0000 this createEmptyMovieClip sound_mc this getNextHighestDepth var active_mic Microphone M...

Страница 450: ... gain_pb to display and a NumericStepper instance called gain_nstep to set the microphone s gain value this createEmptyMovieClip sound_mc this getNextHighestDepth var active_mic Microphone Microphone get sound_mc attachAudio active_mic gain_pb label Gain 3 gain_pb mode manual gain_pb setProgress active_mic gain 100 gain_nstep value active_mic gain function changeGain active_mic setGain gain_nstep ...

Страница 451: ...ce the same microphone Thus if your script contains the lines mic1 Microphone get and mic2 Microphone get both mic1 and mic2 reference the same default microphone In general you shouldn t pass a value for index simply use the Microphone get method to return a reference to the default microphone By means of the Microphone settings panel discussed later in this section the user can specify the defau...

Страница 452: ...s in use by another application or there are no microphones installed on the system To determine whether any microphones are installed use Microphones names length To display the Flash Player Microphone Settings panel which lets the user choose the microphone to be referenced by Microphone get use System showSettings 2 Example The following example lets the user specify the default microphone and ...

Страница 453: ...x microphone You can use the ComboBox to switch between the devices var mic_lbl mx controls Label var mic_cb mx controls ComboBox this createEmptyMovieClip sound_mc this getNextHighestDepth var active_mic Microphone Microphone get sound_mc attachAudio active_mic mic_lbl text active_mic index active_mic name mic_cb dataProvider Microphone names mic_cb selectedIndex active_mic index var cbListener O...

Страница 454: ... specifies whether the user has denied access to the microphone true or allowed access false When this value changes Microphone onStatus is invoked For more information see Microphone get Example This example gets the default microphone and checks whether it is muted var active_mic Microphone Microphone get trace active_mic muted See also Microphone get Microphone onStatus ...

Страница 455: ...on your computer system including an array of names and the default device var status_ta mx controls TextArea status_ta html false status_ta setStyle fontSize 9 var microphone_array Array Microphone names var active_mic Microphone Microphone get status_ta text The default device is active_mic name newline newline status_ta text You have microphone_array length device s installed newline newline fo...

Страница 456: ...ntry Calling Microphone names requires an extensive examination of the hardware and it may take several seconds to build the array In most cases you can just use the default microphone Example The following example displays information about the sound capturing device s on your computer system including an array of names and the default device var status_ta mx controls TextArea status_ta html fals...

Страница 457: ...ked use Microphone setSilenceLevel Example The following example displays the amount of activity level in a ProgressBar instance called activityLevel_pb When the microphone detects sound it invokes the onActivity function which modifies the ProgressBar instance var activityLevel_pb mx controls ProgressBar activityLevel_pb mode manual activityLevel_pb label Activity Level 3 this createEmptyMovieCli...

Страница 458: ...and this event handler is invoked with an information object whose code property is Microphone Muted and whose level property is Status To determine whether the user has denied or allowed access to the microphone without processing this event handler use Microphone muted Note If the user chooses to permanently allow or deny access to all SWF files from a specified domain this method is not invoked...

Страница 459: ...us a href asfunction System showSettings u infoObj code u a this createTextField status_txt this getNextHighestDepth 0 0 100 22 status_txt html true status_txt autoSize true status_txt htmlText font size 72 color FF0000 muted font status_txt _x Stage width status_txt _width 2 status_txt _y Stage height status_txt _height 2 status_txt _visible active_mic muted See also Microphone get Microphone mut...

Страница 460: ... rate_cb to change the rate at which your microphone captures sound The current rate displays in a Label instance called rate_lbl this createEmptyMovieClip sound_mc this getNextHighestDepth var active_mic Microphone Microphone get sound_mc attachAudio active_mic var rate_array Array new Array 5 8 11 22 44 rate_cb dataProvider rate_array rate_cb labelFunction function item Object return item kHz fo...

Страница 461: ...this setting like a volume knob on a stereo 0 is no volume and 50 is normal volume numbers below 50 specify lower than normal volume while numbers above 50 specify higher than normal volume Example The following example uses a ProgressBar instance called gain_pb to display and a NumericStepper instance called gain_nstep to set the microphone s gain value this createEmptyMovieClip sound_mc this get...

Страница 462: ...g values 5 8 11 22 or 44 If it is not the value is rounded to the nearest acceptable value that the sound capture device supports active_mic setRate userRate The following example lets you use a ComboBox instance called rate_cb to change the rate at which your microphone captures sound The current rate displays in a Label instance called rate_lbl this createEmptyMovieClip sound_mc this getNextHigh...

Страница 463: ...Microphone setRate 463 See also Microphone rate ...

Страница 464: ...o detect when audio levels suggest that a person is talking When someone is not talking bandwidth can be saved because there is no need to send the associated audio stream This information can also be used for visual feedback so that users know they or others are silent Silence values correspond directly to activity values Complete silence is an activity value of 0 Constant loud noise as loud as c...

Страница 465: ... minimum 0 silenceLevel_nstep maximum 100 silenceLevel_nstep value active_mic silenceLevel var nstepListener Object new Object nstepListener change function evt Object active_mic setSilenceLevel evt target value active_mic silenceTimeOut silenceLevel_nstep addEventListener change nstepListener this onEnterFrame function silenceLevel_pb setProgress active_mic activityLevel 100 active_mic onActivity...

Страница 466: ...headset on the same computer If your SWF file allows users to specify the sound output device you may want to call Microphone setUseEchoSuppression true if they indicate they are using speakers and will be using the microphone as well Users can also adjust these settings in the Flash Player Microphone Settings panel Example The following example turns on echo suppression if the user selects a Chec...

Страница 467: ...icrophone setUseEchoSuppression 467 active_mic setUseEchoSuppression evt target selected useEchoSuppression_ch addEventListener click chListener See also Microphone setGain Microphone useEchoSuppression ...

Страница 468: ...NumericStepper this createEmptyMovieClip sound_mc this getNextHighestDepth var active_mic Microphone Microphone get sound_mc attachAudio active_mic silenceLevel_pb label Activity level 3 silenceLevel_pb mode manual silenceLevel_nstep minimum 0 silenceLevel_nstep maximum 100 silenceLevel_nstep value active_mic silenceLevel var nstepListener Object new Object nstepListener change function evt Object...

Страница 469: ...Microphone silenceLevel 469 See also Microphone gain Microphone setSilenceLevel ...

Страница 470: ... it displays the activity level of the audio stream var silenceLevel_pb mx controls ProgressBar var silenceTimeOut_nstep mx controls NumericStepper this createEmptyMovieClip sound_mc this getNextHighestDepth var active_mic Microphone Microphone get sound_mc attachAudio active_mic silenceLevel_pb label Activity level 3 silenceLevel_pb mode manual silenceTimeOut_nstep minimum 0 silenceTimeOut_nstep ...

Страница 471: ...Microphone silenceTimeOut 471 silenceLevel_pb label Activity level inactive See also Microphone setSilenceLevel ...

Страница 472: ...ityLevel_pb displays the current activity level of the audio stream var useEchoSuppression_ch mx controls CheckBox var activityLevel_pb mx controls ProgressBar this createEmptyMovieClip sound_mc this getNextHighestDepth var active_mic Microphone Microphone get sound_mc attachAudio active_mic activityLevel_pb mode manual activityLevel_pb label Activity Level 3 useEchoSuppression_ch selected active_...

Страница 473: ... a user runs a JSAPI script by selecting Commands Run Command However you can use this function in an ActionScript script to call a JSAPI command directly If you use MMExecute in a script on Frame 1 of your file the command executes when the SWF file is loaded For more information on the JSAPI see www macromedia com go jsapi_info_en Example The following command will output the number of items in ...

Страница 474: ...the bottom of the Window Other Panels menu The ActionScript trace function does not work from a Flash panel this example uses the JavaScript fl trace version to get the output It might be easier to copy the results of MMExecute to a text field that is part of your Flash Panel file ...

Страница 475: ... for the Mouse class Listener summary for the Mouse class Method Description Mouse addListener Registers an object to receive onMouseDown onMouseMove onMouseWheel and onMouseUp notification Mouse hide Hides the mouse pointer in the SWF file Mouse removeListener Removes an object that was registered with addListener Mouse show Displays the mouse pointer in the SWF file Method Description Mouse onMo...

Страница 476: ...ouseMove onMouseUp or onMouseWheel method invoked Multiple objects can listen for mouse notifications If the listener newListener is already registered no change occurs See also Mouse onMouseDown Mouse onMouseMove Mouse onMouseUp Mouse onMouseWheel Example This example is excerpted from the animation fla file in the HelpExamples Folder Create a mouse listener object var mouseListener Object new Ob...

Страница 477: ...he animation fla file in the HelpExamples Folder The following list shows typical paths to the HelpExamples Folder Windows Program Files Macromedia Flash MX 2004 Samples HelpExamples Macintosh HD Applications Macromedia Flash MX 2004 Samples HelpExamples ...

Страница 478: ...f the cursor_mc movie clip instance to the x and y cursor position Create a movie clip and set its Linkage identifier to cursor_id Add the following ActionScript to Frame 1 of the Timeline to use this script you need a symbol in your library with a Linkage Identifier of pointer_id this attachMovie pointer_id pointer_mc this getNextHighestDepth Mouse hide var mouseListener Object new Object mouseLi...

Страница 479: ... following example uses the Drawing API to draw a rectangle whenever the user clicks drags and releases the mouse at runtime this createEmptyMovieClip canvas_mc this getNextHighestDepth var mouseListener Object new Object mouseListener onMouseDown function this isDrawing true this orig_x _xmouse this orig_y _ymouse this target_mc canvas_mc createEmptyMovieClip canvas_mc getNextHighestDepth mouseLi...

Страница 480: ...480 Chapter 2 ActionScript Language Reference See also Mouse addListener ...

Страница 481: ...ers enable different pieces of code to cooperate because multiple listeners can receive notification about a single event Example The following example uses the mouse pointer as a tool to draw lines using onMouseMove and the Drawing API The user draws a line when they drag the mouse pointer this createEmptyMovieClip canvas_mc this getNextHighestDepth var mouseListener Object new Object mouseListen...

Страница 482: ... identifier to pointer_id Add the following ActionScript to Frame 1 of the Timeline to use this script you need a symbol in your library with a Linkage Identifier of pointer_id this attachMovie pointer_id pointer_mc this getNextHighestDepth Mouse hide var mouseListener Object new Object mouseListener onMouseMove function pointer_mc _x _xmouse pointer_mc _y _ymouse updateAfterEvent Mouse addListene...

Страница 483: ...ecause multiple listeners can receive notification about a single event Example The following example uses the mouse pointer as a tool to draw lines using onMouseMove and the Drawing API The user draws a line when they drag the mouse pointer The user stops drawing the line when they release the mouse button this createEmptyMovieClip canvas_mc this getNextHighestDepth var mouseListener Object new O...

Страница 484: ...ouse wheel To use the onMouseWheel listener you must create a listener object You can then define a function for onMouseWheel and use addListener to register the listener with the Mouse object Note Mouse wheel event listeners are available only in Windows versions of Flash Player Example The following example shows how to create a listener object that responds to mouse wheel events In this example...

Страница 485: ...Wheel 485 mouseListener onMouseWheel function delta Number line_mc _rotation delta mouseListener onMouseDown function trace Down Mouse addListener mouseListener See also Mouse addListener TextField mouseWheelEnabled ...

Страница 486: ...adds the mouse listener after it is removed so the user can draw lines again Add the following ActionScript to Frame 1 of the Timeline Add an instance of the Button component to be placed in the Library This example attaches and positions three Button instances on the Stage this createClassObject mx controls Button clear_button this getNextHighestDepth _x 10 _y 10 label clear this createClassObjec...

Страница 487: ...er Object new Object stopDrawingListener click function evt Object Mouse removeListener mouseListener evt target enabled false startDrawing_button enabled true stopDrawing_button addEventListener click stopDrawingListener var startDrawingListener Object new Object startDrawingListener click function evt Object Mouse addListener mouseListener evt target enabled false stopDrawing_button enabled true...

Страница 488: ...sible by default Example The following example attaches a custom cursor from the library when it rolls over a movie clip called my_mc Give a movie clip in the Library a Linkage identifier of cursor_help_id and add the following ActionScript to Frame 1 of the Timeline my_mc onRollOver function Mouse hide this attachMovie cursor_help_id cursor_mc this getNextHighestDepth _x this _xmouse _y this _ymo...

Страница 489: ...Creates an empty movie clip MovieClip createTextField Creates an empty text field MovieClip duplicateMovieClip Duplicates the specified movie clip MovieClip getBounds Returns the minimum and maximum x and y coordinates of a SWF file in a specified coordinate space MovieClip getBytesLoaded Returns the number of bytes loaded for the specified movie clip MovieClip getBytesTotal Returns the size of th...

Страница 490: ...p prevFrame Sends the playhead to the previous frame of the movie clip MovieClip removeMovieClip Removes the movie clip from the Timeline if it was created with duplicateMovieClip MovieClip duplicateMovieClip or MovieClip attachMovie MovieClip setMask Sets a movie clip as the mask for the specified movie clip MovieClip startDrag Specifies a movie clip as draggable and begins dragging the movie cli...

Страница 491: ...Clip _framesloaded Read only the number of frames that have been loaded from a streaming SWF file MovieClip _height The height of a movie clip instance in pixels MovieClip hitArea A reference to a movie clip that serves as the hit area for another movie clip MovieClip _lockroot The specification of what _root refers to when a SWF file is loaded into a movie clip MovieClip menu An object that assoc...

Страница 492: ... specifying the percentage that the movie clip is scaled horizontally MovieClip _y The y coordinate of a movie clip instance MovieClip _ymouse Read only the y coordinate of the mouse pointer within a movie clip instance MovieClip _yscale The value specifying the percentage for vertically scaling a movie clip Event handler Description MovieClip onData Invoked when all the data is loaded into a movi...

Страница 493: ...e pointer is over a movie clip MovieClip onReleaseOutside Invoked when the mouse is clicked over a movie clip and released while the pointer is outside the movie clip s area MovieClip onRollOut Invoked when the pointer rolls outside of a movie clip area MovieClip onRollOver Invoked when the mouse pointer rolls over a movie clip MovieClip onSetFocus Invoked when a movie clip has input focus and a k...

Страница 494: ...dlers of the MovieClip class by creating a subclass For more information see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The following code sets the _alpha property of a dynamically created movie clip named holder_mc to 50 when the mouse rolls over the movie clip Add the following ActionScript to your FLA or AS file this createEmptyMovieClip holder_mc this getNe...

Страница 495: ...tream connection Add a new Video symbol by opening the Library panel and selecting New Video from the Library options menu Give it the instance name my_video Dynamically load the FLV video at runtime Use the attachAudio method to attach the audio from the FLV file to a movie clip on the Stage Then you can control the audio in the movie clip using the Sound class and two buttons called volUp_btn an...

Страница 496: ...ume_txt text Volume audio_sound getVolume The following example specifies a microphone as the audio source for a dynamically created movie clip instance called audio_mc var active_mic Microphone Microphone get this createEmptyMovieClip audio_mc this getNextHighestDepth audio_mc attachAudio active_mic See also Microphone class NetStream play Sound class Video attachVideo ...

Страница 497: ...d All properties of initObject are copied into the new instance The properties specified with initObject are available to the constructor function This parameter is optional Returns A reference to the newly created instance Description Method takes a symbol from the library and attaches it to the SWF file on the Stage specified by my_mc Use MovieClip removeMovieClip or MovieClip unloadMovie to rem...

Страница 498: ...ill associated with it that path is closed with a line and then filled This is similar to what happens when MovieClip endFill is called You can extend the methods and event handlers of the MovieClip class by creating a subclass For more information see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The following example creates a square with red fill on the Stage t...

Страница 499: ...atios An array of color distribution ratios valid values are 0 255 This value defines the percentage of the width where the color is sampled at 100 percent matrix A transformation matrix that is an object with either of the following two sets of properties a b c d e f g h i which can be used to describe a 3 x 3 matrix of the following form a b c d e f g h i The following example uses a beginGradie...

Страница 500: ...the parent clip for the upper left corner of the gradient w is the width of the gradient h is the height of the gradient and r is the rotation in radians of the gradient The following example uses a beginGradientFill method with a matrix parameter that is an object with these properties this createEmptyMovieClip gradient_mc 1 with gradient_mc colors 0xFF0000 0x0000FF alphas 100 100 ratios 0 0xFF m...

Страница 501: ... object for the matrix parameter are missing or invalid You can extend the methods and event handlers of the MovieClip class by creating a subclass For more information see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The following code uses both methods to draw two stacked rectangles with a red blue gradient fill and a 5 pixel solid lime green stroke this create...

Страница 502: ...502 Chapter 2 ActionScript Language Reference endFill See also MovieClip beginFill MovieClip endFill MovieClip lineStyle MovieClip lineTo MovieClip moveTo ...

Страница 503: ...box graphic it removes the graphic from the Stage this createEmptyMovieClip box_mc this getNextHighestDepth box_mc onRelease function this clear drawBox box_mc 10 10 320 240 function drawBox mc MovieClip x Number y Number w Number h Number Void mc lineStyle 0 mc beginFill 0xEEEEEE mc moveTo x y mc lineTo x w y mc lineTo x w y h mc lineTo x y h mc lineTo x y mc endFill An example is also in the dra...

Страница 504: ... method but you don t need to provide an external linkage identifier for the new movie clip The registration point for a newly created empty movie clip is the upper left corner This method fails if any of the parameters are missing You can extend the methods and event handlers of the MovieClip class by creating a subclass For more information see Assigning a class to a movie clip symbol in Using A...

Страница 505: ... depth parameter determines the new text field s z order position in the movie clip Each position in the z order can contain only one object If you create a new text field on a depth that already has a text field the new text field will replace the existing text field To avoid overwriting existing text fields use the MovieClip getInstanceAtDepth to determine whether a specific depth is already occ...

Страница 506: ...lass to a movie clip symbol in Using ActionScript in Flash Example The following example creates a text field with a width of 300 a height of 100 an x coordinate of 100 a y coordinate of 100 no border red and underlined text this createTextField my_txt 1 100 100 300 100 my_txt multiline true my_txt wordWrap true var my_fmt TextFormat new TextFormat my_fmt color 0xFF0000 my_fmt underline true my_tx...

Страница 507: ... property returns the number of the frame in which the playhead is located in the Timeline specified by my_mc Example The following example uses the _currentframe property to direct the playhead of the movie clip actionClip_mc to advance five frames ahead of its current location actionClip_mc gotoAndStop actionClip_mc _currentframe 5 ...

Страница 508: ...line style from the current drawing position to anchorX anchorY using the control point specified by controlX controlY The current drawing position is then set to anchorX anchorY If the movie clip you are drawing in contains content created with the Flash drawing tools calls to curveTo are drawn underneath this content If you call curveTo before any calls to moveTo the current drawing position def...

Страница 509: ...an Math PI 8 r x r y x r y mc curveTo Math tan Math PI 8 r x r y Math sin Math PI 4 r x Math sin Math PI 4 r y mc curveTo r x Math tan Math PI 8 r y r x y mc curveTo r x Math tan Math PI 8 r y Math sin Math PI 4 r x Math sin Math PI 4 r y mc curveTo Math tan Math PI 8 r x r y x r y mc curveTo Math tan Math PI 8 r x r y Math sin Math PI 4 r x Math sin Math PI 4 r y mc curveTo r x Math tan Math PI 8...

Страница 510: ... are using ActionScript 2 0 which does not support slash syntax Example The following example evaluates the _droptarget property of the garbage_mc movie clip instance and uses eval to convert it from slash syntax to a dot syntax reference The garbage_mc reference is then compared to the reference to the trashcan_mc movie clip instance If the two references are equivalent the visibility of garbage_...

Страница 511: ...d creates an instance of the specified movie clip while the SWF file is playing Duplicated movie clips always start playing at Frame 1 no matter what frame the original movie clip is on when the duplicateMovieClip method is called Variables in the parent movie clip are not copied into the duplicate movie clip Movie clips that have been created using duplicateMovieClip are not duplicated if you cal...

Страница 512: ...vie clip if a movie clip is playing it continues to play The movie clip continues to receive movie clip events for example mouseDown mouseUp keyDown and keyUp The enabled property only governs the button like properties of a movie clip You can change the enabled property at any time the modified movie clip is immediately enabled or disabled The enabled property can be read out of a prototype objec...

Страница 513: ...sed with a line and then filled Example The following example creates a square with red fill on the Stage this createEmptyMovieClip square_mc this getNextHighestDepth square_mc beginFill 0xFF0000 square_mc moveTo 10 10 square_mc lineTo 100 10 square_mc lineTo 100 100 square_mc lineTo 10 100 square_mc lineTo 10 10 square_mc endFill An example is also in the drawingapi fla file in the HelpExamples f...

Страница 514: ...ption Property if the value is undefined or false a movie clip cannot receive input focus unless it is a button If the focusEnabled property value is true a movie clip can receive input focus even if it is not a button Example The following example sets the focusEnabled property for the movie clip my_mc to false my_mc focusEnabled false ...

Страница 515: ...individual movie clip basis Example This example demonstrates how to hide the yellow rectangle around a specified movie clip instance in a SWF file when it has focus in a browser window Create three movie clips called mc1_mc mc2_mc and mc3_mc and add the following ActionScript in Frame 1 of the Timeline mc1_mc _focusrect true mc2_mc _focusrect false mc3_mc _focusrect true mc1_mc onRelease traceOnR...

Страница 516: ...hat the SWF file is loading until a specified frame in the SWF file has finished loading Example The following example uses the _framesloaded property to start a SWF file when all the frames are loaded If all the frames aren t loaded the _xscale property of the movie clip instance loader is increased proportionally to create a progress bar Enter the following ActionScript in Frame 1 of the Timelin...

Страница 517: ...o local coordinates respectively You can extend the methods and event handlers of the MovieClip class by creating a subclass For more information see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The following example creates a movie clip called square_mc The code draws a square for that movie clip and uses MovieClip getBounds to display the coordinate values of t...

Страница 518: ...518 Chapter 2 ActionScript Language Reference See also MovieClip globalToLocal MovieClip localToGlobal ...

Страница 519: ... more information see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The following example uses the _framesloaded property to start a SWF file when all the frames are loaded If all the frames aren t loaded the _xscale property of the movie clip instance loader is increased proportionally to create a progress bar Enter the following ActionScript in Frame 1 of the Ti...

Страница 520: ... For more information see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The following example uses the _framesloaded property to start a SWF file when all the frames are loaded If all the frames aren t loaded the _xscale property of the movie clip instance loader is increased proportionally to create a progress bar Enter the following ActionScript in Frame 1 of th...

Страница 521: ... Flash You can extend the methods and event handlers of the MovieClip class by creating a subclass For more information see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The following code traces the depth of all movie clip instances on the Stage for var i in this if typeof this i movieclip trace movie clip this i _name is at depth this i getDepth See also MovieCl...

Страница 522: ...eClip to determine if the depth parameter you want to pass to any of these methods already contains a movie clip For more information see Managing movie clip depths in Using ActionScript in Flash You can extend the methods and event handlers of the MovieClip class by creating a subclass For more information see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The fol...

Страница 523: ...hs in Using ActionScript in Flash You can extend the methods and event handlers of the MovieClip class by creating a subclass For more information see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The following example creates a new movie clip instance logo_mc at the next highest depth available At runtime logo_mc renders in front of all other instances at the sam...

Страница 524: ... if an error occurs and Flash can t determine the SWF version of my_mc 1 is returned You can extend the methods and event handlers of the MovieClip class by creating a subclass For more information see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The following ActionScript displays the Flash Player version for the SWF file and for a SWF file that loads into a mov...

Страница 525: ...Flash However other products may do so for example Macromedia FlashPaper The contents of the TextSnapshot object aren t dynamic that is if the movie clip moves to a different frame or is altered in some way for example objects in the movie clip are added or removed the TextSnapshot object might not represent the current text in the movie clip To ensure that the object s contents are current reissu...

Страница 526: ...t htmlText textformat The following text appears in text_mc textSnapshot_txt getTextRunInfo type Function setSelectColor type Function findText type Function hitTestTextNearPos type Function getSelectedText type Function getText type Function getSelected type Function setSelected type Function getCount type Function See also TextSnapshot object ...

Страница 527: ...mall numbers of variables POST sends the variables in a separate HTTP header and is used for long strings of variables Returns Nothing Description Method loads a document from the specified URL into the specified window The getURL method can also be used to pass variables to another application defined at the URL using a GET or POST method You can extend the methods and event handlers of the Movie...

Страница 528: ...Add the following ActionScript to a FLA or AS file in the same directory as an image called photo1 jpg this createTextField coords_txt this getNextHighestDepth 10 10 100 22 coords_txt html true coords_txt multiline true coords_txt autoSize true this createEmptyMovieClip target_mc this getNextHighestDepth target_mc _x 100 target_mc _y 100 target_mc loadMovie photo1 jpg var mouseListener Object new ...

Страница 529: ...MovieClip globalToLocal 529 See also MovieClip getBounds MovieClip localToGlobal ...

Страница 530: ...information see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The following example uses the _framesloaded property to start a SWF file when all the frames are loaded If all the frames aren t loaded the _xscale property of the movie clip instance loader is increased proportionally to create a progress bar Enter the following ActionScript in Frame 1 of the Timeline...

Страница 531: ...class to a movie clip symbol in Using ActionScript in Flash Example The following example uses the _framesloaded property to start a SWF file when all the frames are loaded If all the frames aren t loaded the _xscale property of the movie clip instance loader is increased proportionally to create a progress bar Enter the following ActionScript in Frame 1 of the Timeline var pctLoaded Number Math r...

Страница 532: ...lip in the Output panel this createEmptyMovieClip image_mc this getNextHighestDepth var image_mcl MovieClipLoader new MovieClipLoader var mclListener Object new Object mclListener onLoadInit function target_mc MovieClip trace target_mc _name target_mc _width X target_mc _height pixels image_mcl addListener mclListener image_mcl loadClip http www macromedia com devnet mx blueprint articles nielsen ...

Страница 533: ...es on the new hit area behavior The movie clip designated as the hit area does not need to be visible its graphical shape although not visible is hit tested The hitArea property can be read out of a prototype object Example The following example sets the circle_mc movie clip as the hit area for the square_mc movie clip Place these two movie clips on the Stage and test the document When you click c...

Страница 534: ...e specified hit area false otherwise Description Method evaluates the instance specified by my_mc to see if it overlaps or intersects with the hit area identified by the target or x and y coordinate parameters Usage 1 Compares the x and y coordinates to the shape or bounding box of the specified instance according to the shapeFlag setting If shapeFlag is set to true only the area actually occupied...

Страница 535: ...MovieClip hitTest 535 See also MovieClip getBounds MovieClip globalToLocal MovieClip localToGlobal ...

Страница 536: ...e value is less than 0 Flash uses 0 if the value is greater than 100 Flash uses 100 Returns Nothing Description Method specifies a line style that Flash uses for subsequent calls to lineTo and curveTo until you call lineStyle with different parameters You can call lineStyle in the middle of drawing a path to specify different styles for different line segments within a path Note Calls to clear wil...

Страница 537: ... call lineTo before any calls to the moveTo method the current drawing position defaults to 0 0 If any of the parameters are missing this method fails and the current drawing position is not changed You can extend the methods and event handlers of the MovieClip class by creating a subclass For more information see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The ...

Страница 538: ...le the original SWF file is playing Tip If you want to monitor the progress of the download use MovieClipLoader loadClip instead of this function Without the loadMovie method Flash Player displays a single SWF file and then closes The loadMovie method lets you display several SWF files at once and switch between SWF files without loading another HTML document A SWF file or image loaded into a movi...

Страница 539: ...ge picture jpg into a movie clip and use the MovieClip onPress method to make the image act like a button Loading a JPEG using loadMovie replaces the movie clip with the image but doesn t give you access to movie clip methods To get access to movie clip methods you must create an empty parent movie clip and a container child movie clip Load the image into the container and place the event handler ...

Страница 540: ... of variables This method can also be used to update variables in the active movie clip with new values This method requires that the text of the URL be in the standard MIME format application x www form urlencoded CGI script format In SWF files running in a version earlier than Flash Player 7 url must be in the same superdomain as the SWF file that is issuing this call A superdomain is derived by...

Страница 541: ...d to check the loading progress The script checks for a variable in the params txt file named done this createEmptyMovieClip target_mc this getNextHighestDepth target_mc loadVariables params txt function checkParamsLoaded if target_mc done undefined trace not yet else trace finished loading killing interval trace for i in target_mc trace i target_mc i trace clearInterval param_interval var param_i...

Страница 542: ...rmation see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The following example converts x and y coordinates of the my_mc object from the movie clip s local coordinates to the Stage global coordinates The center point of the movie clip is reflected after you click and drag the instance this createTextField point_txt this getNextHighestDepth 0 0 100 22 var mouseLis...

Страница 543: ... swf from someone else s site into chess_mc you can set its _lockroot property when you load it as shown below In this case Chess swf can be published for any version of Flash Player as long as Games swf is published for Flash Player 7 or later Place the following ActionScript on the main Timeline chess_mc _lockroot true When calling loadMovie set the MovieClip _lockroot property to true in the lo...

Страница 544: ...root swf this createEmptyMovieClip nolockroot_mc this getNextHighestDepth nolockroot_mc loadMovie nolockroot swf function dumpRoot trace from current SWF file for i in _root trace i _root i trace dumpRoot which traces the following information from current SWF file dumpRoot type Function version WIN 7 0 19 0 nolockroot_mc _level0 nolockroot_mc lockroot_mc _level0 lockroot_mc from nolockroot swf my...

Страница 545: ...rent SWF file dumpRoot type Function version WIN 7 0 19 0 nolockroot_mc _level0 nolockroot_mc lockroot_mc _level0 lockroot_mc from nolockroot swf myOtherVar 2 myVar 1 from lockroot swf myOtherVar 2 myVar 1 See also MovieClip attachMovie MovieClip loadMovie MovieClipLoader onLoadInit _root and About loading components in Using Components ...

Страница 546: ...mage in Browser that has an associated function named viewImage var menu_cm ContextMenu new ContextMenu menu_cm customItems push new ContextMenuItem View Image in Browser viewImage this createEmptyMovieClip image_mc this getNextHighestDepth var mclListener Object new Object mclListener onLoadInit function target_mc MovieClip target_mc menu menu_cm var image_mcl MovieClipLoader new MovieClipLoader ...

Страница 547: ...d the current drawing position is not changed You can extend the methods and event handlers of the MovieClip class by creating a subclass For more information see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The following example draws a triangle with a 5 pixel solid magenta line and a partially transparent blue fill this createEmptyMovieClip triangle_mc 1 triang...

Страница 548: ... context menu to view information about that instance Add several movie clips with instance names and then add the following ActionScript to your AS or FLA file var menu_cm ContextMenu new ContextMenu menu_cm customItems push new ContextMenuItem Info getMCInfo function getMCInfo target_mc MovieClip obj Object trace You clicked on the movie clip target_mc _name trace t width target_mc _width height...

Страница 549: ...a subclass For more information see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The following example loads content into a SWF file using _framesloaded and nextFrame Do not add any code to Frame 1 but add the following ActionScript to Frame 2 of the Timeline if this _framesloaded 3 this nextFrame else this gotoAndPlay 1 Then add the following code and the conten...

Страница 550: ...be invoked when a specific movie clip receives data you must use onClipEvent instead of this handler The latter handler is invoked when any movie clip receives data Example The following example illustrates the correct use of MovieClip onData and onClipEvent data symbol_mc is a movie clip symbol in the library It is linked to the MovieClip class The following function is triggered for each instanc...

Страница 551: ...ovieClip onData 551 Therefore this function is invoked when symbol_mc is instantiated and also when replacement swf is loaded OnClipEvent data trace The movie clip has received data See also onClipEvent ...

Страница 552: ...define a function that executes when the event handler is invoked You can define the function on the Timeline or in a class file that extends the MovieClip class or is linked to a symbol in the library For more information see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The following example defines a function for the onDragOut method that sends a trace action t...

Страница 553: ...on that executes when the event handler is invoked You can define the function on the Timeline or in a class file that extends the MovieClip class or is linked to a symbol in the library For more information see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The following example defines a function for the onDragOver method that sends a trace action to the Output p...

Страница 554: ...frame actions that are attached to the affected frames You must define a function that executes when the event handler is invoked You can define the function on the Timeline or in a class file that extends the MovieClip class or is linked to a symbol in the library For more information see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The following example defines...

Страница 555: ...ent handler works only if the movie clip has input focus enabled and set First the MovieClip focusEnabled property must be set to true for the movie clip Then the clip must be given focus This can be done either by using Selection setFocus or by setting the Tab key to navigate to the clip If Selection setFocus is used the path for the movie clip must be passed to Selection setFocus It is very easy...

Страница 556: ...ou tab to the movie clip and press a key key was pressed displays in the Output panel However this does not occur after you move the mouse because the movie clip loses focus Therefore you should use Key onKeyDown in most cases See also MovieClip onKeyUp ...

Страница 557: ... movie clip symbol in Using ActionScript in Flash The onKeyUp event handler works only if the movie clip has input focus enabled and set First the MovieClip focusEnabled property must be set to true for the movie clip Then the clip must be given focus This can be done either by using Selection setFocus or by setting the Tab key to navigate to the clip If Selection setFocus is used the path for the...

Страница 558: ... when the event handler is invoked You can define the function on the Timeline or in a class file that extends the MovieClip class or is linked to a symbol in the library For more information see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The following example displays writes information about the movie clip that loses focus and the instance that currently has ...

Страница 559: ...ted with a class If you want an event handler to be invoked when a specific movie clip loads for example when you use MovieClip loadMovie to load a SWF file dynamically you must use onClipEvent load instead of this handler The latter handler is invoked when any movie clip loads Example The following example illustrates one way to use MovieClip onLoad with setInterval to check that a file has loade...

Страница 560: ...s createEmptyMovieClip tester_mc 1 var mclListener Object new Object mclListener onLoadInit function target_mc MovieClip trace movie loaded var image_mcl MovieClipLoader new MovieClipLoader image_mcl addListener mclListener image_mcl loadClip http www yourserver com your_movie swf tester_mc See also onClipEvent MovieClipLoader class ...

Страница 561: ...n that executes when the event handler is invoked You can define the function on the Timeline or in a class file that extends the MovieClip class or is linked to a symbol in the library For more information see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The following example defines a function for the onMouseDown method that sends a trace action to the Output p...

Страница 562: ...ction that executes when the event handler is invoked You can define the function on the Timeline or in a class file that extends the MovieClip class or is linked to a symbol in the library For more information see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The following example defines a function for the onMouseMove method that sends a trace action to the Outp...

Страница 563: ...n that executes when the event handler is invoked You can define the function on the Timeline or in a class file that extends the MovieClip class or is linked to a symbol in the library For more information see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The following example defines a function for the onMouseUp method that sends a trace action to the Output pan...

Страница 564: ...clip You must define a function that executes when the event handler is invoked You can define the function on the Timeline or in a class file that extends the MovieClip class or is linked to a symbol in the library For more information see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The following example defines a function for the onPress method that sends a tr...

Страница 565: ...function that executes when the event handler is invoked You can define the function on the Timeline or in a class file that extends the MovieClip class or is linked to a symbol in the library For more information see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The following example defines a function for the onPress method that sends a trace action to the Outpu...

Страница 566: ...e the movie clip area You must define a function that executes when the event handler is invoked You can define the function on the Timeline or in a class file that extends the MovieClip class or is linked to a symbol in the library For more information see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The following example defines a function for the onReleaseOuts...

Страница 567: ... function that executes when the event handler is invoked You can define the function on the Timeline or in a class file that extends the MovieClip class or is linked to a symbol in the library For more information see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The following example defines a function for the onRollOut method that sends a trace action to the Ou...

Страница 568: ...ust define a function that executes when the event handler is invoked You can define the function on the Timeline or in a class file that extends the MovieClip class or is linked to a symbol in the library For more information see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The following example defines a function for the onRollOver method that sends a trace to ...

Страница 569: ...at executes when the event handler in invoked You can define the function on the Timeline or in a class file that extends the MovieClip class or is linked to a symbol in the library For more information see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The following example displays information about the movie clip that receives keyboard focus and the instance tha...

Страница 570: ... handler before attaching any actions to the affected frame You must define a function that executes when the event handler is invoked You can define the function on the Timeline or in a class file that extends the MovieClip class or is linked to a symbol in the library For more information see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The following example de...

Страница 571: ...ove up multiple levels in the display list as in the following this _parent _parent _alpha 20 Example The following example traces the reference to a movie clip and its relationship to the main Timeline Create a movie clip with the instance name my_mc and add it to the main Timeline Add the following ActionScript to your FLA or AS file my_mc onRelease function trace You clicked the movie clip this...

Страница 572: ...ovie clip symbol in Using ActionScript in Flash Example Use the following ActionScript to play the main Timeline of a SWF file This ActionScript is for a movie clip button called my_mc on the main Timeline stop my_mc onRelease function this _parent play Use the following ActionScript to play the Timeline of a movie clip in a SWF file This ActionScript is for a button called my_btn on the main Time...

Страница 573: ... two movie clip buttons control the Timeline The prev_mc button moves the playhead to the previous frame and the next_mc button moves the playhead to the next frame Add content to a series of frames on the Timeline and add the following ActionScript to Frame 1 of the Timeline stop prev_mc onRelease function var parent_mc MovieClip this _parent if parent_mc _currentframe 1 parent_mc prevFrame else ...

Страница 574: ... using a 2 x 2 pixel grid but bitmaps are not smoothed This is suitable for movies that do not contain text HIGH High rendering quality Graphics are anti aliased using a 4 x 4 pixel grid and bitmaps are smoothed if the movie is static This is the default rendering quality setting used by Flash BEST Very high rendering quality Graphics are anti aliased using a 4 x 4 pixel grid and bitmaps are alway...

Страница 575: ...ss to a movie clip symbol in Using ActionScript in Flash Example Each time you click a button in the following example you attach a movie clip instance to the Stage in a random position When you click a movie clip instance you remove that instance from the SWF file function randRange min Number max Number Number var randNum Number Math round Math random max min min return randNum var bugNum Number...

Страница 576: ...se rotation Values outside this range are added to or subtracted from 360 to obtain a value within the range For example the statement my_mc _rotation 450 is the same as my_mc _rotation 90 Example The following example creates a movie clip instance dynamically rotates and loads an image into the instance this createEmptyMovieClip image_mc 1 image_mc _rotation 15 image_mc loadMovie http www macrome...

Страница 577: ...xample my_mc setMask my_mc If you create a mask layer that contains a movie clip and then apply the setMask method to it the setMask call takes priority and this is not reversible For example you could have a movie clip in a mask layer called UIMask that masks another layer containing another movie clip called UIMaskee If as the SWF file plays you call UIMask setMask UIMaskee from that point on UI...

Страница 578: ...r Description Property global an integer that specifies the number of seconds a sound prebuffers before it starts to stream Note Although you can specify this property for a MovieClip object it is actually a global property and you can specify its value simply as _soundbuftime For more information and an example see _soundbuftime ...

Страница 579: ... to MovieClip stopDrag or until another movie clip is made draggable Only one movie clip is draggable at a time You can extend the methods and event handlers of the MovieClip class by creating a subclass For more information see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The following example creates a draggable movie clip instance called image_mc A MovieClipLo...

Страница 580: ...iption Method stops the movie clip currently playing You can extend the methods and event handlers of the MovieClip class by creating a subclass For more information see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The following example shows how to stop a movie clip named aMovieClip aMovieClip stop See also stop ...

Страница 581: ...see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The following example creates a draggable movie clip instance called image_mc A MovieClipLoader object is used to load an image into image_mc this createEmptyMovieClip image_mc 1 var mclListener Object new Object mclListener onLoadInit function target_mc MovieClip target_mc onPress function this startDrag target_mc...

Страница 582: ...parent movie clip Swapping the depth level of movie clips has the effect of moving one movie clip in front of or behind the other If a movie clip is tweening when this method is called the tweening is stopped For more information see Managing movie clip depths in Using ActionScript in Flash You can extend the methods and event handlers of the MovieClip class by creating a subclass For more informa...

Страница 583: ... be excluded from tab ordering To do this the tabChildren property of the list box should be set to false The tabChildren property has no effect if the tabIndex property is used the tabChildren property affects only automatic tab ordering The following example disables tabbing for all children movie clips inside a parent movie clip called menu_mc menu_mc onRelease function menu_mc menu1_mc onRelea...

Страница 584: ...ering If the tabIndex property is also set to a value the object is included in custom tab ordering as well If tabEnabled is false the object is not included in automatic or custom tab ordering even if the tabIndex property is set However if MovieClip tabChildren is true the movie clip s children can still be included in automatic tab ordering even if tabEnabled is false Example The following exam...

Страница 585: ... properties The tabIndex property must be a positive integer The objects are ordered according to their tabIndex properties in ascending order An object with a tabIndex value of 1 precedes an object with a tabIndex value of 2 The custom tab ordering disregards the hierarchical relationships of objects in a SWF file All objects in the SWF file with tabIndex properties are placed in the tab order Yo...

Страница 586: ...f the movie clip instance specified by my_mc in slash notation Use the eval function to convert the target path to dot notation Example The following example displays the target paths of movie clip instances in a SWF file in both slash and dot notation for var i in this if typeof this i movieclip trace name this i _name t target this i _target t target 2 eval this i _target ...

Страница 587: ...es the playhead to the previous frame and the next_mc button moves the playhead to the next frame Add content to a series of frames on the Timeline and add the following ActionScript to Frame 1 of the Timeline stop prev_mc onRelease function var parent_mc MovieClip this _parent if parent_mc _currentframe 1 parent_mc prevFrame else parent_mc gotoAndStop parent_mc _totalframes next_mc onRelease func...

Страница 588: ...st the default behavior is false You can change the trackAsMenu property at any time the modified movie clip immediately takes on the new behavior Example The following example sets the trackAsMenu property for three movie clips on the Stage Click a movie clip and release the mouse button on a second movie clip to see which instance receives the event myMC1_mc trackAsMenu true myMC2_mc trackAsMenu...

Страница 589: ...the methods and event handlers of the MovieClip class by creating a subclass For more information see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The following example unloads a movie clip instance called image_mc when a user clicks the unloadMC_btn instance this createEmptyMovieClip image_mc 1 image_mc loadMovie http www macromedia com images shared product_box...

Страница 590: ...112x112 jpg image_mc The following example assigns the ContextMenu object menu_cm to the movie clip image_mc The ContextMenu object contains a custom menu item labeled View Image in Browser that has an associated function named viewImage var menu_cm ContextMenu new ContextMenu menu_cm customItems push new ContextMenuItem View Image in Browser viewImage this createEmptyMovieClip image_mc this getNe...

Страница 591: ...ip If useHandCursor is false the arrow pointer is used instead You can change the useHandCursor property at any time the modified movie clip immediately takes on the new cursor behavior The useHandCursor property can be read out of a prototype object Example The following example sets the useHandCursor property for two movie clips called myMC1_mc and myMC2_mc The property is set to true for one in...

Страница 592: ...ton in a movie clip with _visible set to false cannot be clicked Example The following example sets the _visible property for two movie clips called myMC1_mc and myMC2_mc The property is set to true for one instance and false for the other Notice that myMC1_mc instance cannot be clicked after the _visible property is set to false myMC1_mc onRelease function trace this _name _visible false this _vi...

Страница 593: ...p in the Output panel this createEmptyMovieClip image_mc this getNextHighestDepth var image_mcl MovieClipLoader new MovieClipLoader var mclListener Object new Object mclListener onLoadInit function target_mc MovieClip trace target_mc _name target_mc _width X target_mc _height pixels image_mcl addListener mclListener image_mcl loadClip http www macromedia com devnet mx blueprint articles nielsen sp...

Страница 594: ...ip s children inherit a coordinate system that is rotated 90º counterclockwise The movie clip s coordinates refer to the registration point position Example The following example attaches a movie clip with the linkage identifier cursor_id to a SWF file The movie clip is called cursor_mc and it is used to replace the default mouse pointer The following ActionScript sets the current coordinates of t...

Страница 595: ...ion to a movie clip on the Stage called my_mc this createTextField mouse_txt this getNextHighestDepth 0 0 150 66 mouse_txt html true mouse_txt multiline true var row1_str String nbsp t b _xmouse t b b _ymouse b my_mc onMouseMove function mouse_txt htmlText textformat tabStops 50 100 mouse_txt htmlText row1_str mouse_txt htmlText b _level0 b t _xmouse t _ymouse mouse_txt htmlText b my_mc b t this _...

Страница 596: ...vie were set at 100 Example The following example creates a movie clip at runtime called box_mc The Drawing API is used to draw a box in this instance and when the mouse rolls over the box horizontal and vertical scaling is applied to the movie clip When the mouse rolls off the instance it returns to the previous scaling this createEmptyMovieClip box_mc 1 box_mc _x 100 box_mc _y 100 with box_mc li...

Страница 597: ...a coordinate system that is rotated 90º counterclockwise The movie clip s coordinates refer to the registration point position Example The following example attaches a movie clip with the linkage identifier cursor_id to a SWF file The movie clip is called cursor_mc and it is used to replace the default mouse pointer The following ActionScript sets the current coordinates of the movie clip instance...

Страница 598: ... and in relation to a movie clip on the Stage called my_mc this createTextField mouse_txt this getNextHighestDepth 0 0 150 66 mouse_txt html true mouse_txt multiline true var row1_str String nbsp t b _xmouse t b b _ymouse b my_mc onMouseMove function mouse_txt htmlText textformat tabStops 50 100 mouse_txt htmlText row1_str mouse_txt htmlText b _level0 b t _xmouse t _ymouse mouse_txt htmlText b my_...

Страница 599: ...0 Example The following example creates a movie clip at runtime called box_mc The Drawing API is used to draw a box in this instance and when the mouse rolls over the box horizontal and vertical scaling is applied to the movie clip When the mouse rolls off the instance it returns to the previous scaling this createEmptyMovieClip box_mc 1 box_mc _x 100 box_mc _y 100 with box_mc lineStyle 1 0xCCCCCC...

Страница 600: ...r onLoadComplete listener is invoked After the downloaded file s first frame actions have been executed the MovieClipLoader onLoadInit listener is invoked After MovieClipLoader onLoadInit has been invoked you can set properties use methods and otherwise interact with the loaded movie If the file fails to load completely the MovieClipLoader onLoadError listener is invoked Method summary for the Mov...

Страница 601: ...ClipLoader loadClip See also MovieClipLoader addListener Listener Description MovieClipLoader onLoadComplete Invoked when a file loaded with MovieClipLoader loadClip has completely downloaded MovieClipLoader onLoadError Invoked when a file loaded with MovieClipLoader loadClip has failed to load MovieClipLoader onLoadInit Invoked when the actions on the first frame of the loaded clip have been exec...

Страница 602: ...eEmptyMovieClip image_mc this getNextHighestDepth var mclListener Object new Object mclListener onLoadInit function target_mc MovieClip target_mc _x Stage width 2 target_mc _width 2 target_mc _y Stage height 2 target_mc _width 2 var w Number target_mc _width var h Number target_mc _height target_mc lineStyle 4 0x000000 target_mc moveTo 0 0 target_mc lineTo w 0 target_mc lineTo w h target_mc lineTo...

Страница 603: ...ble dynamically created movie clip called image_mc The number of bytes loaded and the total number of bytes for the loaded image display in a dynamically created text field called filesize_txt this createEmptyMovieClip image_mc this getNextHighestDepth var mclListener Object new Object mclListener onLoadInit function target_mc MovieClip target_mc onPress function this startDrag target_mc onRelease...

Страница 604: ...vantages The following handlers are implemented by the use on a listener object which is registered with the MovieClipLoader class using MovieClipLoader addListener listenerObject The MovieClipLoader onLoadStart handler is invoked when loading begins The MovieClipLoader onLoadError handler is invoked if the clip cannot be loaded The MovieClipLoader onLoadProgress handler is invoked as the loading ...

Страница 605: ...ner onLoadProgress function target_mc MovieClip loadedBytes Number totalBytes Number trace First my_mcl instance Progress trace onLoadProgress called back on movie clip target_mc trace loadedBytes bytes loaded at progress callback trace totalBytes bytes total at progress callback myListener onLoadComplete function target_mc MovieClip trace First my_mcl instance trace Your load is done on movie cli...

Страница 606: ...2 onLoadComplete function target_mc MovieClip trace Second my_mcl instance trace Your load is done on movie clip target_mc var loadProgress Object my_mcl getProgress target_mc trace loadProgress bytesLoaded bytes loaded at end trace loadProgress bytesTotal bytes total at end myListener2 onLoadError function target_mc MovieClip errorCode String trace Second my_mcl instance trace ERROR CODE errorCod...

Страница 607: ... the way they work with your SWF file The onLoadComplete event is called after the SWF or JPEG file has loaded but before the application has been initialized At this point it is impossible to access the loaded movie clip s methods and properties and because of this you cannot call a function move to a specific frame and so on In most situations it s better to use the onLoadInit event instead whic...

Страница 608: ..._width 22 target_mc timer_txt text loaded in timerMS ms var image_mcl MovieClipLoader new MovieClipLoader image_mcl addListener mclListener image_mcl loadClip http www macromedia com images shared product_boxes 112x112 box_studio_112x112 jpg image_mc See also MovieClipLoader addListener MovieClipLoader onLoadStart MovieClipLoader onLoadError ...

Страница 609: ... MovieClipLoader onLoadStart was called but MovieClipLoader onLoadComplete was not called For example if MovieClipLoader onLoadStart is called but the download is interrupted due to server overload server crash and so on MovieClipLoader onLoadComplete will not be called The value for target_mc identifies the movie clip this call is being made for This is useful if you are loading multiple files wi...

Страница 610: ...it function target_mc MovieClip trace success trace image_mcl getProgress target_mc bytesTotal bytes loaded var image_mcl MovieClipLoader new MovieClipLoader image_mcl addListener mclListener image_mcl loadClip http www fakedomain com images bad_hair_day jpg image_mc ...

Страница 611: ...ur ActionScript Example The following example loads an image into a movie clip instance called image_mc The onLoadInit and onLoadComplete events are used to determine how long it takes to load the image This information displays in a text field called timer_txt this createEmptyMovieClip image_mc this getNextHighestDepth var mclListener Object new Object mclListener onLoadStart function target_mc M...

Страница 612: ...612 Chapter 2 ActionScript Language Reference See also MovieClipLoader onLoadStart ...

Страница 613: ...tes parameters The value for target_mc identifies the movie clip this call is being made for This is useful if you are loading multiple files with the same set of listeners This optional parameter is passed to your ActionScript Example The following example creates a progress bar using the Drawing API The progress bar displays the loading progress of an image using the onLoadProgress listener When...

Страница 614: ...lListener onLoadProgress function target_mc MovieClip bytesLoaded Number bytesTotal Number progressBar_mc bar_mc _xscale Math round bytesLoaded bytesTotal 100 mclListener onLoadComplete function target_mc MovieClip progressBar_mc removeMovieClip mclListener onLoadInit function target_mc MovieClip target_mc _height 320 target_mc _width 240 this createEmptyMovieClip image_mc 100 var image_mcl MovieC...

Страница 615: ...image into a movie clip instance called image_mc The onLoadInit and onLoadComplete events are used to determine how long it takes to load the image This information displays in a text field called timer_txt this createEmptyMovieClip image_mc this getNextHighestDepth var mclListener Object new Object mclListener onLoadStart function target_mc MovieClip target_mc startTimer getTimer mclListener onLo...

Страница 616: ...616 Chapter 2 ActionScript Language Reference See also MovieClipLoader onLoadError MovieClipLoader onLoadInit MovieClipLoader onLoadComplete ...

Страница 617: ...ogress information is displayed in the Output panel this createEmptyMovieClip image_mc this getNextHighestDepth var mclListener Object new Object mclListener onLoadStart function target_mc MovieClip trace t onLoadStart mclListener onLoadComplete function target_mc MovieClip trace t onLoadComplete mclListener onLoadError function target_mc MovieClip errorCode String trace t onLoadError errorCode mc...

Страница 618: ...618 Chapter 2 ActionScript Language Reference start_button enabled true stop_button enabled false image_mcl removeListener mclListener stop_button enabled false ...

Страница 619: ... into a movie clip called image_mc If you click the movie clip the movie clip is removed and information is displayed in the Output panel this createEmptyMovieClip image_mc this getNextHighestDepth var mclListener Object new Object mclListener onLoadInit function target_mc MovieClip target_mc _x 100 target_mc _y 100 target_mc onRelease function trace Unloading clip trace t name target_mc _name tra...

Страница 620: ...nce NaN Availability Flash Player 5 Usage NaN Description Variable a predefined variable with the IEEE 754 value for NaN not a number To determine if a number is NaN use isNaN See also isNaN Number NaN CHAPTER 2 ActionScript Language Reference ...

Страница 621: ...lability Flash Player 5 Usage Infinity Description Constant specifies the IEEE 754 value representing negative infinity The value of this constant is the same as Number NEGATIVE_INFINITY CHAPTER 2 ActionScript Language Reference ...

Страница 622: ...unication Server documentation Usage new NetConnection NetConnection Parameters None Returns A reference to a NetConnection object Description Constructor creates a NetConnection object that you can use in conjunction with a NetStream object to play back local streaming video FLV files After creating the NetConnection object use NetConnection connect to make the actual connection Playing external ...

Страница 623: ...NetConnection class 623 See also NetStream class Video attachVideo ...

Страница 624: ...tion Constructor opens a local connection through which you can play back video FLV files from an HTTP address or from the local file system Example The following example opens a connection to play the video2 flv file Select New Video from the Library panel s options menu to create a new video object and give it the instance name my_video var connection_nc NetConnection new NetConnection connectio...

Страница 625: ...cript in Flash Method summary for the NetStream class The following methods and properties of the NetConnection and NetStream classes are used to control FLV playback Property summary for the NetStream class Method Purpose NetStream close Closes the stream but does not clear the video object NetStream pause Pauses or resumes playback of a stream NetStream play Begins playback of an external video ...

Страница 626: ...gh the specified NetConnection object Example The following code first constructs a new NetConnection object connection_nc and uses it to construct a new NetStream object called stream_ns Select New Video from the Library options menu to create a video object instance and give it an instance name my_video Then add the following ActionScript to your FLA or AS file var connection_nc NetConnection ne...

Страница 627: ...mber of seconds that are currently in the buffer The text field also displays the buffer length that the video is set to and percentage of buffer that is filled this createTextField buffer_txt this getNextHighestDepth 10 10 300 22 buffer_txt html true var connection_nc NetConnection new NetConnection connection_nc connect null var stream_ns NetStream new NetStream connection_nc stream_ns setBuffer...

Страница 628: ...are currently in the buffer The text field also displays the buffer length that the video is set to and percentage of buffer that is filled this createTextField buffer_txt this getNextHighestDepth 10 10 300 22 buffer_txt html true var connection_nc NetConnection new NetConnection connection_nc connect null var stream_ns NetStream new NetStream connection_nc stream_ns setBufferTime 3 my_video attac...

Страница 629: ...o A text field called loaded_txt is dynamically created to display information about the loading progress as well 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 video1 flv this createTextField loaded_txt this getNextHighestDepth 10 10 160 22 this createEmptyMovieClip prog...

Страница 630: ...heckBytesLoaded my_ns NetStream var pctLoaded Number Math round my_ns bytesLoaded my_ns bytesTotal 100 loaded_txt text Math round my_ns bytesLoaded 1000 of Math round my_ns bytesTotal 1000 KB loaded pctLoaded progressBar_mc bar_mc _xscale pctLoaded if pctLoaded 100 clearInterval loaded_interval See also NetStream bufferLength ...

Страница 631: ...am_ns NetStream new NetStream connection_nc my_video attachVideo stream_ns stream_ns play video1 flv this createTextField loaded_txt this getNextHighestDepth 10 10 160 22 this createEmptyMovieClip progressBar_mc this getNextHighestDepth progressBar_mc createEmptyMovieClip bar_mc progressBar_mc getNextHighestDepth with progressBar_mc bar_mc beginFill 0xFF0000 moveTo 0 0 lineTo 100 0 lineTo 100 10 l...

Страница 632: ...e loaded_txt text Math round my_ns bytesLoaded 1000 of Math round my_ns bytesTotal 1000 KB loaded pctLoaded progressBar_mc bar_mc _xscale pctLoaded if pctLoaded 100 clearInterval loaded_interval See also NetStream bytesLoaded NetStream bufferTime ...

Страница 633: ...akes the stream available for another use This command also deletes the local copy of an FLV file that was downloaded using HTTP Example The following onDisconnect function closes a connection and deletes the temporary copy of video1 flv that was stored on the local disk when you click the button called close_btn var connection_nc NetConnection new NetConnection connection_nc connect null var stre...

Страница 634: ...lue during testing to help you determine how much compression to apply when exporting the file Example The following example creates a text field that displays the current number of frames per second that video1 flv displays 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 ...

Страница 635: ...hat is either status or error In addition to this onStatus handler Flash also provides a super function called System onStatus If onStatus is invoked for a particular object and there is no function assigned to respond to it Flash processes a function assigned to System onStatus if it exists The following events notify you when certain NetStream activities occur If you consistently see errors rega...

Страница 636: ...n new NetConnection connection_nc connect null var stream_ns NetStream new NetStream connection_nc my_video attachVideo stream_ns stream_ns play video1 flv stream_ns onStatus function infoObject Object trace NetStream onStatus called getTimer ms for var prop in infoObject trace t prop t infoObject prop trace See also System onStatus NetStream setBufferTime ...

Страница 637: ...it is called on a specified stream it pauses play and the next time it is called it resumes play This parameter is optional Returns Nothing Description Method pauses or resumes playback of a stream The first time you call this method without sending a parameter it pauses play the next time it resumes play You might want to attach this method to a button that the user presses to pause or resume pla...

Страница 638: ...ject to control some aspects of the audio For more information see MovieClip attachAudio If the FLV file can t be found the NetStream onStatus event handler is invoked If you want to stop a stream that is currently playing use NetStream close You can play local FLV files that are stored in the same directory as the SWF file or in a subdirectory you can t navigate to a higher level directory For ex...

Страница 639: ...NetStream play 639 See also MovieClip attachAudio NetStream close NetStream pause Video attachVideo ...

Страница 640: ...ime n to seek n seconds forward or backward respectively from the current position For example to rewind 20 seconds from the current position use my_ns seek my_ns time 20 The precise location to which a video seeks will differ depending on the frames per second setting at which it was exported Therefore if the same video is exported at 6 fps and 30 fps it will seek to two different locations if yo...

Страница 641: ...OfSeconds The number of seconds of data to be buffered before Flash begins displaying data The default value is 0 1 one tenth of a second Description Method specifies how long to buffer messages before starting to display the stream For example if you want to make sure that the first 15 seconds of the stream play without interruption set numberOfSeconds to 15 Flash begins playing the stream only a...

Страница 642: ...e it an instance name my_video Add the following ActionScript to your FLA or AS file 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 video1 flv stream_ns onStatus function infoObject Object statusCode_txt text infoObject code this createTextField time_txt this getNextHighe...

Страница 643: ...entheses as well as the newly created object which is referenced using the keyword this The constructor function can use this to set the variables of the object Example The following example creates the Book function and then uses the new operator to create the objects book1 and book2 function Book name String price Number this name name this price price var book1 new Book Confederacy of Dunces 19...

Страница 644: ...ank line in text output generated by your code Use newline to make space for information that is retrieved by a function or statement in your code Example The following example shows how newline displays output from the trace statement on multiple lines var myName String Lisa myAge Number 30 trace myName myAge trace trace myName newline myAge output Lisa30 Lisa 30 CHAPTER 2 ActionScript Language R...

Страница 645: ... arrow key the playhead goes to the previous frame and stops The listener is initialized to wait for the arrow key to be pressed and the init variable is used to prevent the listener from being redefined if the playhead returns to Frame 1 stop if init undefined someListener new Object someListener onKeyDown function if Key isDown Key LEFT Key isDown Key UP _level0 prevFrame else if Key isDown Key ...

Страница 646: ...ighestDepth nextscene_mc createTextField nextscene_txt this getNextHighestDepth 200 0 100 22 nextscene_mc nextscene_txt autoSize true nextscene_mc nextscene_txt border true nextscene_mc nextscene_txt text Next Scene this createEmptyMovieClip prevscene_mc this getNextHighestDepth prevscene_mc createTextField prevscene_txt this getNextHighestDepth 00 0 100 22 prevscene_mc prevscene_txt autoSize true...

Страница 647: ...ta was provided You can use null to represent values that are missing or that do not have a defined data type Example In a numeric context null evaluates to 0 Equality tests can be performed with null In this statement a binary tree node has no left child so the field for its left child could be set to null if tree left null tree left new TreeNode CHAPTER 2 ActionScript Language Reference ...

Страница 648: ...alue is NaN If expression is undefined the return value is as follows In files published for Flash Player 6 or earlier the result is 0 In files published for Flash Player 7 or later the result is NaN This function is used to convert Flash 4 files containing deprecated operators that are imported into the Flash 5 or later authoring environment For more information see bitwise AND Example In the fol...

Страница 649: ...Number 649 See also NaN Number class ...

Страница 650: ...ber Number new Number 1234 myNumber toString The following example assigns the value of the MIN_VALUE property to a variable declared without the use of the constructor var smallest Number Number MIN_VALUE Method summary for the Number class Property summary for the Number class The properties in the following table are constants Method Description Number toString Returns the string representation...

Страница 651: ...bject Description Constructor creates a new Number object You must use the Number constructor when using Number toString and Number valueOf You do not use a constructor when using the properties of a Number object The new Number constructor is primarily used as a placeholder A Number object is not the same as the Number function that converts a parameter to a primitive value Example The following ...

Страница 652: ...r double precision IEEE 754 This number is approximately 1 79e 308 Example The following ActionScript displays the largest and smallest representable numbers to the Output panel trace Number MIN_VALUE Number MIN_VALUE trace Number MAX_VALUE Number MAX_VALUE This code displays the following values Number MIN_VALUE 4 94065645841247e 324 Number MAX_VALUE 1 79769313486232e 308 ...

Страница 653: ...sion IEEE 754 This number is approximately 5e 324 Example The following ActionScript displays the largest and smallest representable numbers to the Output panel trace Number MIN_VALUE Number MIN_VALUE trace Number MAX_VALUE Number MAX_VALUE This code displays the following values Number MIN_VALUE 4 94065645841247e 324 Number MAX_VALUE 1 79769313486232e 308 ...

Страница 654: ...654 Chapter 2 ActionScript Language Reference Number NaN Availability Flash Player 5 Usage Number NaN Description Property the IEEE 754 value representing Not A Number NaN See also isNaN NaN ...

Страница 655: ...y Negative infinity is a special numeric value that is returned when a mathematical operation or function returns a negative value larger than can be represented Example This example compares the result of dividing the following values var posResult Number 1 0 if posResult Number POSITIVE_INFINITY trace posResult posResult output posResult Infinity var negResult Number 1 0 if negResult Number NEGA...

Страница 656: ...stant Infinity Positive infinity is a special numeric value that is returned when a mathematical operation or function returns a value larger than can be represented Example This example compares the result of dividing the following values var posResult Number 1 0 if posResult Number POSITIVE_INFINITY trace posResult posResult output posResult Infinity var negResult Number 1 0 if negResult Number ...

Страница 657: ...tation of the specified Number object myNumber Example The following example uses 2 and 8 for the radix parameter and returns a string that contains the corresponding representation of the number 9 var myNumber Number new Number 9 trace myNumber toString 2 output 1001 trace myNumber toString 8 output 11 The following example results in a hexadecimal value var r Number new Number 250 var g Number n...

Страница 658: ... 5 Usage myNumber valueOf Number Parameters None Returns Number Description Method returns the primitive value type of the specified Number object Example The following example results in the primative value of the numSocks object var numSocks new Number 2 trace numSocks valueOf output 2 ...

Страница 659: ...ommand is equivalent to creating an object using the Object constructor see Constructor for the Object class on page 660 Example In the following example a new empty object is created and then the object is populated with values var company Object new Object company name Macromedia Inc company address 600 Townsend Street company city San Francisco company state CA company postal 94103 for var i in...

Страница 660: ...s This parameter is optional Method Description Object addProperty Creates a getter setter property on an object Object registerClass Associates a movie clip symbol with an ActionScript object class Object toString Converts the specified object to a string and returns it Object unwatch Removes the watchpoint that Object watch created Object valueOf Returns the primitive value of an object Object w...

Страница 661: ...object Description Constructor creates an Object object and stores a reference to the object s constructor method in the object s constructor property Example The following example creates a generic object named myObject var myObject Object new Object ...

Страница 662: ...is a function with no parameters Its return value can be of any type Its type can change between invocations The return value is treated as the current value of the property A set function is a function that takes one parameter which is the new value of the property For example if property x is assigned by the statement x 1 the set function is passed the parameter 1 of type number The return value...

Страница 663: ...es of Catcher in the Rye The previous example works but the properties bookcount and bookname are added to every instance of the Book object which requires having two properties for every instance of the object If there are many properties such as bookcount and bookname in a class they could consume a great deal of memory Instead you can add the properties to Book prototype so that the bookcount a...

Страница 664: ...iting Book prototype you define the Book class in an external file named Book as For more information see Creating and using classes in Using ActionScript in Flash The following code must be in a separate external file named Book as that contains only this class definition and resides within the Flash application s classpath class Book var books Number function set bookcount numBooks Number Void t...

Страница 665: ...str String new String sven trace my_str constructor String output true If you use the instanceof operator you can also determine if an object belongs to a specified class var my_str String new String sven trace my_str instanceof String output true However in the following example the Object constructor property converts primitive data types such as the string literal seen here into wrapper objects...

Страница 666: ...ototype property of the constructor function that created myObject The __proto__ property is automatically assigned to all objects when they are created The ActionScript interpreter uses the __proto__ property to access the prototype property of the object s constructor function to find out what properties and methods the object inherits from its class ...

Страница 667: ... instance of the specified movie clip symbol is created by using MovieClip attachMovie or MovieClip duplicateMovieClip it is registered to the class specified by theClass rather than to the MovieClip class If theClass is null this method removes any ActionScript class definition associated with the specified movie clip symbol or class identifier For movie clip symbols any existing instances of the...

Страница 668: ...if the properties or methods are actually defined This property is useful for enabling highly transparent client server communication and is the recommended way of invoking server side methods Example The following examples progressively build upon the first example and illustrate five different usages of the __resolve property To aid understanding key statements that differ from the previous usag...

Страница 669: ...n for __resolve to call myObject myFunction function name trace Method name was called define the __resolve function myObject __resolve function name trace Resolve called for name to check when __resolve is called Not only call the function but also save a reference to it var f Function function this myFunction name create a new object method and assign it the reference this name f return the refe...

Страница 670: ... creating a functor that accepts parameters This example makes extensive use of the arguments object and uses several methods of the Array class instantiate a new object var myObject Object new Object define a generic function for __resolve to call myObject myFunction function name arguments shift trace Method name was called with arguments arguments join define the __resolve function myObject __r...

Страница 671: ...Object __resolve 671 myObject someOtherMethod hello world output Method someOtherMethod was called with arguments hello world ...

Страница 672: ...d time Array toString returns the array contents as a comma delimited string var myArray Array new Array one two trace myArray toString output one two Number toString returns the number value as a string Because trace won t tell us whether the value is a string or number we will also use typeof to test whether toString works var myNumber Number 5 trace typeof myNumber output number trace myNumber ...

Страница 673: ...code to place into a FLA file var myVehicle Vehicle new Vehicle 2 red trace myVehicle toString output A vehicle that is red and has 2 doors for comparison purposes this is a call to valueOf there is no primitive value of myVehicle so the object is returned giving the same output as toString trace myVehicle valueOf output A vehicle that is red and has 2 doors ...

Страница 674: ...bject property that should no longer be watched Returns A Boolean value true if the watchpoint is successfully removed false otherwise Description Method removes a watchpoint that Object watch created This method returns a value of true if the watchpoint is successfully removed false otherwise Example See the example for Object watch See also Object addProperty Object watch ...

Страница 675: ... following examples show the return values for the built in classes Date and Array and compares them to the return values of Object toString Create a new Date object set to February 1 2004 8 15 AM The toString method returns the current time in human readable form The valueOf method returns the primitive value in milliseconds var myDate Date new Date 2004 01 01 8 15 trace myDate toString output Su...

Страница 676: ...ur can use the return statement in your callback method definition to affect the value of the property you are watching The value returned by your callback method is assigned to the watched object property The value you choose to return depends on whether you wish to monitor modify or prevent changes to the property If you are merely monitoring the property return the newVal parameter If you are m...

Страница 677: ...ipt properties such as _x _y _width and _height are getter setter properties and cannot be watched with Object watch Example The following example uses watch to check whether the speed property exceeds the speed limit Create a new object var myObject Object new Object Add a property that tracks speed myObject speed 0 Write the callback function to be executed if the speed property changes var spee...

Страница 678: ...en rolls outside the button area dragOver While the pointer is over the button the mouse button has been pressed then rolled outside the button and then rolled back over the button keyPress key The specified keyboard key is pressed For the key portion of the parameter specify a key code or key constant You can use this parameter to intercept a key press that is to override any built in behavior fo...

Страница 679: ...on 679 on release trace X this _x trace Y this _y stopDrag See also onClipEvent ...

Страница 680: ...frame actions that are attached to the affected frames mouseMove The action is initiated every time the mouse is moved Use the _xmouse and _ymouse properties to determine the current mouse position mouseDown The action is initiated when the left mouse button is pressed mouseUp The action is initiated when the left mouse button is released keyDown The action is initiated when a key is pressed Use K...

Страница 681: ...playhead is sent to the previous frame onClipEvent keyDown if Key getCode Key RIGHT this _parent nextFrame else if Key getCode Key LEFT this _parent prevFrame The following example uses onClipEvent with the load and mouseMove movie events The _xmouse and _ymouse properties track the position of the mouse each time the mouse moves which appears in the text field that s created at runtime onClipEven...

Страница 682: ...eters tab in the Components inspector onUpdate is invoked The onUpdate function does something to update itself For instance if the component includes a color parameter the onUpdate function might alter the color of a movie clip inside the Live Preview to reflect the new parameter value In addition it might store the new color in an internal variable The following example uses the onUpdate functio...

Страница 683: ...onUpdate 683 buttonLabel textColor my_mc labelColor ...

Страница 684: ...ve the current movie clip or object Example In the following example there is a movie clip on the Stage with the instance name square_mc Within that movie clip is another movie clip with an instance name circle_mc The following ActionScript lets you modify the circle_mc parent instance which is square_mc when the circle is clicked When you are working with relative addressing using _parent instead...

Страница 685: ... the initial number If the string does not begin with a number that can be parsed parseFloat returns NaN White space preceding valid integers is ignored as are trailing nonnumeric characters Example The following examples use the parseFloat function to evaluate various types of numbers trace parseFloat 2 output 2 trace parseFloat 2 5 output 2 5 trace parseFloat 2 5 output 2 5 trace parseFloat 3 5e...

Страница 686: ...eginning with 0 or specifying a radix of 8 are interpreted as octal numbers White space preceding valid integers is ignored as are trailing nonnumeric characters Example The examples in this section use the parseInt function to evaluate various types of numbers The following example returns 3 parseInt 3 5 The following example returns NaN parseInt bar The following example returns 4 parseInt 4foo ...

Страница 687: ...parseInt 687 The following examples show octal number parsing and return 511 which is the decimal representation of the octal 777 parseInt 0777 parseInt 777 8 See also NaN parseFloat ...

Страница 688: ...le there are two movie clip instances on the Stage with the instance names stop_mc and play_mc The ActionScript stops the SWF file s playback when the stop_mc movie clip instance is clicked Playback resumes when the play_mc instance is clicked this stop_mc onRelease function stop this play_mc onRelease function play trace frame 1 See also gotoAndPlay MovieClip gotoAndPlay CHAPTER 2 ActionScript La...

Страница 689: ...he current frame is Frame 1 the playhead does not move Example When the user clicks a button called myBtn_btn and the following ActionScript is placed on a frame in the Timeline for that button the playhead is sent to the previous frame stop this myBtn_btn onRelease function prevFrame See also MovieClip prevFrame nextFrame CHAPTER 2 ActionScript Language Reference ...

Страница 690: ...uage Reference prevScene Availability Flash 2 Usage prevScene Void Parameters None Returns Nothing Description Function sends the playhead to Frame 1 of the previous scene See also nextScene CHAPTER 2 ActionScript Language Reference ...

Страница 691: ... in your movie clip vary in size bframe Indicates that the bounding box of each printable frame should be used as the print area for that frame which changes the print area for each frame and scales the objects to fit the print area Use bframe if you have objects of different sizes in each frame and want each object to fill the printed page Returns None Description Function prints the target movie...

Страница 692: ...der_mc 999 holder_mc loadMovie http www macromedia com devnet mx blueprint articles nielsen spotlight_jnielsen jpg this myBtn_btn onRelease function print this _parent holder_mc bframe In the previous ActionScript you could replace bframe with bmovie so that the print area is defined by the bounding box of a frame with the b frame label attached See also printAsBitmap printAsBitmapNum PrintJob cla...

Страница 693: ...frames in your movie clip vary in size bframe Indicates that the bounding box of each printable frame should be used as the print area for that frame This changes the print area for each frame and scales the objects to fit the print area Use bframe if you have objects of different sizes in each frame and want each object to fill the printed page Returns Nothing Description Function prints the targ...

Страница 694: ...llowing example prints all the printable frames in holder_mc with a print area defined by the bounding box of the frame this createEmptyMovieClip holder_mc 999 holder_mc loadMovie http www macromedia com devnet mx blueprint articles back_button sp_mchambers jpg this myBtn_btn onRelease function printAsBitmap this _parent holder_mc bframe See also print printAsBitmapNum PrintJob class printNum ...

Страница 695: ...of each printable frame should be used as the print area for that frame This changes the print area for each frame and scales the objects to fit the print area Use bframe if you have objects of different sizes in each frame and you want each object to fill the printed page Returns None Description Function prints a level in Flash Player as a bitmap according to the boundaries specified in the para...

Страница 696: ...s Non PostScript printers convert vectors to bitmaps Example The following example prints the contents of the Stage when the user clicks the button myBtn_btn The area to print is defined by the bounding box of the frame myBtn_btn onRelease function printAsBitmapNum 0 bframe See also print printAsBitmap PrintJob class printNum ...

Страница 697: ...such as page height width and orientation and you can configure your document to dynamically format Flash content that is appropriate for the printer settings These user layout properties are read only and cannot be changed by Flash Player Method summary for the PrintJob class You must use the methods for PrintJob class in the order listed in the following table Constructor for the PrintJob class ...

Страница 698: ...pecified area to print job repeat once for each page to be printed if my_pj addPage params pagesToPrint if my_pj addPage params pagesToPrint if my_pj addPage params pagesToPrint send pages from the spooler to the printer but only if one or more calls to addPage was successful You should always check for successful calls to start and addPage before calling send if pagesToPrint 0 my_pj send print pa...

Страница 699: ...se the following equivalencies to convert inches or centimeters to twips or points a twip is 1 20 of a point 1 point 1 72 inch 20 twips 1 inch 72 points 1440 twips 1 cm 567 twips You can t reliably convert between pixels and points the conversion rate depends on the screen and its resolution If the screen is set to display 72 pixels per inch for example one point is equal to one pixel Note If you ...

Страница 700: ...end the spooled pages to the printer If this method returns false for example if you haven t called PrintJob start or the user canceled the print job any subsequent calls to PrintJob addPage will fail However if previous calls to PrintJob addPage were successful the concluding PrintJob send command sends the successfully spooled pages to the printer If you passed a value for printArea the xMin and...

Страница 701: ... yMax 500 printAsBitmap true 1 pageCount Starting 50 pixels to the right of 0 0 and 70 pixels down print an area 500 pixels wide and 600 pixels high of frame 4 of level 5 in vector format if my_pj addPage 5 xMin 50 xMax 550 yMin 70 yMax 670 null 4 pageCount Starting at 0 0 print an area 400 pixels wide and 400 pixels high of frame 3 of the dance_mc movie clip in bitmap format if my_pj addPage danc...

Страница 702: ...702 Chapter 2 ActionScript Language Reference If addPage was successful at least once print the spooled pages if pageCount 0 my_pj send delete my_pj See also PrintJob send PrintJob start ...

Страница 703: ...inter Because calls to PrintJob send will not be successful if related calls to PrintJob start and PrintJob addpage failed you should check that calls to PrintJob addpage and PrintJob start were successful before calling PrintJob send var my_pj PrintJob new PrintJob if my_pj start if my_pj addPage this my_pj send delete my_pj Example See PrintJob addPage and PrintJob start See also PrintJob addPag...

Страница 704: ... the read only height width and orientation properties this method populates to format the printout Because the user sees information such as Printing page 1 immediately after clicking OK you should call the PrintJob addPage and PrintJob send commands as soon as possible If this method returns false for example if the user clicks Cancel instead of OK in the operating system s Print dialog box any ...

Страница 705: ...to addPage is possible var pageAdded Boolean false check the user s printer orientation setting and add appropriate print area to print job if my_pj orientation portrait Here the printArea measurements are appropriate for an 8 5 x 11 portrait page pageAdded my_pj addPage this xMin 0 xMax 600 yMin 0 yMax 800 else my_pj orientation is landscape Now the printArea measurements are appropriate for an 1...

Страница 706: ...me Indicates that the bounding box of each printable frame should be used as the print area for that frame This changes the print area for each frame and scales the objects to fit the print area Use bframe if you have objects of different sizes in each frame and want each object to fill the printed page Returns Nothing Description Function prints the level in Flash Player according to the boundari...

Страница 707: ...e or function For more information see Controlling member access in Using ActionScript in Flash You can use this keyword only in class definitions not in interface definitions Example The following example demonstrates how you can hide certain properties within a class using the private keyword Create a new AS file called Login as class Login private var loginUserName String private var loginPassw...

Страница 708: ...ith trace gus username output Gus trace gus password output undefined trace gus loginPassword error Because loginPassword is a private variable you cannot access it from outside the Login as class file Attempts to access the private variable generate an error message See also public static ...

Страница 709: ...ly for stylistic reasons For example you might want to use it for reasons of consistency in a block of code that also contains private or static variables Example The following example shows how you can use public variables in a class file Create a new class file called User as and enter the following code class User public var age Number public var name String Then create a new FLA or AS file in ...

Страница 710: ... are not smoothed MEDIUM Medium rendering quality Graphics are anti aliased using a 2 x 2 pixel grid but bitmaps are not smoothed Suitable for movie clips that do not contain text HIGH High rendering quality Graphics are anti aliased using a 4 x 4 pixel grid and bitmaps are smoothed if the movie clip is static This is the default rendering quality setting used by Flash BEST Very high rendering qua...

Страница 711: ...d newClip_mc Images are loaded into both movie clips When a button button_mc is clicked the duplicated movie clip is removed from the Stage this createEmptyMovieClip myClip_mc this getNextHighestDepth myClip_mc loadMovie http www macromedia com devnet mx blueprint articles server_side jeremy_gray jpg duplicateMovieClip this myClip_mc newClip_mc this getNextHighestDepth newClip_mc loadMovie http ww...

Страница 712: ...immediately to the calling function If the return statement is used alone it returns undefined You can t return multiple values If you try to do so only the last value is returned In the following example c is returned return a b c If you need to return multiple values you might want to use an array or object instead Example The following example uses the return statement inside the body of the su...

Страница 713: ... using the deprecated slash notation to specify an absolute path within the current level Caution If a movie clip that contains _root is loaded into another movie clip _root refers to the Timeline of the loading movie clip not the Timeline that contains _root If you want to ensure that _root refers to the Timeline of the loaded movie clip even if it is loaded into another movie clip use MovieClip ...

Страница 714: ... of the selection span Returns 1 if there is no index or currently selected field Selection getCaretIndex Returns the current caret insertion point position in the currently focused selection span Returns 1 if there is no caret position or currently focused selection span Selection getEndIndex Returns the index at the end of the selection span Returns 1 if there is no index or currently selected f...

Страница 715: ...ipt object named focusListener This object defines for itself an onSetFocus property to which it assigns a function The function takes two parameters a reference to the text field that lost focus and one to the text field that gained focus The function sets the border property of the text field that lost focus to false and sets the border property of the text field that gained focus to true this c...

Страница 716: ...utput_txt this getNextHighestDepth 0 0 300 200 output_txt multiline true output_txt wordWrap true output_txt border true output_txt type input output_txt text Enter your text here var my_cm ContextMenu new ContextMenu my_cm customItems push new ContextMenuItem Uppercase doUppercase function doUppercase Void var startIndex Number Selection getBeginIndex var endIndex Number Selection getEndIndex var...

Страница 717: ...nother text field this createTextField pos_txt this getNextHighestDepth 50 20 100 22 this createTextField content_txt this getNextHighestDepth 50 50 400 300 content_txt border true content_txt type input content_txt wordWrap true content_txt multiline true content_txt onChanged getCaretPos var keyListener Object new Object keyListener onKeyUp getCaretPos Key addListener keyListener var mouseListen...

Страница 718: ...o upper or lower case function convertCase target menuItem var beginIndex Number Selection getBeginIndex var endIndex Number Selection getEndIndex var tempString String make sure that text is actually selected if beginIndex 1 endIndex 1 set the temporary string to the text before the selected text tempString target text slice 0 beginIndex switch menuItem caption case Uppercase if the user selects ...

Страница 719: ...a file for the entire script Typical paths to the HelpExamples folder are Windows Program Files Macromedia Flash MX 2004 Samples HelpExamples Macintosh HD Applications Macromedia Flash MX 2004 Samples HelpExamples See Also Selection getBeginIndex ...

Страница 720: ...ither a TextField object Button object Component instance nor button movie clip has focus this method returns null Example The following example displays the currently focused selection s target path in a TextArea component instance Add several component instances or button text field and movie clip instances to the Stage Then add the following ActionScript to your AS or FLA file var focus_ta mx c...

Страница 721: ...n addListener someListener Listeners enable different pieces of code to cooperate because multiple listeners can receive notification about a single event Example The following example demonstrates how to determine when input focus changes in a SWF file between several dynamically created text fields Enter the following ActionScript into a FLA or AS file and then test the document this createTextF...

Страница 722: ...t htmlText textformat tabStops 20 80 status_txt htmlText nbsp toldFocus t oldFocus status_txt htmlText nbsp tnewFocus t newFocus status_txt htmlText nbsp tgetFocus t Selection getFocus status_txt htmlText textformat Selection addListener someListener See also Selection addListener Selection setFocus ...

Страница 723: ... text field instances When you select a text field information displays in the Output panel When you click the remove_btn instance the listener is removed and information no longer displays in the Output panel this createTextField one_txt 1 0 0 100 22 this createTextField two_txt 2 0 25 100 22 this createTextField three_txt 3 0 50 100 22 this createTextField four_txt 4 0 75 100 22 for var i in thi...

Страница 724: ...hen it is running in a browser window If the user does not fill in one of the required text fields username_txt and password_txt the cursor automatically focuses in the text field that s missing data For example if the user does not type anything into the username_txt text field and clicks the submit button an error message appears and the cursor focuses in the username_txt text field this createT...

Страница 725: ...lection setFocus username_txt return false if password_txt text length 0 status_txt text fill in password Selection setFocus password_txt return false status_txt text success Selection setFocus null return true See also Selection getFocus Selection onSetFocus ...

Страница 726: ...e index specified in the start parameter and end at the index specified in the end parameter Selection span indexes are zero based for example the first position is 0 the second position is 1 and so on This method has no effect if there is no currently focused text field Example In the following ActionScript you create a text field at runtime and add a string to it Then you focus the text field an...

Страница 727: ...es Using implicit set methods lets you modify the value of an object s property without accessing the property directly Implicit get set methods are syntactic shorthand for the Object addProperty method in ActionScript 1 For more information see Implicit getter setter methods in Using ActionScript in Flash Example The following example creates a Login class that demonstrates how the set keyword ca...

Страница 728: ...Frame 1 of the Timeline var gus Login new Login Gus Smith trace gus username output Gus gus username Rupert trace gus username output Rupert In the following example the get function executes when the value is traced The set function triggers only when you pass it a value as shown in the line gus username Rupert See also get Object addProperty ...

Страница 729: ...f you use this statement to set a variable to a value whose data type is different from the data type associated with the variable in a class file no compiler error is generated A subtle but important distinction to bear in mind is that the parameter variableString is a string not a variable name If you pass an existing variable name as the first parameter to set without enclosing the name in quot...

Страница 730: ... set name Jakob trace name The following code loops three times and creates three new variables called caption0 caption1 and caption2 for var i 0 i 3 i set caption i this is caption i trace caption0 trace caption1 trace caption2 See also var call ...

Страница 731: ...led as close to interval as possible You must use the updateAfterEvent function to make sure that the screen refreshes often enough If interval is greater than the SWF file s frame rate the interval function is only called each time the playhead enters a frame this minimizes the impact each time the screen is refreshed Example Usage 1 The following example calls an anonymous function every 1000 mi...

Страница 732: ...ct for our MovieClipLoader instance var listenerObjectbject new Object listenerObject onLoadInit function target_mc MovieClip trace start interval after the target movie clip loaded create a callback which executes about every 1000 ms 1 second and calls the intervalFunc function target_mc myInterval setInterval intervalFunc 1000 target_mc function intervalFunc target_mc display a trivial message w...

Страница 733: ... to Frame 1 var me User new User Gary this deleteUser_btn onRelease function trace Goodbye me username delete me Then create a FLA in the same directory called User as Enter the following ActionScript class User var intervalID Number var username String function User param_username String trace Welcome param_username this username param_username this intervalID setInterval this traceUsername 1000 ...

Страница 734: ... a movie clip as the movie clip plays Example The following ActionScript creates a new movie clip and loads an image into it The _x and _y coordinates are set for the clip using setProperty When you click the button called right_btn the _x coordinate of a movie clip named params_mc is incremented by 20 pixels this createEmptyMovieClip params_mc 999 params_mc loadMovie http www macromedia com devne...

Страница 735: ...ts as large as 100K When you try to save a larger object Flash Player shows the Local Storage dialog box which lets the user allow or deny local storage for the domain that is requesting access Ensure that your Stage size is at least 215 x 138 pixels this is the minimum size Flash requires to display the dialog box If the user clicks Allow the object is saved and SharedObject onStatus is invoked w...

Страница 736: ... no size limit in Flash Player that runs from the authoring environment Method summary for the SharedObject class Property summary for the SharedObject class Event handler summary for the SharedObject class Constructor for the SharedObject class For information on creating local shared objects see SharedObject getLocal Method Description SharedObject clear Purges all the data from the shared objec...

Страница 737: ...nd my_so is now empty Example The following example sets data in the shared object and then empties all of the data from the shared object var my_so SharedObject SharedObject getLocal superfoo my_so data name Hector trace before my_so clear for var prop in my_so data trace t prop trace my_so clear trace after my_so clear for var prop in my_so data trace t prop This ActionScript displays the follow...

Страница 738: ...p All attributes of a shared object s data property are saved if the object is persistent and the shared object contains the following information userName Ramona adminPrivileges true itemNumbers 101 346 483 Note Do not assign values directly to the data property of a shared object as in so data someValue Flash ignores these assignments To delete attributes for local shared objects use code such a...

Страница 739: ... object Object Example The following example saves text from a TextInput component instance to a shared object named my_so for the complete example see SharedObject getLocal create listener object and function for enter event var textListener Object new Object textListener enter function eventObj Object my_so data myTextSaved eventObj target text my_so flush ...

Страница 740: ...ct to a file when the shared object session ends that is when the SWF file is closed when the shared object is garbage collected because it no longer has any references to it or when you call SharedObject clear If this method returns pending the Flash Player shows a dialog box asking the user to increase the amount of disk space available to objects from this domain To allow space for the shared o...

Страница 741: ...verride Boolean settings Object var my_so SharedObject SharedObject getLocal soName http www mydomain com app sys settings list index var i For each specified value in settings If override is true set the persistent setting to the provided value If override is false fetch the persistent setting unless there isn t one in which case set it to the provided value for i in settings if override my_so da...

Страница 742: ...eter s importance Returns A reference to a shared object that is persistent locally and is available only to the current client If Flash can t create or find the shared object for example if localPath was specified but no such directory exists this method returns null Description Method returns a reference to a locally persistent shared object that is available only to the current client Note If t...

Страница 743: ...le your localPath parameter options for the portfolio shared object created by the SWF file at www myCompany com apps stockwatcher swf are apps or apps stockwatcher swf You will need to determine which option provides enough flexibility for your application Example The following example creates a shared object that stores text typed into a TextInput component instance The resulting SWF file will l...

Страница 744: ... for this user if my_so data user undefined this user my_so data user this gotoAndStop my_so data frame The following code block is placed on each SWF file frame On each frame call the rememberme function to save the frame number function rememberme my_so data frame this _currentframe my_so data user John ...

Страница 745: ... the longer it takes to estimate its size For this reason estimating object size can have significant processing time Therefore you might want to avoid using this method unless you have a specific need for it Example The following example gets the size of the shared object my_so var items_array Array new Array 101 346 483 var currentUserIsAdmin Boolean true var currentUserName String Ramona var my...

Страница 746: ...on called System onStatus If onStatus is invoked for a particular object and no function is assigned to respond to it Flash processes a function assigned to System onStatus if it exists The following events notify you when certain SharedObject activities occur Example The following example displays different messages based on whether the user chooses to allow or deny the SharedObject object instan...

Страница 747: ...rentUserName my_so onStatus function infoObject Object status_txt htmlText textformat tabStops 50 for var i in infoObject status_txt htmlText b i b t infoObject i status_txt htmlText textformat var flushResult my_so flush 1000001 switch flushResult case pending message_str flush is pending waiting on user interaction break case true message_str flush was successful Requested storage space approved...

Страница 748: ...Returns the size of the sound in bytes Sound getPan Returns the value of the previous setPan call Sound getTransform Returns the value of the previous setTransform call Sound getVolume Returns the value of the previous setVolume call Sound loadSound Loads an MP3 file into Flash Player Sound setPan Sets the left right balance of the sound Sound setTransform Sets the amount of each channel left and ...

Страница 749: ...ls all of the sounds in the movie Example The following example creates a new Sound object called global_sound The second line calls setVolume and adjusts the volume on all sounds in the movie to 50 var global_sound Sound new Sound global_sound setVolume 50 The following example creates a new Sound object passes it the target movie clip my_mc and calls the start method which starts any sound in my...

Страница 750: ... parameter to the specified Sound object The sound must be in the library of the current SWF file and specified for export in the Linkage Properties dialog box You must call Sound start to start playing the sound To make sure that the sound can be controlled from any scene in the SWF file place the sound on the main Timeline of the SWF file Example The following example attaches the sound logoff_i...

Страница 751: ...conds my_sound loadSound song1 mp3 true The following example loads several songs into a SWF file A progress bar created using the Drawing API displays the loading progress When the music starts and completes loading information displays in the Output panel Add the following ActionScript to your FLA or AS file var pb_height Number 10 var pb_width Number 100 var pb MovieClip this createEmptyMovieCl...

Страница 752: ..._sound Sound new Sound my_sound onLoad function success Boolean if success trace sound loaded my_sound onSoundComplete function clearInterval my_interval trace Cleared interval my_sound loadSound song3 mp3 true my_interval setInterval updateProgressBar 100 my_sound function updateProgressBar the_sound Sound Void var pos Number Math round the_sound position the_sound duration 100 pb bar_mc _xscale ...

Страница 753: ...e when the file finishes loading Add the following ActionScript to your FLA or AS file this createTextField message_txt this getNextHighestDepth 10 10 300 22 this createTextField status_txt this getNextHighestDepth 10 50 300 40 status_txt autoSize true status_txt multiline true status_txt border false var my_sound Sound new Sound my_sound onLoad function success Boolean if success this start messa...

Страница 754: ...Script Language Reference status_txt text the_sound getBytesLoaded of the_sound getBytesTotal bytes pct newline status_txt text the_sound position of the_sound duration milliseconds pos newline See also Sound getBytesTotal ...

Страница 755: ...tBytesTotal Number Parameters None Returns An integer indicating the total size in bytes of the specified Sound object Description Method returns the size in bytes of the specified Sound object Example See Sound getBytesLoaded for a sample usage of this method See also Sound getBytesLoaded ...

Страница 756: ...ng the Drawing API When the user drags the slider bar the pan level of the loaded sound changes The current pan level is displayed in a dynamically created text field Add the following ActionScript to your FLA or AS file var bar_width Number 200 this createEmptyMovieClip bar_mc this getNextHighestDepth with bar_mc lineStyle 4 0x000000 moveTo 0 0 lineTo bar_width 4 0 lineStyle 0 0x000000 moveTo bar...

Страница 757: ...ease function this stopDrag var multiplier Number 100 this right this left 2 var pan Number this _x this left bar_width 2 multiplier my_sound setPan pan pan_txt text my_sound getPan var my_sound Sound new Sound my_sound loadSound song2 mp3 true this createTextField pan_txt this getNextHighestDepth knob_mc _x knob_mc _y knob_mc _height 20 22 pan_txt selectable false pan_txt autoSize center pan_txt ...

Страница 758: ...t to your FLA or AS file var my_sound Sound new Sound my_sound loadSound song1 mp3 true var transform_obj Object my_sound getTransform this createEmptyMovieClip transform_mc this getNextHighestDepth transform_mc createTextField transform_txt transform_mc getNextHighestDepth 0 8 120 22 transform_mc transform_txt html true var knob_ll MovieClip transform_mc attachMovie knob_id ll_mc transform_mc get...

Страница 759: ...00 knob_rr left knob_rr _x knob_rr right knob_rr _x knob_rr _y knob_rr _y 100 transform_obj rr knob_rr onPress pressKnob knob_rr onRelease releaseKnob knob_rr onReleaseOutside releaseKnob updateTransformTxt function pressKnob this startDrag false this left this top this right this bottom function releaseKnob this stopDrag updateTransformTxt function updateTransformTxt var ll_num Number 30 100 knob...

Страница 760: ...f the sound playing in the SWF file Add the following ActionScript to your AS or FLA file var my_sound Sound new Sound my_sound loadSound song3 mp3 true this createEmptyMovieClip knob_mc this getNextHighestDepth knob_mc left knob_mc _x knob_mc right knob_mc left 100 knob_mc top knob_mc _y knob_mc bottom knob_mc _y knob_mc _x my_sound getVolume with knob_mc lineStyle 0 0x000000 beginFill 0xCCCCCC m...

Страница 761: ... 761 this isDragging true knob_mc onMouseMove function if this isDragging this volume_txt text this _x knob_mc onRelease function this stopDrag this isDragging false my_sound setVolume this _x See also Sound setVolume ...

Страница 762: ...ort ID3 1 0 and ID3 1 1 tags Flash Player 7 adds support for ID3 2 0 tags specifically 2 3 and 2 4 The following table lists the standard ID3 2 0 tags and the type of content the tags represent you query them in the format my_sound id3 COMM my_sound id3 TIME and so on MP3 files can contain tags other than those in this table Sound id3 provides access to those tags as well Property Description COMM...

Страница 763: ...rformers TORY Original release year TOWN File owner licensee TPE1 Lead performers soloists TPE2 Band orchestra accompaniment TPE3 Conductor performer refinement TPE4 Interpreted remixed or otherwise modified by TPOS Part of a set TPUB Publisher TRCK Track number position in set TRDA Recording dates TRSN Internet radio station name TRSO Internet radio station owner TSIZ Size TSRC ISRC international...

Страница 764: ...of song mp3 to the Output panel var my_sound Sound new Sound my_sound onID3 function for var prop in my_sound id3 trace prop my_sound id3 prop my_sound loadSound song mp3 false See also Sound attachSound Sound loadSound TRCK Sound id3 track TYER Sound id3 year ID3 2 0 tag Corresponding ID3 1 0 property ...

Страница 765: ...efore they play They are managed by the ActionScript Sound class and respond to all methods and properties of this class Streaming sounds play while they are downloading Playback begins when sufficient data has been received to start the decompressor For more information see Working with Sound in Using Flash All MP3s event or streaming loaded with this method are saved in the browser s file cache ...

Страница 766: ...rid with the instance name id3_dg to your document and add the following ActionScript to your FLA or AS file import mx controls gridclasses DataGridColumn var id3_dg mx controls DataGrid id3_dg move 0 0 id3_dg setSize Stage width Stage height var property_dgc DataGridColumn id3_dg addColumn new DataGridColumn property property_dgc width 100 property_dgc headerText ID3 Property var value_dgc DataGr...

Страница 767: ...ample The following example creates a new Sound object and loads a sound Loading the sound is handled by the onLoad handler which allows you to start the song after it is successfully loaded Create a new FLA file and add the following ActionScript to your FLA or AS file For this example to work you must have an MP3 called song1 mp3 in the same directory as your FLA or AS file this createTextField ...

Страница 768: ...u must create a function that executes when this handler is invoked You can use either an anonymous function or a named function Example Usage 1 The following example uses an anonymous function var my_sound Sound new Sound my_sound attachSound mySoundID my_sound onSoundComplete function trace mySoundID completed my_sound start Usage 2 The following example uses a named function function callback1 ...

Страница 769: ..._sound position Number Description Read only property the number of milliseconds a sound has been playing If the sound is looped the position is reset to 0 at the beginning of each loop Example See Sound duration for a sample usage of this property See Also Sound duration ...

Страница 770: ...s only the left channel 100 uses only the right channel and 0 balances the sound evenly between the two channels Returns An integer Description Method determines how the sound is played in the left and right channels speakers For mono sounds pan determines which speaker left or right the sound plays through Example See Sound getPan for a sample usage of this method See also Sound attachSound Sound...

Страница 771: ...lay mono sounds as stereo play stereo sounds as mono and to add interesting effects to sounds The properties for the soundTransformObject are as follows 11 A percentage value specifying how much of the left input to play in the left speaker 0 100 1r A percentage value specifying how much of the right input to play in the left speaker 0 100 rr A percentage value specifying how much of the right inp...

Страница 772: ... using setTransform as follows my_sound setTransform mySoundTransformObject The following example plays a stereo sound as mono the soundTransformObjectMono object has the following parameters var mySoundTransformObjectMono Object new Object mySoundTransformObjectMono ll 50 mySoundTransformObjectMono lr 50 mySoundTransformObjectMono rr 50 mySoundTransformObjectMono rl 50 my_sound setTransform mySou...

Страница 773: ... Parameters volume A number from 0 to 100 representing a volume level 100 is full volume and 0 is no volume The default setting is 100 Returns Nothing Description Method sets the volume for the Sound object Example See Sound getVolume for a sample usage of this method See also Sound setPan Sound setTransform ...

Страница 774: ...ed or starting at the point in the sound specified by the secondOffset parameter Example The following example creates a new Sound object and loads a sound Loading the sound is handled by the onLoad handler which allows you to start the song after it s successfully loaded Then the sound starts playing using the start method Create a new FLA file and add the following ActionScript to your FLA or AS...

Страница 775: ...no parameter is specified or just the sound specified in the idName parameter Example The following example uses two buttons stop_btn and play_btn to control the playback of a sound that loads into a SWF file Add two buttons to your document and add the following ActionScript to your FLA or AS file var my_sound Sound new Sound my_sound loadSound song1 mp3 true stop_btn onRelease function trace sou...

Страница 776: ...et to buffer the MP3 for 10 seconds A new Sound object instance is created for the MP3 create text fields to hold debug information this createTextField counter_txt this getNextHighestDepth 0 0 100 22 this createTextField debug_txt this getNextHighestDepth 0 20 100 22 set the sound buffer to 10 seconds _soundbuftime 10 create the new sound object instance var bg_sound Sound new Sound load the MP3 ...

Страница 777: ...od Description Stage addListener Adds a listener object that detects when a SWF file is resized Stage removeListener Removes a listener object from the Stage object Property Description Stage align Alignment of the SWF file in the player or browser Stage height Height of the Stage in pixels Stage scaleMode The current scaling of the SWF file Stage showMenu Shows or hides the default items in the F...

Страница 778: ...create a listener object Stage listener objects receive notification from Stage onResize Example This example creates a new listener object called stageListener It then uses myListener to call onResize and define a function that will be called when onResize is triggered Finally the code adds the myListener object to the callback list of the Stage object Listener objects allow multiple objects to l...

Страница 779: ...file Add a ComboBox instance to your document with the instance name stageAlign_cb Add the following ActionScript to your FLA or AS file var stageAlign_cb mx controls ComboBox stageAlign_cb dataProvider T B L R TL TR BL BR var cbListener Object new Object cbListener change function evt Object var align String evt target selectedItem Stage align align stageAlign_cb addEventListener change cbListene...

Страница 780: ... creates a new listener object called stageListener It then uses myListener to call onResize and define a function that will be called when onResize is triggered Finally the code adds the myListener object to the callback list of the Stage object Listener objects allow multiple objects to listen for resize notifications this createTextField stageSize_txt this getNextHighestDepth 10 10 100 22 var s...

Страница 781: ... this event handler to write a function that lays out the objects on the Stage when a SWF file is resized Example The following example displays a message in the Output panel when the Stage is resized Stage scaleMode noScale var myListener Object new Object myListener onResize function trace Stage size is now Stage width by Stage height Stage addListener myListener later call Stage removeListener ...

Страница 782: ...e remove_btn Add the following ActionScript to Frame 1 of the Timeline this createTextField stageSize_txt this getNextHighestDepth 10 10 100 22 stageSize_txt autoSize true stageSize_txt border true var stageListener Object new Object stageListener onResize function stageSize_txt text w Stage width h Stage height Stage addListener stageListener remove_btn onRelease function stageSize_txt text Remov...

Страница 783: ...le settings for the SWF file Add a ComboBox instance to your document with the instance name scaleMode_cb Add the following ActionScript to your FLA or AS file var scaleMode_cb mx controls ComboBox scaleMode_cb dataProvider showAll exactFit noBorder noScale var cbListener Object new Object cbListener change function evt Object var scaleMode_str String evt target selectedItem Stage scaleMode scaleM...

Страница 784: ...edia Flash Player items appear Example The following example creates a clickable text link that lets the user enable and disable the Flash Player context menu this createTextField showMenu_txt this getNextHighestDepth 10 10 100 22 showMenu_txt html true showMenu_txt autoSize true showMenu_txt htmlText a href asfunction toggleMenu u Stage showMenu Stage showMenu u a function toggleMenu Stage showMe...

Страница 785: ...he value of width will stay constant as you resize the player window Example This example creates a new listener object called stageListener It then uses myListener to call onResize and define a function that will be called when onResize is triggered Finally the code adds the myListener object to the callback list of the Stage object Listener objects allow multiple objects to listen for resize not...

Страница 786: ... can be dragged at a time After a startDrag operation is executed the movie clip remains draggable until it is explicitly stopped by stopDrag or until a startDrag action for another movie clip is called Example The following example creates a movie clip pic_mc at runtime that users can drag to any location by attaching the startDrag and stopDrag actions to the movie clip An image is loaded into pi...

Страница 787: ...e class by using the syntax someClassName name If you do create an instance of the class you can also access a static member using the instance You can use this keyword in class definitions only not in interface definitions Example The following example demonstrates how you can use the static keyword to create a counter that tracks how many instances of the class have been created Because the numI...

Страница 788: ...788 Chapter 2 ActionScript Language Reference See also private public ...

Страница 789: ...meters None Returns Nothing Description Function stops the SWF file that is currently playing The most common use of this action is to control movie clips with buttons See also gotoAndStop MovieClip gotoAndStop CHAPTER 2 ActionScript Language Reference ...

Страница 790: ... stop_mc the sound is paused When the user clicks play_mc the song resumes from its paused position this createTextField songinfo_txt this getNextHighestDepth 0 0 Stage width 22 var bg_sound Sound new Sound bg_sound loadSound yourSong mp3 true bg_sound onID3 function songinfo_txt text this id3 artist this id3 album this id3 track this id3 songname for prop in this id3 trace prop this id3 prop trac...

Страница 791: ...t drag operation Example The following code placed in the main Timeline stops the drag action on the movie clip instance my_mc when the user releases the mouse button my_mc onPress function startDrag this my_mc onRelease function stopDrag See also MovieClip _droptarget MovieClip stopDrag startDrag CHAPTER 2 ActionScript Language Reference ...

Страница 792: ...if no such property exists If expression is undefined the return values are as follows In files published for Flash Player 6 or earlier the result is an empty string In files published for Flash Player 7 or later the result is undefined If expression is a Boolean value the return string is true or false If expression is a movie clip the return value is the target path of the movie clip in slash no...

Страница 793: ...ty with a string literal Do not confuse a string literal with a String object In the following example the first line of code creates the string literal first_string and the second line of code creates the String object second_string var first_string String foo var second_string String new String foo Use string literals unless you specifically need to use a String object Method summary for the Str...

Страница 794: ...instead of the constructor for the String class unless you have a good reason to use a String object rather than a string literal See also String string delimiter String substring Returns the characters between two indexes in a string String toLowerCase Converts the string to lowercase and returns the result does not change the contents of the original object String toUpperCase Converts the string...

Страница 795: ...cription Method returns the character in the position specified by the parameter index If index is not a number from 0 to string length 1 an empty string is returned This method is similar to String charCodeAt except that the returned value is a character not a 16 bit integer character code Example In the following example this method is called on the first letter of the string Chris var my_str St...

Страница 796: ...er Description Method returns a 16 bit integer from 0 to 65535 that represents the character specified by index If index is not a number from 0 to string length 1 NaN is returned This method is similar to String charAt except that the returned value is a 16 bit integer character code not a character Example In the following example this method is called on the first letter of the string Chris var ...

Страница 797: ...tring Description Method combines the value of the String object with the parameters and returns the newly formed string the original value my_str is unchanged Example The following example creates two strings and combines them using String concat var stringA String Hello var stringB String World var combinedAB String stringA concat stringB trace combinedAB output Hello World ...

Страница 798: ...gers that represent ASCII values Returns A string Description Method returns a string comprising the characters represented by the ASCII values in the parameters Example The following example uses fromCharCode to insert an character in the e mail address var address_str String dog String fromCharCode 64 house net trace address_str output dog house net ...

Страница 799: ...or after startIndex within the calling string This index is zero based meaning that the first character in a string is considered to be at index 0 not index 1 If substring is not found the method returns 1 Example The following examples use indexOf to return the index of characters and substrings var searchString String Lorem ipsum dolor sit amet var index Number index searchString indexOf L trace...

Страница 800: ...x within the calling string This index is zero based meaning that the first character in a string is considered to be at index 0 not index 1 If substring is not found the method returns 1 Example The following example shows how to use lastIndexOf to return the index of a certain character var searchString String Lorem ipsum dolor sit amet var index Number index searchString lastIndexOf L trace ind...

Страница 801: ...ps from 0 to my_str length The code checks the characters within a string and if the string contains the character true displays in the Output panel If it does not contain the character then false displays in the Output panel function checkAtSymbol my_str String Boolean for var i 0 i my_str length i if my_str charAt i return true return false trace checkAtSymbol dog house net output true trace che...

Страница 802: ... If the end parameter is not specified the end of the substring is the end of the string If the character indexed by start is the same as or to the right of the character indexed by end the method returns an empty string Example The following example creates a variable my_str assigns it a String value and then calls the slice method using a variety of values for both the start and end parameters E...

Страница 803: ...lice 3 my_str slice 3 slice 3 em An example is also in the Strings fla file in the HelpExamples folder The following list gives typical paths to this folder Windows Program Files Macromedia Flash MX 2004 Samples HelpExamples Macintosh HD Applications Macromedia Flash MX 2004 Samples HelpExamples See also String substr String substring ...

Страница 804: ...ing is placed as an element in the array If the delimiter parameter is undefined the entire string is placed into the first element of the returned array Example The following example returns an array with five elements var my_str String P A T S Y var my_array Array my_str split for var i 0 i my_array length i trace my_array i output P A T S Y The following example returns an array with two elemen...

Страница 805: ...Strings fla file in the HelpExamples folder The following list gives typical paths to this folder Windows Program Files Macromedia Flash MX 2004 Samples HelpExamples Macintosh HD Applications Macromedia Flash MX 2004 Samples HelpExamples See Also Array join ...

Страница 806: ...from the index specified in the start parameter through the number of characters specified in the length parameter The substr method does not change the string specified by my_str it returns a new string Example The following example creates a new string my_str and uses substr to return the second word in the string first using a positive start parameter and then using a negative start parameter v...

Страница 807: ...e points specified by the start and end parameters If the end parameter is not specified the end of the substring is the end of the string If the value of start equals the value of end the method returns an empty string If the value of start is greater than the value of end the parameters are automatically swapped before the function executes and the original value is unchanged Example The followi...

Страница 808: ...ring using toLowerCase to convert all uppercase characters to lowercase characters var upperCase String LOREM IPSUM DOLOR var lowerCase String upperCase toLowerCase trace upperCase upperCase output upperCase LOREM IPSUM DOLOR trace lowerCase lowerCase output lowerCase lorem ipsum dolor An example is also in the Strings fla file in the HelpExamples folder The following list gives typical paths to t...

Страница 809: ...d then creates a copy of that string using toUpperCase var lowerCase String lorem ipsum dolor var upperCase String lowerCase toUpperCase trace lowerCase lowerCase output lowerCase lorem ipsum dolor trace upperCase upperCase output upperCase LOREM IPSUM DOLOR An example is also found in the Strings fla file in the HelpExamples folder The following list gives typical paths to this folder Windows Pro...

Страница 810: ...erical value or other ActionScript element Example The following example uses quotation marks to indicate that the value of the variable yourGuess is the literal string Prince Edward Island and not the name of a variable The value of province is a variable not a literal to determine the value of province the value of yourGuess must be located var yourGuess String Prince Edward Island submit_btn on...

Страница 811: ...a constructor function to invoke the superclass version of the constructor function and can optionally pass parameters to it This is useful for creating a subclass that performs additional initialization but also invokes the superclass constructor to perform superclass initialization Example In the following example you create two classes You use the super keyword in the Sock class to call functio...

Страница 812: ...e mySock getColor mySock setColor Orange trace mySock getColor The following result is displayed in the Output panel Clothes I am the constructor Socks I am the constructor Socks I am getColor Clothes I am getColor maroon Socks I am setColor Socks I am getColor Clothes I am getColor Orange If you forgot to put the super keyword in the Sock class s getColor method then the getColor method could cal...

Страница 813: ... of true All switch statements should include a default case The default case should include a break statement that prevents a fall through error if another case is added later When a case falls through it doesn t have a break statement Example In the following example if the String fromCharCode Key getAscii parameter evaluates to A the trace statement that follows case A executes if the parameter...

Страница 814: ...814 Chapter 2 ActionScript Language Reference case i trace you pressed I or i break default trace you pressed some other key Key addListener listenerObj See also strict equality break case default if ...

Страница 815: ... t V WIN 207 2C0 2 C19 2C0 M Macromedia 20Windows R 1600x1200 DP 72 COL color AR 1 0 OS Window s 20XP L en PT External AVD f LFD f WD f Property summary for the System capabilities object All properties of the System capabilities object are read only Property Description Server string System capabilities avHardwareDisable Specifies whether the user s camera and microphone are enabled or disabled A...

Страница 816: ... running L System capabilities localFileReadDisable Specifies whether the player will attempt to read anything including the first SWF file the player launches with from the user s hard disk LFD System capabilities manufacturer Indicates the manufacturer of Flash Player M System capabilities os Indicates the operating system hosting Flash Player OS System capabilities pixelAspectRatio Indicates th...

Страница 817: ...ription Read only property a Boolean value that specifies whether access to the user s camera and microphone has been administratively prohibited true or allowed false The server string is AVD Example The following example traces the value of this read only property trace System capabilities avHardwareDisable See also Camera get Microphone get System showSettings ...

Страница 818: ... property a Boolean value that is true if the player is running in an environment that supports communication between Flash Player and accessibility aids false otherwise The server string is ACC Example The following example traces the value of this read only property trace System capabilities hasAccessibility See also Accessibility isActive Accessibility updateProperties _accProps ...

Страница 819: ... capabilities hasAudio Boolean Description Read only property a Boolean value that is true if the player is running on a system that has audio capabilities false otherwise The server string is A Example The following example traces the value of this read only property trace System capabilities hasAudio ...

Страница 820: ...abilities hasAudioEncoder Boolean Description Read only property a Boolean value that is true if the player can encode an audio stream such as that coming from a microphone false otherwise The server string is AE Example The following example traces the value of this read only property trace System capabilities hasAudioEncoder ...

Страница 821: ...m capabilities hasEmbeddedVideo Boolean Description Read only property a Boolean value that is true if the player is running on a system that supports embedded video false otherwise The server string is EV Example The following example traces the value of this read only property trace System capabilities hasEmbeddedVideo ...

Страница 822: ...ge System capabilities hasMP3 Boolean Description Read only property a Boolean value that is true if the player is running on a system that has an MP3 decoder false otherwise The server string is MP3 Example The following example traces the value of this read only property trace System capabilities hasMP3 ...

Страница 823: ...stem capabilities hasPrinting Boolean Description Read only property a Boolean value that is true if the player is running on a system that supports printing false otherwise The server string is PR Example The following example traces the value of this read only property trace System capabilities hasPrinting ...

Страница 824: ...oadcast Boolean Description Read only property a Boolean value that is true if the player supports the development of screen broadcast applications to be run through the Flash Communication Server false otherwise The server string is SB Example The following example traces the value of this read only property trace System capabilities hasScreenBroadcast ...

Страница 825: ...ck Boolean Description Read only property a Boolean value that is true if the player supports the playback of screen broadcast applications that are being run through the Flash Communication Server false otherwise The server string is SP Example The following example traces the value of this read only property trace System capabilities hasScreenPlayback ...

Страница 826: ... r65 Usage System capabilities hasStreamingAudio Boolean Description Read only property a Boolean value that is true if the player can play streaming audio false otherwise The server string is SA Example The following example traces the value of this read only property trace System capabilities hasStreamingAudio ...

Страница 827: ...65 Usage System capabilities hasStreamingVideo Boolean Description Read only property a Boolean value that is true if the player can play streaming video false otherwise The server string is SV Example The following example traces the value of this read only property trace System capabilities hasStreamingVideo ...

Страница 828: ...abilities hasVideoEncoder Boolean Description Read only property a Boolean value that is true if the player can encode a video stream such as that coming from a web camera false otherwise The server string is VE Example The following example traces the value of this read only property trace System capabilities hasVideoEncoder ...

Страница 829: ...ties isDebugger Boolean Description Read only property a Boolean value that indicates whether the player is an officially released version false or a special debugging version true The server string is DEB Example The following example traces the value of this read only property trace System capabilities isDebugger ...

Страница 830: ...English systems no longer includes the country code In Flash Player 6 all English systems return the language code and the two letter country code subtag en US In Flash Player 7 English systems return only the language code en Second on Microsoft Windows systems this property now returns the User Interface UI Language In Flash Player 6 on the Microsoft Windows platform System capabilities language...

Страница 831: ...uage 831 Example The following example traces the value of this read only property trace System capabilities language Russian ru Simplified Chinese zh CN Spanish es Swedish sv Traditional Chinese zh TW Turkish tr Language Tag ...

Страница 832: ...unable to read files including the first SWF file that Flash Player launches with from the user s hard disk For example attempts to read a file on the user s hard disk using XML load LoadMovie or LoadVars load will fail if this property is set to true Reading runtime shared libraries will also be blocked if this property is set to true but reading local shared objects is allowed without regard to ...

Страница 833: ...ufacturer String Description Read only property a string that indicates the manufacturer of Flash Player in the format Macromedia OSName OSName could be Windows Macintosh Linux or Other OS Name The server string is M Example The following example traces the value of this read only property trace System capabilities manufacturer ...

Страница 834: ...ng that indicates the current operating system The os property can return the following strings Windows XP Windows 2000 Windows NT Windows 98 ME Windows 95 Windows CE available only in Flash Player SDK not in the desktop version Linux and MacOS The server string is OS Example The following example traces the value of this read only property trace System capabilities os ...

Страница 835: ...sh Player 6 Usage System capabilities pixelAspectRatio Number Description Read only property an integer that indicates the pixel aspect ratio of the screen The server string is AR Example The following example traces the value of this read only property trace System capabilities pixelAspectRatio ...

Страница 836: ...ayer This property can have one of the following values StandAlone for the Flash StandAlone Player External for the Flash Player version used by test movie mode PlugIn for the Flash Player browser plug in ActiveX for the Flash Player ActiveX Control used by Microsoft Internet Explorer The server string is PT Example The following example traces the value of this read only property trace System cap...

Страница 837: ...r String Description Read only property a string that indicates the screen color This property can have the value color gray or bw which represents color grayscale and black and white respectively The server string is COL Example The following example traces the value of this read only property trace System capabilities screenColor ...

Страница 838: ...Player 6 Usage System capabilities screenDPI Number Description Read only property a number that indicates the dots per inch dpi resolution of the screen in pixels The server string is DP Example The following example traces the value of this read only property trace System capabilities screenDPI ...

Страница 839: ...ities screenResolutionX Number Description Read only property an integer that indicates the maximum horizontal resolution of the screen The server string is R which returns both the width and height of the screen Example The following example traces the value of this read only property trace System capabilities screenResolutionX ...

Страница 840: ...bilities screenResolutionY Number Description Read only property an integer that indicates the maximum vertical resolution of the screen The server string is R which returns both the width and height of the screen Example The following example traces the value of this read only property trace System capabilities screenResolutionY ...

Страница 841: ...at specifies values for each System capabilities property as shown in the following example A t SA t SV t EV t MP3 t AE t VE t ACC f PR t SP t SB f DEB t V WIN 207 2C0 2C 19 2C0 M Macromedia 20Windows R 1600x1200 DP 72 COL color AR 1 0 OS Windows 20 XP L en PT External AVD f LFD f WD f Example The following example traces the value of this read only property trace System capabilities serverString ...

Страница 842: ... 6 Usage System capabilities version String Description Read only property a string containing the Flash Player platform and version information for example WIN 7 0 19 0 The server string is V Example The following example traces the value of this read only property trace System capabilities version ...

Страница 843: ...y allowDomain Lets SWF files in the identified domains access objects and variables in the calling SWF file or in any other SWF file from the same domain as the calling SWF file System security allowInsecureDomain Lets SWF files in the identified domains access objects and variables in the calling SWF file which is hosted using the HTTPS protocol System security loadPolicyFile Loads a cross domain...

Страница 844: ... to allow access by SWF files that are running in Flash Player 7 or later System security allowDomain www domain com store domain com Also for files running in Flash Player 7 or later you can t use this method to let SWF files hosted using a secure protocol HTTPS allow access from SWF files hosted in nonsecure protocols you must use System security allowInsecureDomain instead Occasionally you migh...

Страница 845: ... will already be loaded by the time the child loads Example The SWF file located at www macromedia com MovieA swf contains the following lines System security allowDomain www shockwave com loadMovie http www shockwave com MovieB swf my_mc Because MovieA contains the allowDomain command MovieB can access the objects and variables in MovieA If MovieA didn t contain this command the Flash security im...

Страница 846: ...layer 6 can use System security allowDomain to permit HTTP to HTTPS access However because security is implemented differently in Flash Player 7 you must use System Security allowInsecureDomain to permit such access in SWF files published for Flash Player 7 or later Note It is sometimes necessary to call System security allowInsecureDomain with an argument that exactly matches the domain of the SW...

Страница 847: ...System security allowInsecureDomain 847 See also System security allowDomain System exactSettings ...

Страница 848: ...h Player 7 0 19 0 can load policy files from arbitrary locations as shown in the following example System security loadPolicyFile http foo com sub dir pf xml This causes Flash Player to retrieve a policy file from the specified URL Any permissions granted by the policy file at that location will apply to all content at the same level or lower in the virtual directory hierarchy of the server The fo...

Страница 849: ...cify the ports to which access is granted When a policy file comes from a port lower than 1024 it can grant access to any ports when a policy file comes from port 1024 or higher it can grant access only to other ports 1024 and higher The allowed ports are specified in a to ports attribute in the allow access from tag Single port numbers port ranges and wildcards are all allowed The following examp...

Страница 850: ...for the System class Method Description System setClipboard Replaces the contents of the system Clipboard with a text string System showSettings Displays a Flash Player Settings panel Method Description System exactSettings Specifies whether to use superdomain or exact domain matching rules when accessing local settings System useCodepage Tells Flash Player whether to use Unicode or the traditiona...

Страница 851: ...operty is false in a SWF file hosted at here xyz com and true in a SWF file hosted at xyz com both files will use the same settings and data namely those in the xyz com directory If this isn t the behavior you want ensure that you set this property in each file to correctly represent where you want to store settings and data If you want to change this property from its default value do so in the f...

Страница 852: ... the player has stored the shared objects created by the Flash Player 6 SWF file in a folder that s specific to the superdomain of that SWF file you should use superdomain rules for shared object retrieval in your Flash Player 7 SWF file This step requires specifying System exactSettings false in your Flash Player 7 SWF file It is also possible that you might have SWF files that are published for ...

Страница 853: ...ined an onStatus function for that particular instance then Flash uses the function you define for System onStatus instead Note The Camera and Microphone classes also have onStatus handlers but do not pass information objects with a level property of error Therefore System onStatus is not called if you don t specify a function for these handlers Example The following example shows how to create a ...

Страница 854: ... string Example The following example places the phrase Hello World onto the system Clipboard System setClipboard Hello world The following example creates two text fields at runtime called in_txt and out_txt When you select text in the in_txt field you can click the copy_btn to copy the data to the Clipboard Then you can paste the text into the out_txt field this createTextField in_txt this getNe...

Страница 855: ...microphone gain and echo suppression settings For example if your application requires the use of a camera you can tell the user to select Allow in the Privacy Settings panel and then issue a System showSettings 0 command Ensure that your Stage size is at least 215 x 138 pixels this is the minimum size Flash requires to display the panel Example The following example shows how to display the Flash...

Страница 856: ...depage to true Add the following code as the first line of code in the first frame of the SWF file that is loading the data System useCodepage true When this code is present Flash Player interprets external text using the traditional code page of the operating system running Flash Player This is generally CP1252 for an English Windows operating system and Shift JIS for a Japanese operating system ...

Страница 857: ...the specified movie clip Description Function returns a string containing the target path of movieClipObject The target path is returned in dot notation To retrieve the target path in slash notation use the _target property Example The following example traces the target path of a movie clip as soon as it loads this createEmptyMovieClip myClip_mc this getNextHighestDepth trace targetPath myClip_mc...

Страница 858: ...ee Formatting text with Cascading Style Sheets in Using ActionScript in Flash Method summary for the TextField StyleSheet class Event handler summary for the TextField StyleSheet class L Method Description TextField StyleSheet clear Removes all styles from the style sheet object TextField StyleSheet getStyle Returns a copy of the style sheet object associated with a specified style name TextField ...

Страница 859: ...he following ActionScript to your AS or FLA file var my_styleSheet TextField StyleSheet new TextField StyleSheet my_styleSheet onLoad function success Boolean if success trace Styles loaded var styles_array Array my_styleSheet getStyleNames trace styles_array join newline else trace Error loading CSS my_styleSheet load styles css The styles css file contains two styles called heading and mainbody ...

Страница 860: ... styles from the my_styleSheet object are removed Create a new style sheet object var my_styleSheet TextField StyleSheet new TextField StyleSheet my_styleSheet onLoad function success Boolean if success trace Styles loaded var styles_array Array my_styleSheet getStyleNames for var i 0 i styles_array length i trace t styles_array i trace else trace Error loading CSS Start the loading operation my_s...

Страница 861: ... following code import TextField StyleSheet class StyleSheetTracer StyleSheetTracer displayFromURL This method displays the CSS style sheet at URL url to the Output Panel static function displayFromURL url String Void Create a new style sheet object var my_styleSheet StyleSheet new StyleSheet The load operation is asynchronous so set up a callback function to display the loaded style sheet my_styl...

Страница 862: ...de In styles css heading font family Arial Helvetica sans serif font size 24px font weight bold mainBody font family Arial Helvetica sans serif font size 12px font weight normal And finally in a FLA or AS file enter the following ActionScript to load the external style sheet styles css StyleSheetTracer displayFromURL styles css This displays the following in the Output panel Style heading fontWeig...

Страница 863: ...tyleSheet that contains two styles heading and bodyText It then invokes the style sheet object s getStyleNames method assigns the results to the array names_array and displays the contents of the array in the Output panel var my_styleSheet TextField StyleSheet new TextField StyleSheet my_styleSheet setStyle heading fontsize 24px my_styleSheet setStyle bodyText fontsize 12px var names_array Array m...

Страница 864: ...ly loading style sheets using ActionScript 2 0 see the entry for TextField StyleSheet getStyle The following example loads the CSS file named styles css into the style sheet object styleObj When the file has finished loading successfully the style sheet object is applied to a TextField object named news_txt this createTextField news_txt 999 10 10 320 240 news_txt multiline true news_txt wordWrap t...

Страница 865: ...finished loading successfully the style sheet object is applied to a TextField object named news_txt this createTextField news_txt 999 10 10 320 240 news_txt multiline true news_txt wordWrap true news_txt html true var my_styleSheet TextField StyleSheet new TextField StyleSheet my_styleSheet onLoad function success Boolean if success news_txt styleSheet my_styleSheet news_txt htmlText p class head...

Страница 866: ...ting subclasses in Using ActionScript in Flash Example The following example parses the CSS in css_str The ActionScript displays information about whether it parsed successfully and then displays the parsed CSS in the Output panel Add the following ActionScript to your AS or FLA file var css_str String heading font family Arial Helvetica sans serif font size 24px font weight bold var my_styleSheet...

Страница 867: ...ple The following code adds a style named emphasized to the style sheet myStyleSheet The style includes two style properties color and fontWeight The style object is defined with the operator myStyleSheet setStyle emphasized color 000000 fontWeight bold You could also create a style object using an instance of the Object class and then pass that object as the style parameter as the next example sh...

Страница 868: ...color 000000 Note The line of code delete styleObj deletes the original style object passed to setStyle While not necessary this step reduces memory usage because Flash Player creates a copy of the style object you pass to setStyle See also object initializer Formatting text with Cascading Style Sheets in Using ActionScript in Flash ...

Страница 869: ...t properties Description Method extends the CSS parsing capability Advanced developers can override this method by extending the TextField StyleSheet class For more information see Creating subclasses in Using ActionScript in Flash Example The following code subclasses this method class advCSS extends TextField StyleSheet override the transform method function transform style Object TextFormat for...

Страница 870: ...onts on the player s host system as an array TextField getDepth Returns the depth of a text field TextField getNewTextFormat Gets the default text format assigned to newly inserted text TextField getTextFormat Returns a TextFormat object containing formatting information for some or all text in a text field TextField removeListener Removes a listener object TextField removeTextField Removes a text...

Страница 871: ...ect with a text field TextField mouseWheelEnabled Indicates whether Flash Player should automatically scroll multiline text fields when the mouse pointer is positioned over a text field and the user rolls the mouse wheel TextField multiline Indicates if the text field contains multiple lines TextField _name The instance name of a text field instance TextField _parent A reference to the instance th...

Страница 872: ...ether the text field word wraps TextField _x The x coordinate of a text field instance TextField _xmouse Read only the x coordinate of the pointer relative to a text field instance TextField _xscale The value specifying the percentage for horizontally scaling a text field instance TextField _y The y coordinate of a text field instance TextField _ymouse Read only the y coordinate of the pointer rel...

Страница 873: ...ler method For example the following code uses txt as the parameter that is passed to the onScroller event handler The parameter is then used in a trace statement to send the instance name of the text field to the Output panel my_txt onScroller function textfield_txt TextField trace textfield_txt _name scrolled Example The following example defines an onChanged handler for the input text field my_...

Страница 874: ...874 Chapter 2 ActionScript Language Reference my_txt addListener txtListener See also TextField onChanged TextField onScroller TextField removeListener ...

Страница 875: ...ith a text field Example The following code sets the _alpha property of a text field named my_txt to 20 Create a new font symbol in the library by selecting New Font from the Library options menu Then set the linkage of the font to my font Add the following ActionScript to your FLA or AS file var my_fmt TextFormat new TextFormat my_fmt font my font where my font is the linkage name of a font in th...

Страница 876: ...meaning the right side of the text field will remain fixed and any resizing of a single line text field will be on the left side If the text includes a line break for example n or r then the bottom side will also be resized to fit the next line of text If wordWrap is also set to true then only the bottom side of the text field will be resized and the left side will remain fixed If autoSize is set ...

Страница 877: ...t define a function that executes when a user clicks the mouse myMouseListener onMouseDown function left_txt autoSize left left_txt text This is much longer text center_txt autoSize center center_txt text This is much longer text right_txt autoSize right right_txt text This is much longer text true_txt autoSize true true_txt text This is much longer text false_txt autoSize false false_txt text Thi...

Страница 878: ...ckground fill If false the text field has no background fill Example The following example creates a text field with a button that toggles the background color of the field this createTextField my_txt this getNextHighestDepth 10 10 320 240 my_txt border true my_txt text Lorum ipsum my_txt backgroundColor 0xFF0000 toggle_btn onRelease function my_txt background my_txt background ...

Страница 879: ...r Number Description Property the color of the text field background Default is 0xFFFFFF white This property may be retrieved or set even if there currently is no background but the color is only visible if the text field has a border Example See the example for TextField background See also TextField background ...

Страница 880: ...on Property if true the text field has a border If false the text field has no border Example The following example creates a text field called my_txt sets the border property to true and displays some text in the field this createTextField my_txt this getNextHighestDepth 10 10 320 240 my_txt border true my_txt text Lorum ipsum ...

Страница 881: ...00000 black This property may be retrieved or set even if there is currently no border Example The following example creates a text field called my_txt sets the border property to true and displays some text in the field this createTextField my_txt this getNextHighestDepth 10 10 320 240 my_txt border true my_txt borderColor 0x00FF00 my_txt text Lorum ipsum See also TextField border ...

Страница 882: ...ng example creates a text field and fills it with text The scroll and bottomScroll properties for the text field are then traced for the comment_txt field this createTextField comment_txt this getNextHighestDepth 0 0 160 120 comment_txt html true comment_txt selectable true comment_txt multiline true comment_txt wordWrap true comment_txt htmlText b What is hexadecimal b br The hexadecimal color sy...

Страница 883: ...le The following example creates two text fields called first_txt and second_txt The white space is removed from the second text field Add the following ActionScript to your FLA or AS file var my_str String Hello tWorld nHow are you t t tEnd this createTextField first_txt this getNextHighestDepth 10 10 160 120 first_txt html true first_txt multiline true first_txt wordWrap true first_txt condenseW...

Страница 884: ...ample In this example you need to create a dynamic text field called my_txt and then use the following ActionScript to embed fonts and rotate the text field The reference to my font refers to a Font symbol in the library with linkage set to my font var my_fmt TextFormat new TextFormat my_fmt font my font this createTextField my_txt this getNextHighestDepth 10 10 160 120 my_txt wordWrap true my_txt...

Страница 885: ...epths Create a dynamic text field on the Stage Add the following ActionScript to your FLA or AS file which dynamically creates two text fields at runtime and outputs their depths this createTextField first_mc this getNextHighestDepth 10 10 100 22 this createTextField second_mc this getNextHighestDepth 10 10 100 22 for var prop in this if this prop instanceof TextField var this_txt TextField this p...

Страница 886: ...uch as my_txt when you call this method This method returns names of fonts on the player s host system as an array It does not return names of all fonts in currently loaded SWF files The names are of type String Example The following code displays a font list returned by getFontList var font_array Array TextField getFontList font_array sort trace You have font_array length fonts currently installe...

Страница 887: ...newly inserted text such as text inserted with the replaceSel method or text entered by a user receives When getNewTextFormat is invoked the TextFormat object returned has all of its properties defined No property is null Example The following example displays the specified text field s my_txt text format object this createTextField my_txt this getNextHighestDepth 10 10 160 120 var my_fmt TextForm...

Страница 888: ...ed meaning that it has different values at different points in the text has a value of null Usage 2 Returns a TextFormat object containing a copy of the text field s text format at index Usage 3 Returns a TextFormat object containing formatting information for the span of text from beginIndex to endIndex Only properties that are common to all of the text in the specified range is set in the result...

Страница 889: ...eight Availability Flash Player 6 Usage my_txt _height Number Description Property the height of the text field in pixels Example The following code example sets the height and width of a text field my_txt _width 200 my_txt _height 200 ...

Страница 890: ...f there are multiple fonts on a line the height of the line adjusts to fit the largest font in use Note The hscroll property is zero based not one based like the vertical scrolling property TextField scroll Example The following example scrolls the my_txt text field horizontally using two buttons called scrollLeft_btn and scrollRight_btn The amount of scroll displays in a text field called scroll_...

Страница 891: ...ml property is true the text field is an HTML text field If html is false the text field is a non HTML text field Example The following example creates a text field that sets the html property to true HTML formatted text displays in the text field this createTextField my_txt this getNextHighestDepth 10 10 160 22 my_txt html true my_txt htmlText b this is bold text b See also TextField htmlText ...

Страница 892: ...not an HTML text field it behaves identically to the text property You can indicate that a text field is an HTML text field in the Property inspector or by setting the text field s html property to true Example The following example creates a text field that sets the html property to true HTML formatted text displays in the text field this createTextField my_txt this getNextHighestDepth 10 10 160 ...

Страница 893: ...property returns the same value as text length but is faster A character such as tab t counts as one character Example The following example outputs the number of characters in the date_txt text field which displays the current date var today Date new Date this createTextField date_txt this getNextHighestDepth 10 10 100 22 date_txt autoSize true date_txt text today toString trace date_txt length ...

Страница 894: ...han maxChars allows the maxChars property indicates only how much text a user can enter If the value of this property is null there is no limit on the amount of text a user can enter Example The following example creates a text field called age_txt that only lets users enter up to two numbers in the field this createTextField age_txt this getNextHighestDepth 10 10 30 22 age_txt type input age_txt ...

Страница 895: ...scroll 895 TextField maxhscroll Availability Flash Player 6 Usage my_txt maxhscroll Number Description Read only property indicates the maximum value of TextField hscroll Example See the example for TextField hscroll ...

Страница 896: ...lDown_btn to scroll the text field Add the following ActionScript to your FLA or AS file this createTextField scroll_txt this getNextHighestDepth 10 10 160 20 this createTextField my_txt this getNextHighestDepth 10 30 320 240 my_txt multiline true my_txt wordWrap true for var i 0 i 10 i my_txt text Lorem ipsum dolor sit amet consectetuer adipiscing elit sed diam nonummy nibh euismod tincidunt ut l...

Страница 897: ... add resizing functionality not shown this createTextField news_txt this getNextHighestDepth 10 10 320 240 news_txt border true news_txt wordWrap true news_txt multiline true news_txt text To see the custom context menu item right click PC or control click Mac within the text field var menu_cm ContextMenu new ContextMenu menu_cm customItems push new ContextMenuItem Resize doResize function doResiz...

Страница 898: ...llable_txt field has the mouseWheelEnabled property set to true so scrollable_txt scrolls when you click the field and roll the mouse wheel The nonscrollable_txt field does not scroll if you click the field and roll the mouse wheel var font_array Array TextField getFontList sort this createTextField scrollable_txt this getNextHighestDepth 10 10 240 320 scrollable_txt border true scrollable_txt wor...

Страница 899: ...ne if the value is false the text field is a single line text field Example The following example creates a multiline text field called fontList_txt that displays a long multiline list of fonts var font_array Array TextField getFontList sort this createTextField fontList_txt this getNextHighestDepth 10 10 240 320 fontList_txt border true fontList_txt wordWrap true fontList_txt multiline true fontL...

Страница 900: ...the following ActionScript to your FLA or AS file which dynamically creates two text fields at runtime and displays their depths in the Output panel this createTextField first_mc this getNextHighestDepth 10 10 100 22 this createTextField second_mc this getNextHighestDepth 10 10 100 22 for var prop in this if this prop instanceof TextField var this_txt TextField this prop trace this_txt _name is a ...

Страница 901: ..._txt as the parameter that is passed to the onChanged event handler The parameter is then used in a trace statement to send the instance name of the text field to the Output panel this createTextField myInputText_txt 99 10 10 300 20 myInputText_txt border true myInputText_txt type input myInputText_txt onChanged function textfield_txt TextField trace the value of textfield_txt _name was changed Ne...

Страница 902: ...e value null Example The following example creates two text fields called first_txt and second_txt When you give focus to a text field information about the text field with current focus and the text field that lost focus is displayed in the Output panel this createTextField first_txt 1 10 10 300 20 first_txt border true first_txt type input this createTextField second_txt 2 10 40 300 20 second_tx...

Страница 903: ...me of the text field to the Output panel myTextField onScroller function my_txt TextField trace my_txt _name scrolled The TextField onScroller event handler is commonly used to implement scroll bars Scroll bars typically have a thumb or other indicator that shows the current horizontal or vertical scrolling position in a text field Text fields can be navigated using the mouse and keyboard which ca...

Страница 904: ... or AS file this createTextField scroll_txt this getNextHighestDepth 10 10 160 20 this createTextField my_txt this getNextHighestDepth 10 30 320 240 my_txt multiline true my_txt wordWrap true for var i 0 i 10 i my_txt text Lorem ipsum dolor sit amet consectetuer adipiscing elit sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat scrollUp_btn onRelease function my_...

Страница 905: ...n Event handler invoked when a text field receives keyboard focus The oldFocus parameter is the object that loses the focus For example if the user presses the Tab key to move the input focus from a button to a text field oldFocus contains the text field instance If there is no previously focused object oldFocus contains a null value Example See the example for TextField onKillFocus See Also TextF...

Страница 906: ... text fields and outputs information about the _parent of each object The first text field first_txt is created on the main Timeline The second text field second_txt is created inside the movie clip called holder_mc this createTextField first_txt this getNextHighestDepth 10 10 160 22 first_txt border true trace first_txt _name s _parent is first_txt _parent this createEmptyMovieClip holder_mc this...

Страница 907: ...ng the shortcuts to discover a password on an unattended computer Example The following example creates two text fields username_txt and password_txt Text is entered into both text fields however password_txt has the password property set to true Therefore the characters display as asterisks instead of as characters in the password_txt field this createTextField username_txt this getNextHighestDep...

Страница 908: ...rty The _quality property can be set to the following values LOW Low rendering quality Graphics are not anti aliased and bitmaps are not smoothed MEDIUM Medium rendering quality Graphics are anti aliased using a 2 x 2 pixel grid but bitmaps are not smoothed Suitable for movies that do not contain text HIGH High rendering quality Graphics are anti aliased using a 4 x 4 pixel grid and bitmaps are sm...

Страница 909: ...h TextField addListener Example The following example creates an input text field called my_txt When the user types into the field information about the number of characters in the text field is displayed in the Output panel If the user clicks the removeListener_btn instance then the listener is removed and information is no longer displayed this createTextField my_txt this getNextHighestDepth 10 ...

Страница 910: ...When you call this method the text field is removed This method is similar to MovieClip removeMovieClip Example The following example creates a text field that you can remove from the Stage when you click the remove_btn instance Create a button and call it remove_btn and then add the following ActionScript to your FLA or AS file this createTextField my_txt this getNextHighestDepth 10 10 300 22 my_...

Страница 911: ...e text field with text on the Stage When you select some text and then right click or Control click over the text field you can select Enter current date from the context menu This selection calls a function that replaces the selected text with the current date this createTextField my_txt this getNextHighestDepth 10 10 320 240 my_txt border true my_txt wordWrap true my_txt multiline true my_txt ty...

Страница 912: ... called my_txt and assigns the text dog house net to the field The indexOf method is used to find the first occurrence of the specified symbol If the symbol is found the specified text between the index of 0 and the symbol replaces with the string bird If the symbol is not found an error message is displayed in the Output panel this createTextField my_txt this getNextHighestDepth 10 10 320 22 my_t...

Страница 913: ...pted characters If the string does not begin with no characters are initially accepted and succeeding characters in the string are included in the set of accepted characters Example The following example allows only uppercase characters spaces and numbers to be entered into a text field my_txt restrict A Z 0 9 The following example includes all characters but excludes lowercase letters my_txt rest...

Страница 914: ...not supported for text files that use device fonts You must use embedded fonts to use _rotation with a text field Example In this example you need to create a dynamic text field called my_txt and then use the following ActionScript to embed fonts and rotate the text field The reference to my font refers to a Font symbol in the library with linkage set to my font var my_fmt TextFormat new TextForma...

Страница 915: ...line the height of the line adjusts to fit the largest font in use For more information on scrolling text see Creating scrolling text in Using Flash Example The following example sets the maximum value for the scrolling text field my_txt Create two buttons scrollUp_btn and scrollDown_btn to scroll the text field Add the following ActionScript to your FLA or AS file this createTextField scroll_txt ...

Страница 916: ... text in the text field does not respond to selection commands from the mouse or keyboard and the text cannot be copied using the Copy command If selectable is set to true the text in the text field can be selected using the mouse or keyboard You can select text this way even if the text field is a dynamic text field instead of an input text field The text can be copied using the Copy command Exam...

Страница 917: ... the default new text format The new default text format is specified by textFormat which is a TextFormat object Example In the following example a new text field called my_txt is created at runtime and several properties are set The format of the newly inserted text is applied var my_fmt TextFormat new TextFormat my_fmt bold true my_fmt font Arial my_fmt color 0xFF9900 this createTextField my_txt...

Страница 918: ... Any property of textFormat that is set to null will not be applied By default all of the properties of a newly created TextFormat object are set to null There are two types of formatting information in a TextFormat object character level and paragraph level formatting Each character in a text field might have its own character formatting settings such as font name font size bold and italic For pa...

Страница 919: ... and applied to the my_txt text field var format1_fmt TextFormat new TextFormat format1_fmt font Arial var format2_fmt TextFormat new TextFormat format2_fmt font Courier var string1 String Sample string number one newline var string2 String Sample string number two newline this createTextField my_txt this getNextHighestDepth 0 0 300 200 my_txt multiline true my_txt wordWrap true my_txt text string...

Страница 920: ... to change the style sheet that is applied to news_txt or clear the style sheet from the text field Add the following ActionScript to your FLA or AS file this createTextField news_txt this getNextHighestDepth 0 0 300 200 news_txt wordWrap true news_txt multiline true news_txt html true var newsText String p class headline Description p Method starts loading the CSS file into styleSheet The load op...

Страница 921: ...he text field Save the following two CSS files in the same directory as the FLA or AS file you created previously in styles css important color FF0000 bold font weight bold headline color 000000 font family Arial Helvetica sans serif font size 18px font weight bold display block in styles2 css important color FF00FF bold font weight bold headline color 00FF00 font family Arial Helvetica sans serif...

Страница 922: ... Example The following example creates several text fields called one_txt two_txt three_txt and four_txt The three_txt text field has the tabEnabled property set to false so it is excluded from the automatic tab ordering this createTextField one_txt this getNextHighestDepth 10 10 100 22 one_txt border true one_txt type input this createTextField two_txt this getNextHighestDepth 10 40 100 22 two_tx...

Страница 923: ...er in the tab ordering is undefined The custom tab ordering defined by the tabIndex property is flat This means that no attention is paid to the hierarchical relationships of objects in the SWF file All objects in the SWF file with tabIndex properties are placed in the tab order and the tab order is determined by the order of the tabIndex values If two objects have the same tabIndex value the one ...

Страница 924: ...924 Chapter 2 ActionScript Language Reference one_txt tabIndex 3 two_txt tabIndex 1 three_txt tabIndex 2 four_txt tabIndex 4 See also Button tabIndex MovieClip tabIndex ...

Страница 925: ...rent window _blank specifies a new window _parent specifies the parent of the current frame and _top specifies the top level frame in the current window Example The following ActionScript creates a text field called my_txt and outputs the target path of the new field in both slash and dot notation this createTextField my_txt this getNextHighestDepth 10 10 100 22 trace my_txt _target output my_txt ...

Страница 926: ...n HTML formatted string of text to the field When you trace the htmlText property the Output panel displays the HTML formatted string When you trace the value of the text property the unformatted string with HTML tags displays in the Output panel this createTextField my_txt this getNextHighestDepth 10 10 400 22 my_txt html true my_txt htmlText b Remember to always update the help panel b trace htm...

Страница 927: ...to represent color values Each digit has sixteen possible values or characters The characters range from 0 to 9 and then A to F Black is represented by 000000 and white at the opposite end of the color system is FFFFFF Example The following ActionScript creates a text field and changes its color property to red this createTextField my_txt 99 10 10 100 300 my_txt text this will be red text my_txt t...

Страница 928: ...roperty is then used to resize the text field and the new height and width will also be displayed in the Output panel this createTextField my_txt 99 10 10 100 300 my_txt text Sample text trace textHeight my_txt textHeight textWidth my_txt textWidth trace _height my_txt _height _width my_txt _width n my_txt autoSize true trace after my_txt autoSize true trace _height my_txt _height _width my_txt _w...

Страница 929: ...dth 929 TextField textWidth Availability Flash Player 6 Usage my_txt textWidth Number Description Property indicates the width of the text Example See the example for TextField textHeight See Also TextField textHeight ...

Страница 930: ...xt and password_txt Text is entered into both text fields however password_txt has the password property set to true Therefore the characters display as asterisks instead of as characters in the password_txt field this createTextField username_txt this getNextHighestDepth 10 10 100 22 username_txt border true username_txt type input username_txt maxChars 16 username_txt text hello this createTextF...

Страница 931: ...hat loads into it this createTextField my_txt 1 10 10 100 22 trace my_txt _url var mclListener Object new Object mclListener onLoadInit function target_mc MovieClip trace target_mc _url var holder_mcl MovieClipLoader new MovieClipLoader holder_mcl addListener mclListener holder_mcl loadClip best_flash_ever swf this createEmptyMovieClip holder_mc 2 When you test this example the URL of the SWF file...

Страница 932: ... property is String Example The following example creates a text field called my_txt and associates the variable today_date with the text field When you change the variable today_date then the text that displays in my_txt updates this createTextField my_txt 1 10 10 200 22 my_txt variable today_date var today_date Date new Date var date_interval Number setInterval updateDate 500 function updateDate...

Страница 933: ...visible _visible property set to false are disabled Example The following example creates a text field called my_txt A button called visible_btn toggles the visibility of my_txt this createTextField my_txt 1 10 10 200 22 my_txt background true my_txt backgroundColor 0xDFDFDF my_txt border true my_txt type input visible_btn onRelease function my_txt _visible my_txt _visible See also Button _visible...

Страница 934: ...order true my_txt multiline true my_txt type input my_txt wordWrap true this createTextField width_txt this getNextHighestDepth 10 10 30 20 width_txt border true width_txt maxChars 3 width_txt restrict 0 9 width_txt type input width_txt text my_txt _width width_txt onChanged function my_txt _width this text this createTextField height_txt this getNextHighestDepth 70 10 30 20 height_txt border true...

Страница 935: ...es not have word wrap Example The following example demonstrates how wordWrap affects long text in a text field that s created at runtime this createTextField my_txt 99 10 10 100 200 my_txt text This is very long text that will certainly extend beyond the width of this text field my_txt border true Test the SWF file in Flash Player by selecting Control Test Movie Then return to your ActionScript a...

Страница 936: ...ckwise the enclosed text field inherits a coordinate system that is rotated 90º counterclockwise The text field s coordinates refer to the registration point position Example The following example creates a text field wherever you click the mouse When it creates a text field that field displays the current x and y coordinates of the text field this createTextField coords_txt this getNextHighestDep...

Страница 937: ... relation to the my_txt instance Add the following ActionScript to a FLA or AS file this createTextField mouse_txt this getNextHighestDepth 10 10 200 22 mouse_txt border true this createTextField textfield_txt this getNextHighestDepth 220 10 200 22 textfield_txt border true this createTextField my_txt this getNextHighestDepth 100 100 160 120 my_txt border true var mouseListener Object new Object m...

Страница 938: ...e default registration point is 0 0 Example The following example scales the my_txt instance when you click the scaleUp_btn and scaleDown_btn instances this createTextField my_txt 99 10 40 100 22 my_txt autoSize true my_txt border true my_txt selectable false my_txt text Sample text goes here scaleUp_btn onRelease function my_txt _xscale 2 my_txt _yscale 2 scaleDown_btn onRelease function my_txt _...

Страница 939: ... corner of the Stage as 0 0 If the text field is inside another movie clip that has transformations the text field is in the local coordinate system of the enclosing movie clip Thus for a movie clip rotated 90º counterclockwise the enclosed text field inherits a coordinate system that is rotated 90º counterclockwise The text field s coordinates refer to the registration point position Example See ...

Страница 940: ...tField _ymouse Availability Flash Player 6 Usage my_txt _ymouse Number Description Read only property indicates the y coordinate of the mouse position relative to the text field Example See the example for TextField _xmouse See also TextField _xmouse ...

Страница 941: ...le Number Description Property the vertical scale of the text field as applied from the registration point of the text field expressed as a percentage The default registration point is 0 0 Example See the example for TextField _xscale See also TextField _x TextField _xscale TextField _y ...

Страница 942: ...the bold property to a defined value The code my_txt setTextFormat my_fmt only changes the bold property of the text field s default text format because the bold property is the only one defined in my_fmt All other aspects of the text field s default text format remain unchanged When TextField getTextFormat is invoked a TextFormat object is returned with all of its properties defined no property i...

Страница 943: ...splayed If the target window is an empty string the text is displayed in the default target window _self If the url parameter is set to an empty string or to the value null you can get or set this property but the property will have no effect align The alignment of the paragraph represented as a string If left the paragraph is left aligned If center the paragraph is centered If right the paragraph...

Страница 944: ... any omitted parameters are treated as null Example The following example creates a TextFormat object formats the stats_txt text field and creates a new text field to display the text in Define a TextFormat which is used to format the stats_txt text field var my_fmt TextFormat new TextFormat my_fmt bold true my_fmt font Arial my_fmt size 12 my_fmt color 0xFF0000 Create a text field to display the ...

Страница 945: ...aragraph is centered If right the paragraph is right aligned The default value is null which indicates that the property is undefined Example The following example creates a text field with a border and uses TextFormat align to center the text var my_fmt TextFormat new TextFormat my_fmt align center this createTextField my_txt 1 100 100 300 100 my_txt multiline true my_txt wordWrap true my_txt bor...

Страница 946: ...t normal indentation TextFormat indent affects only the first line of each paragraph If this property is null the TextFormat object does not specify block indentation Example This example creates a text field with a border and sets the blockIndent to 20 this createTextField mytext 1 100 100 100 100 mytext multiline true mytext wordWrap true mytext border true var myformat TextFormat new TextFormat...

Страница 947: ...icates that the property is undefined If the value is true then the text is boldface Example The following example creates a text field that includes characters in boldface var my_fmt TextFormat new TextFormat my_fmt bold true this createTextField my_txt 1 100 100 300 100 my_txt multiline true my_txt wordWrap true my_txt border true my_txt text this is my test field object text my_txt setTextForma...

Страница 948: ...lt value is null Example The following example creates a new text field at runtime and enters a string with a line break into the field The TextFormat class is used to format the characters by adding bullets to each line in the text field This is demonstrated in the following ActionScript var my_fmt TextFormat new TextFormat my_fmt bullet true this createTextField my_txt 1 100 100 300 100 my_txt m...

Страница 949: ...nents for example 0xFF0000 is red and 0x00FF00 is green Example The following example creates a text field and sets the text color to red var my_fmt TextFormat new TextFormat my_fmt blockIndent 20 this createTextField my_txt 1 100 100 300 100 my_txt multiline true my_txt wordWrap true my_txt border true my_txt text this is my first test field object text my_txt setTextFormat my_fmt ...

Страница 950: ...e default value is null which indicates that the property is undefined Example The following example creates a text field and sets the font to Courier this createTextField mytext 1 100 100 100 100 mytext multiline true mytext wordWrap true mytext border true var myformat TextFormat new TextFormat myformat font Courier mytext text this is my first test field object text mytext setTextFormat myforma...

Страница 951: ...th parameter is specified word wrapping is applied to the specified text This lets you determine the height at which a text box shows all of the specified text The ascent and descent measurements provide respectively the distance above and below the baseline for a line of text The baseline for the first line of text is positioned at the text field s origin plus its ascent measurement The width and...

Страница 952: ...object and apply its properties var my_fmt TextFormat new TextFormat with my_fmt font Arial bold true Obtain metrics information for the text string with the specified formatting var metrics Object my_fmt getTextExtent my_str Create a text field just large enough to display the text this createTextField my_txt this getNextHighestDepth 100 100 metrics textFieldWidth metrics textFieldHeight my_txt b...

Страница 953: ...ow with improved text metrics Obtain text measurement information for the string wrapped at 100 pixels var metrics Object my_fmt getTextExtent textToDisplay 100 Create a new TextField object using the metric information just obtained this createTextField my_txt this getNextHighestDepth 50 50 metrics ascent 100 metrics textFieldHeight my_txt wordWrap true my_txt border true Assign the text and the ...

Страница 954: ...raph The default value is null which indicates that the property is undefined Example The following example creates a text field and sets the indentation to 10 this createTextField mytext 1 100 100 100 100 mytext multiline true mytext wordWrap true mytext border true var myformat TextFormat new TextFormat myformat indent 10 mytext text this is my first test field object text mytext setTextFormat m...

Страница 955: ...efault value is null which indicates that the property is undefined Example The following example creates a text field and sets the text style to italic this createTextField mytext 1 100 100 100 100 mytext multiline true mytext wordWrap true mytext border true var myformat TextFormat new TextFormat myformat italic true mytext text this is my first test field object text mytext setTextFormat myform...

Страница 956: ...nes The default value is null which indicates that the property is undefined Example The following example creates a text field and sets the leading to 10 var my_fmt TextFormat new TextFormat my_fmt leading 10 this createTextField my_txt 1 100 100 100 100 my_txt multiline true my_txt wordWrap true my_txt border true my_txt text this is my first test field object text my_txt setTextFormat my_fmt ...

Страница 957: ... null which indicates that the property is undefined Example The following example creates a text field and sets the left margin to 20 points this createTextField mytext 1 100 100 100 100 mytext multiline true mytext wordWrap true mytext border true var myformat TextFormat new TextFormat myformat leftMargin 20 mytext text this is my first test field object text mytext setTextFormat myformat ...

Страница 958: ...t value is null which indicates that the property is undefined Example The following example creates a text field and sets the right margin to 20 points this createTextField mytext 1 100 100 100 100 mytext multiline true mytext wordWrap true mytext border true var myformat TextFormat new TextFormat myformat rightMargin 20 mytext text this is my first test field object text mytext setTextFormat myf...

Страница 959: ... which indicates that the property is undefined Example The following example creates a text field and sets the text size to 20 points this createTextField mytext 1 100 100 100 100 mytext multiline true mytext wordWrap true mytext border true var myformat TextFormat new TextFormat myformat size 20 mytext text this is my first test field object text mytext setTextFormat myformat ...

Страница 960: ...le creates two text fields one with tab stops every 20 pixels and the other with tab stops every 40 pixels this createTextField mytext 1 100 100 200 100 mytext multiline true mytext wordWrap true mytext border true var myformat TextFormat new TextFormat myformat tabStops 20 40 60 80 mytext text ABCD mytext setTextFormat myformat this createTextField mytext2 2 100 220 200 100 mytext2 multiline true...

Страница 961: ... frame and _top specifies the top level frame in the current window If the TextFormat url property is an empty string or null you can get or set this property but the property will have no effect Example The following example creates a text field with a hyperlink to the Macromedia website The example uses TextFormat target to display the Macromedia website in a new browser window var myformat Text...

Страница 962: ...e U tag but the latter is not true underlining because it does not skip descenders correctly The default value is null which indicates that the property is undefined Example The following example creates a text field and sets the text style to underline this createTextField mytext 1 100 100 200 100 mytext multiline true mytext wordWrap true mytext border true var myformat TextFormat new TextFormat...

Страница 963: ...hyperlink The default value is null which indicates that the property is undefined Example This example creates a text field that is a hyperlink to the Macromedia website var myformat TextFormat new TextFormat myformat url http www macromedia com this createTextField mytext 1 100 100 200 100 mytext multiline true mytext wordWrap true mytext border true mytext html true mytext text Go to Macromedia...

Страница 964: ...n of the first occurrence of specified text TextSnapshot getCount Returns the number of characters TextSnapshot getSelected Specifies whether any of the text in the specified range has been selected by TextSnapshot setSelected TextSnapshot getSelectedText Returns a string that contains all the characters specified by TextSnapshot setSelected TextSnapshot getText Returns a string containing the cha...

Страница 965: ...t match the case of the string in textToFind Returns The zero based index position of the first occurrence of the specified text or 1 Description Method searches the specified TextSnapshot object and returns the position of the first occurrence of textToFind found at or after startIndex If textToFind is not found the method returns 1 Example The following example illustrates how to use this method...

Страница 966: ...cters in a TextSnapshot object Example The following example illustrates how you can output the number of characters in a specified TextSnapshot object To use this code place a static text field containing the text TextSnapshot Example on the Stage this example assumes that the movie clip contains the static text TextSnapshot Example var my_mc MovieClip this var my_snap TextSnapshot my_mc getTextS...

Страница 967: ...Returns A Boolean value of true if at least one character in the given range has been selected by the corresponding TextSnapshot setSelected command false otherwise Description Method returns a Boolean value that specifies whether a TextSnapshot object contains selected text in the specified range To search all characters pass a value of 0 for from and TextSnapshot getCount or any very large numbe...

Страница 968: ...lected text is returned without any characters added Example The following example illustrates how to use this method To use this code place a static text field containing the text TextSnapshot Example on the Stage Create a dynamic text field on the Stage select it and click the Character button in the Property inspector Select Specify ranges and enter any character into the Include These Characte...

Страница 969: ...TextSnapshot getSelectedText 969 When you test the SWF file you see a colored rectangle around the specified characters See also TextSnapshot getSelected ...

Страница 970: ...rns A string containing the characters in the specified range or an empty string if no characters are found in the specified range Description Method returns a string that contains all the characters specified by the from and to parameters If no characters are selected an empty string is returned To return all characters pass a value of 0 for from and TextSnapshot getCount or any very large number...

Страница 971: ...TextSnapshot getText 971 trace count output 20 trace theText output TextSnapshot Example See also TextSnapshot getSelectedText ...

Страница 972: ...t or pass a value of 0 for maxDistance the location specified by the x y coordinates must lie inside the bounding box of my_snap This method functions correctly only for fonts that include character metric information by default Flash does not include this information for static text fields In some cases this behavior means that the method returns 1 instead of an index value To ensure that an inde...

Страница 973: ...ich character the mouse pointer is over if any var hitIndex Number my_ts hitTestTextNearPos _xmouse _ymouse 0 deselect everything my_ts setSelected 0 my_ts getCount false if hitIndex 0 select the single character the mouse pointer is over my_ts setSelected hitIndex hitIndex 1 true See also MovieClip getTextSnapshot MovieClip _x MovieClip _y ...

Страница 974: ...o this add a dynamic text field that uses that font select Character Options for that dynamic text field and then specify that font outlines should be embedded for at least one character It doesn t matter which character s you specify nor even if they are the characters used in the static text fields in question Example The following example illustrates how to use this method To use this code plac...

Страница 975: ...ot setSelectColor 975 trace theText output Txt trace firstCharIsSelected output true trace secondCharIsSelected output false When you test the SWF file you see a colored rectangle around the specified characters ...

Страница 976: ...nding box is defined by TextSnapshot setSelectColor To select or deselect all characters pass a value of 0 for from and TextSnapshot getCount or any very large number for to To specify a single character pass a value of from 1 for to Because characters are individually marked as selected you can issue this command multiple times to select multiple characters that is using this command does not des...

Страница 977: ...nt Number my_snap getCount my_snap setSelectColor 0xFF0000 Set the selection color to red my_snap setSelected 0 4 true Select the first four characters my_snap setSelected 1 2 false Deselect the second character leaving the rest selected var firstCharIsSelected Boolean my_snap getSelected 0 1 var secondCharIsSelected Boolean my_snap getSelected 1 2 var theText String my_snap getSelectedText false ...

Страница 978: ...er to a variable defined in a class file Create ApplyThis as and enter the following code class ApplyThis var str String Defined in ApplyThis as function conctStr x String String return x x function addStr String return str Then in a FLA or AS file add the following ActionScript var obj ApplyThis new ApplyThis var abj ApplyThis new ApplyThis abj str defined in FLA or AS trace obj addStr call abj n...

Страница 979: ...s Number Void this radius radius this area Math PI Math pow radius 2 var myCircle new Circle 4 trace myCircle area In the following statement assigned to a frame inside a movie clip the keyword this references the current movie clip sets the alpha property of the current movie clip to 20 this _alpha 20 In the following statement inside a MovieClip onPress handler the keyword this references the cu...

Страница 980: ...kEmail email String if email indexOf 1 throw new Error Invalid email address checkEmail someuser_theirdomain com The following code then calls the checkEmail function within a try code block If the email_txt string does not contain a valid e mail address the error message appears in a text field error_txt try checkEmail Joe Smith catch e error_txt text e toString In the following example a subclas...

Страница 981: ...xOf 1 throw new InvalidEmailAddress try checkEmail Joe Smith catch e this createTextField error_txt this getNextHighestDepth 0 0 100 22 error_txt autoSize true error_txt text e toString See also Error class try catch finally ...

Страница 982: ...ion parameter to check whether a condition exists or to display values in the Output panel The trace statement is similar to the alert function in JavaScript You can use the Omit Trace Actions command in the Publish Settings dialog box to remove trace actions from the exported SWF file Example The following example uses a trace statement to display in the Output panel the methods and properties of...

Страница 983: ...ent var shouldExecute Boolean code that sets shouldExecute to either true or false goes here shouldExecute is set to true for this example shouldExecute true if shouldExecute true trace your statements here true is also implied so the if statement could also be written if shouldExecute trace your statements here The following example shows how automatic data typing converts true to the number 1 va...

Страница 984: ...is if the try block completes normally then the code in the finally block is still executed The finally block executes even if the try block exits using a return statement A try block must be followed by a catch block a finally block or both A single try block can have multiple catch blocks but only one finally block You can nest try blocks as many levels deep as desired The error parameter specif...

Страница 985: ...se setInterval is used clearInterval must be placed in the finally block to ensure that the interval is cleared from memory myFunction function trace this is myFunction try myInterval setInterval this myFunction 1000 throw new Error my error catch myError Error trace error caught myError finally clearInterval myInterval trace error is cleared In the following example the finally block is used to d...

Страница 986: ...hrows a different type of object In this case myRecordSet is an instance of a hypothetical class named RecordSet whose sortRows method can throw two types of errors RecordSetException and MalformedRecord In the following example the RecordSetException and MalformedRecord objects are subclasses of the Error class Each is defined in its own AS class file For more information see Creating Custom Clas...

Страница 987: ...f the RecordSet class It defines catch blocks for each type of error that is thrown by sortRows import RecordSet var myRecordSet RecordSet new RecordSet try myRecordSet sortRows trace everything is fine catch e RecordSetException trace e toString catch e MalformedRecord trace e toString See also Error class throw class extends ...

Страница 988: ...hether the expression is a string movie clip object function number or Boolean value The following table shows the results of the typeof operator on each type of expression nu Example In the following example all instances in a SWF file and their types are traced and displayed in the Output panel for i in _root trace _root i typeof _root i Parameter Output String string Movie clip movieclip Button...

Страница 989: ...e null When null and undefined are compared with the equality operator they compare as equal However when null and undefined are compared with the strict equality operator they compare as not equal Example In the following example the variable x has not been declared and therefore has the value undefined In the first section of code the equality operator compares the value of x to the value undefi...

Страница 990: ...990 Chapter 2 ActionScript Language Reference The following result is displayed in the Output panel The value of x is undefined x is undefined typeof x is undefined null and undefined are equal ...

Страница 991: ...at converting all hexadecimal sequences to ASCII characters and returns the string Example The following example shows the escape to unescape conversion process var email String user somedomain com trace email var escapedEmail String escape email trace escapedEmail var unescapedEmail String unescape escapedEmail trace unescapedEmail The following result is displayed in the Output panel user somedo...

Страница 992: ...mage into that clip It is loaded using the MovieClipLoader class When you click the image the movie clip unloads from the SWF file var pic_mcl MovieClipLoader new MovieClipLoader pic_mcl loadClip http www macromedia com devnet mx blueprint articles performance spotlight_speterson jpg this createEmptyMovieClip pic_mc this getNextHighestDepth var listenerObject Object new Object listenerObject onLoa...

Страница 993: ...eans of loadMovieNum from Flash Player To unload a SWF or image that was loaded with MovieClip loadMovie use unloadMovie instead of unloadMovieNum Example The following example loads an image into a SWF file When you click unload_btn the loaded content is removed loadMovieNum yourimage jpg 1 unload_btn onRelease function unloadMovieNum 1 See also MovieClip loadMovie loadMovieNum unloadMovie CHAPTE...

Страница 994: ...on works only with certain Mouse and MovieClip handlers the mouseDown mouseUp mouseMove keyDown and keyUp handlers for the Mouse class the onMouseMove onMouseDown onMouseUp onKeyDown and onKeyUp handlers for the MovieClip class It does not work with the Key class Example The following example show how to create a custom cursor called cursor_mc ActionScript is used to replace the mouse cursor with ...

Страница 995: ... When you use var you can strictly type the variable For more information see Strict data typing in Using ActionScript in Flash Note You must also use var when declaring properties inside class definitions in external scripts Class files also support public private and static variable scopes See Creating Custom Classes with ActionScript 2 0 in Using ActionScript in Flash and see private public and...

Страница 996: ...ideo stream first place a Video object on the Stage Then use Video attachVideo to attach the video stream to the Video object To place a Video object on the Stage 1 If the Library panel isn t visible select Window Library to display it 2 Add an embedded Video object to the library by clicking the Options menu on the right side of the Library panel title bar and selecting New Video 3 Drag the Video...

Страница 997: ...tains only audio the audio portion of an FLV files is played automatically when the NetStream play command is issued If you want to control the audio associated with an FLV file you can use MovieClip attachAudio to route the audio to a movie clip you can then create a Sound object to control some aspects of the audio For more information see MovieClip attachAudio Example The following example play...

Страница 998: ...t having to hide the Video object Example The following example pauses and clears video1 flv that is playing in a Video object called my_video when the user clicks the pause_btn instance var pause_btn Button var my_video Video my_video is a Video object on the Stage var my_nc NetConnection new NetConnection my_nc connect null var my_ns NetStream new NetStream my_nc my_video attachVideo my_ns my_ns...

Страница 999: ...g example plays video1 flv in the my_video video object and lets the user change the deblocking filter behavior on video1 flv Add a video object called my_video and a ComboBox instance called deblocking_cb to your file and then add the following ActionScript to your FLA or AS file var deblocking_cb mx controls ComboBox var my_video Video my_video is a Video object on the Stage var my_nc NetConnect...

Страница 1000: ...d with a code property of NetStream Buffer Full If you call it when the code property is NetStream Play Start the height and width values will be 0 because the Video object doesn t yet have the height and width of the loaded FLV file var my_nc NetConnection new NetConnection my_nc connect null var my_ns NetStream new NetStream my_nc my_mc my_video attachVideo my_ns my_ns play video1 flv my_ns onSt...

Страница 1001: ...Video height 1001 my_mc _height my_mc my_video height See also MovieClip _height Video width ...

Страница 1002: ...operty that is applied to the video my_video when it plays in a SWF file Create a button called smoothing_btn and add the following ActionScript to your FLA or AS file this createTextField smoothing_txt this getNextHighestDepth 0 0 100 22 smoothing_txt autoSize true var my_nc NetConnection new NetConnection my_nc connect null var my_ns NetStream new NetStream my_nc my_video attachVideo my_ns my_ns...

Страница 1003: ...he same as the Camera width property of the Camera object that is capturing the video stream For FLV files this value is the width of the file that was exported as an FLV file You may want to use this property for example to ensure that the user is seeing the video at the same size at which it was captured regardless of the actual size of the Video object on the Stage Example See the examples for ...

Страница 1004: ...ed to test for undefined values if someUndefinedVariable void 0 trace someUndefinedVariable is undefined The previous code can also be written in the following way if someUndefinedVariable undefined trace someUndefinedVariable is undefined Usage 2 In the following example a function that returns a value is defined using the Void return type which results in a compile time error function myFunction...

Страница 1005: ... is evaluated 2 If condition evaluates to true or a value that converts to the Boolean value true such as a nonzero number go to step 3 Otherwise the while statement is completed and execution resumes at the next statement after the while loop 3 Run the statement block statement s 4 Go to step 1 Looping is commonly used to perform an action while a counter variable is less than a specified value A...

Страница 1006: ...1006 Chapter 2 ActionScript Language Reference i 3 The following result is displayed in the Output panel 0 3 6 9 12 15 18 See also do while continue for for in ...

Страница 1007: ...ctionScript starts at the beginning of the scope chain specified by the object and searches for the identifier at each level of the scope chain in a specific order The scope chain used by the with statement to resolve identifiers starts with the first item in the following list and continues to the last item The object specified in the object parameter in the innermost with statement The object sp...

Страница 1008: ...op 3 The following code snippet shows how to write the preceding code without using a with statement someOther_mc _x 50 someOther_mc _y 100 someOther_mc gotoAndStop 3 The with statement is useful for accessing multiple items in a scope chain list simultaneously In the following example the built in Math object is placed at the front of the scope chain Setting Math as a default object resolves the ...

Страница 1009: ...L class Method Description XML addRequestHeader Adds or changes HTTP headers for POST operations XML appendChild Appends a node to the end of the specified object s child list XML cloneNode Clones the specified node and optionally recursively clones all children XML createElement Creates a new XML element XML createTextNode Creates a new XML text node XML getBytesLoaded Returns the number of bytes...

Страница 1010: ...ject XML nodeType The type of the specified node XML element or text node XML nodeValue The text of the specified node if the node is a text node XML parentNode Read only references the parent node of the specified node XML previousSibling Read only references the previous sibling in the parent node s child list XML status A numeric status code that indicates the success or failure of an XML docum...

Страница 1011: ...l any of the methods of the XML class Note Use the createElement and createTextNode methods to add elements and text nodes to an XML document tree Example The following example creates a new empty XML object var my_xml XML new XML The following example creates an XML object by parsing the XML text specified in the source parameter and populates the newly created XML object with the resulting XML d...

Страница 1012: ...ade to set the same header name each successive value replaces the value set in the previous call You cannot add or change the following standard HTTP headers using this method Accept Ranges Age Allow Allowed Connection Content Length Content Location Content Range ETag Host Last Modified Locations Max Forwards Proxy Authenticate Proxy Authorization Public Range Retry After Server TE Trailer Trans...

Страница 1013: ...node is placed in the new tree structure after it is removed from its existing parent node Example This example does the following things in the order shown Creates two empty XML documents doc1 and doc2 Creates a new node using the createElement method and appends it using the appendChild method to the XML document named doc1 Shows how to move a node using the appendChild method by moving the root...

Страница 1014: ... cloneNode true doc1 appendChild clone trace doc1 doc1 output doc1 root trace doc2 doc2 output doc2 root create a new node to append to root node named clone of doc1 var newNode XMLNode doc1 createElement newbie clone appendChild newNode trace doc1 doc1 output doc1 root newbie root ...

Страница 1015: ...ibute named color you would retrieve that attribute s value by using the color as the key index as the following code shows var myColor String doc firstChild attributes color Example The following example shows the XML attribute names create a tag called mytag with an attribute called name with value Val var doc XML new XML mytag name Val item mytag assign the value of the name attribute to variab...

Страница 1016: ...es create a new XML document var doc XML new XML create a root node var rootNode XMLNode doc createElement rootNode create three child nodes var oldest XMLNode doc createElement oldest var middle XMLNode doc createElement middle var youngest XMLNode doc createElement youngest add the rootNode as the root of the XML document tree doc appendChild rootNode add each of the child nodes as children of r...

Страница 1017: ... previousSibling all have a value of null If the deep parameter is set to false or the my_xml node has no child nodes firstChild and lastChild are also null Example The following example shows how to use the XML cloneNode method to create a copy of a node create a new XML document var doc XML new XML create a root node var rootNode XMLNode doc createElement rootNode create three child nodes var ol...

Страница 1018: ...added rootNode oldest middle middle youngest rootNode create a copy of rootNode using cloneNode to demonstrate a deep copy var rootClone XMLNode rootNode cloneNode true insert the clone which contains all child nodes to rootNode rootNode appendChild rootClone trace rootNode output with line breaks added rootNode oldest middle middle youngest rootNode oldest middle middle youngest rootNode rootNode...

Страница 1019: ...cument and checks its default content type create a new XML document var doc XML new XML trace the default content type trace doc contentType output application x www form urlencoded The following example defines an XML packet and sets the content type for the XML object The data is then sent to a server and shows a result in a browser window var my_xml XML new XML highscore name Ernie name score ...

Страница 1020: ...hat represents the element This method and the XML createTextNode method are the constructor methods for creating nodes for an XML object Example The following example creates three XML nodes using the createElement method create an XML document var doc XML new XML create three XML nodes using createElement var element1 XMLNode doc createElement element1 var element2 XMLNode doc createElement elem...

Страница 1021: ... nodes using the createTextNode method and places them into existing XML nodes create an XML document var doc XML new XML create three XML nodes using createElement var element1 XMLNode doc createElement element1 var element2 XMLNode doc createElement element2 var element3 XMLNode doc createElement element3 place the new nodes into the XML tree doc appendChild element1 element1 appendChild element...

Страница 1022: ...1022 Chapter 2 ActionScript Language Reference See also XML createElement ...

Страница 1023: ... XML parser is not a validating parser The DOCTYPE declaration is read by the parser and stored in the XML docTypeDecl property but no DTD validation is performed If no DOCTYPE declaration was encountered during a parse operation the XML docTypeDecl property is set to undefined The XML toString method outputs the contents of XML docTypeDecl immediately after the XML declaration stored in XML xmlDe...

Страница 1024: ...ode var rootNode XMLNode doc createElement rootNode create three child nodes var oldest XMLNode doc createElement oldest var middle XMLNode doc createElement middle var youngest XMLNode doc createElement youngest add the rootNode as the root of the XML document tree doc appendChild rootNode add each of the child nodes as children of rootNode rootNode appendChild oldest rootNode appendChild middle ...

Страница 1025: ...asterArray i j stringNode firstChild nodeValue To view the entire script see XML_languagePicker fla in the HelpExamples folder Windows Program Files Macromedia Flash MX 2004 Samples HelpExamples Macintosh HD Applications Macromedia Flash MX 2004 Samples HelpExamples See also XML appendChild XML insertBefore XML removeNode ...

Страница 1026: ... the parameter refers to a valid XML file using HTTP If you attempt to use this example to load a local file that resides on your hard disk this example will not work properly because in test movie mode Flash Player loads local files in their entirety create a new XML document var doc XML new XML var checkProgress function xmlObj XML var bytesLoaded Number xmlObj getBytesLoaded var bytesTotal Numb...

Страница 1027: ...otal Availability Flash Player 6 Usage my_xml getBytesTotal Number Parameters None Returns An integer Description Method returns the size in bytes of the XML document Example See example for XML getBytesLoaded See also XML getBytesLoaded ...

Страница 1028: ...s the code loops over each child node to display the name and value of the node Add the following ActionScript to your FLA or AS file var my_xml XML new XML login username hank username password rudolph password login if my_xml firstChild hasChildNodes use firstChild to iterate through the child nodes of rootNode for var aNode XMLNode my_xml firstChild firstChild aNode null aNode aNode nextSibling...

Страница 1029: ... shows XML prototype ignoreWhite true Example The following example loads an XML file with a text node that contains only white space the foyer tag comprises fourteen space characters To run this example create a text file named flooring xml and copy the following tags into it house kitchen ceramic tile kitchen bathroom linoleum bathroom foyer foyer house Create a new Flash document named flooring...

Страница 1030: ... will be preserved set the ignoreWhite property to false default value flooring ignoreWhite false output line breaks added for clarity house kitchen ceramic tile kitchen bathroom linoleum bathroom foyer foyer house The XML_blogTracker fla and XML_languagePicker fla files in the HelpExamples folder also contain a code example The following are typical paths to this folder Windows Program Files Macr...

Страница 1031: ...node into the XML object s child list before the beforeNode node If the beforeNode parameter is undefined or null the node is added using the appendChild method If beforeNode is not a child of my_xml the insertion fails Example The following example is an excerpt from the XML cloneNode example create a copy of the middle node using cloneNode var middle2 XMLNode middle cloneNode false insert the cl...

Страница 1032: ...ast item in the node s child list and ending with the first child of the node s child list create a new XML document var doc XML new XML create a root node var rootNode XMLNode doc createElement rootNode create three child nodes var oldest XMLNode doc createElement oldest var middle XMLNode doc createElement middle var youngest XMLNode doc createElement youngest add the rootNode as the root of the...

Страница 1033: ...ew XML document var doc XML new XML rootNode oldest middle youngest rootNode var rootNode XMLNode doc firstChild use lastChild to iterate through the child nodes of rootNode for var aNode XMLNode rootNode lastChild aNode null aNode aNode previousSibling trace aNode output youngest middle oldest See also XML appendChild XML insertBefore XML removeNode XMLNode class ...

Страница 1034: ...s at store someDomain com because both files are in the same superdomain of someDomain com In SWF files of any version running in Flash Player 7 or later the url parameter must be in exactly the same domain see Flash Player security features in Using ActionScript in Flash For example a SWF file at www someDomain com can load data only from sources that are also at www someDomain com If you want to...

Страница 1035: ...e XML object flooring onLoad function success trace flooring load the XML into the flooring object flooring load flooring xml For the contents of the flooring xml file and the output that this example produces see the example for XML ignoreWhite See also XML loaded XML onLoad ...

Страница 1036: ...ng example uses the XML loaded property in a simple script var my_xml XML new XML my_xml ignoreWhite true my_xml onLoad function success Boolean trace success success trace loaded my_xml loaded trace status my_xml status my_xml load http www flash mx com mm problems products xml Information displays in the Output panel when the onLoad handler invokes If the call completes successfully true display...

Страница 1037: ...s property cannot be used to manipulate child nodes use the appendChild insertBefore and removeNode methods to manipulate child nodes Example The following example is an excerpt from the example for the XML firstChild property and shows how you can use the XML nextSibling property to loop through an XML node s child nodes for var aNode XMLNode rootNode firstChild aNode null aNode aNode nextSibling...

Страница 1038: ...XMLNode doc createElement rootNode place the new node into the XML tree doc appendChild myNode create an XML text node using createTextNode var myTextNode XMLNode doc createTextNode textNode place the new node into the XML tree myNode appendChild myTextNode trace myNode nodeName trace myTextNode nodeName output rootNode null The following example creates a new XML packet If the root node has child...

Страница 1039: ...XML nodeName 1039 trace aNode nodeName t aNode firstChild nodeValue The following node names are displayed in the Output panel output username hank password rudolph See also XML nodeType ...

Страница 1040: ...L class only supports 1 ELEMENT_NODE and 3 TEXT_NODE Example The following example creates an element node and a text node and checks the node type of each create an XML document var doc XML new XML create an XML node using createElement var myNode XMLNode doc createElement rootNode place the new node into the XML tree doc appendChild myNode create an XML text node using createTextNode Integer val...

Страница 1041: ...Type 1041 var myTextNode XMLNode doc createTextNode textNode place the new node into the XML tree myNode appendChild myTextNode trace myNode nodeType trace myTextNode nodeType output 1 3 See also XML nodeValue ...

Страница 1042: ...appendChild myNode create an XML text node using createTextNode var myTextNode XMLNode doc createTextNode myTextNode place the new node into the XML tree myNode appendChild myTextNode trace myNode nodeValue trace myTextNode nodeValue output null myTextNode The following example creates and parses an XML packet The code loops through each child node and displays the node value using the firstChild ...

Страница 1043: ...0 i my_xml firstChild childNodes length i trace t my_xml firstChild childNodes i firstChild nodeValue The following information is displayed in the Output panel using firstChild morton good amp evil using firstChild nodeValue morton good evil See also XML nodeType ...

Страница 1044: ... of using the Flash XML parser The src parameter is a string that contains XML text downloaded from the server unless an error occurs during the download in which case the src parameter is undefined By default the XML onData event handler invokes XML onLoad You can override the XML onData event handler with custom behavior but XML onLoad is not called unless you call it in your implementation of X...

Страница 1045: ... default implementation you must assign a function that contains custom actions Example The following example includes ActionScript for a simple e commerce storefront application The sendAndLoad method transmits an XML element that contains the user s name and password and uses an XML onLoad handler to process the reply from the server var login_str String login username username_txt text password...

Страница 1046: ... the parent node of the username node in the Output panel var my_xml XML new XML login username morton username password good amp evil password login first child is the login node var rootNode XMLNode my_xml firstChild first child of the root is the username node var targetNode XMLNode rootNode firstChild trace the parent node of targetNode nodeName is targetNode parentNode nodeName trace contents...

Страница 1047: ...XML object with the resulting XML tree Any existing trees in the XML object are discarded Example The following example creates and parses an XML packet var xml_str String state name California city San Francisco city state defining the XML source within the XML constructor var my1_xml XML new XML xml_str trace my1_xml firstChild attributes name output California defining the XML source using the ...

Страница 1048: ...s sibling node This property cannot be used to manipulate child nodes use the XML appendChild XML insertBefore and XML removeNode methods to manipulate child nodes Example The following example is an excerpt from the example for the XML lastChild property and shows how you can use the XML previousSibling property to loop through an XML node s child nodes for var aNode XMLNode rootNode lastChild aN...

Страница 1049: ... packet and then deletes the specified XML object and its descendant nodes var xml_str String state name California city San Francisco city state var my_xml XML new XML xml_str var cityNode XMLNode my_xml firstChild firstChild trace before XML removeNode n my_xml cityNode removeNode trace trace after XML removeNode n my_xml output line breaks added for clarity before XML removeNode state name Cali...

Страница 1050: ...nal if you do not specify a window parameter it is the same as specifying _self Returns Nothing Description Method encodes the specified XML object into an XML document and sends it to the specified URL using the POST method in a browser The Flash test environment only uses the GET method Example The following example defines an XML packet and sets the content type for the XML object The data is t...

Страница 1051: ... a SWF file at www someDomain com can load data from sources at store someDomain com because both files are in the same superdomain of someDomain com In SWF files of any version running in Flash Player 7 or later the url parameter must be in exactly the same domain see Flash Player security features in Using ActionScript in Flash For example a SWF file at www someDomain com can load data only from...

Страница 1052: ...y_xml ignoreWhite true myLoginReply_xml onLoad myOnLoad my_xml sendAndLoad http www flash mx com mm login_xml cfm myLoginReply_xml function myOnLoad success Boolean if success if myLoginReply_xml firstChild nodeName packet myLoginReply_xml firstChild attributes success true gotoAndStop loggedIn else gotoAndStop loginFailed else gotoAndStop connectionFailed See also XML send XML load XML loaded XML...

Страница 1053: ...as not properly terminated 9 A start tag was not matched with an end tag 10 An end tag was encountered without a matching start tag Example The following example loads an XML packet into a SWF file A status message displays depending on whether the XML loads and parses successfully Add the following ActionScript to your FLA or AS file var my_xml XML new XML my_xml onLoad function success Boolean i...

Страница 1054: ...rMessage Out of memory break case 8 errorMessage An attribute value was not properly terminated break case 9 errorMessage A start tag was not matched with an end tag break case 10 errorMessage An end tag was encountered without a matching start tag break default errorMessage An unknown error has occurred break trace status my_xml status errorMessage else trace Unable to load parse XML status my_xm...

Страница 1055: ...tring method outputs the document s XML declaration stored in the XML xmlDecl property followed by the document s DOCTYPE declaration stored in the XML docTypeDecl property followed by the text representation of all XML nodes in the object The XML declaration is not output if the XML xmlDecl property is undefined The DOCTYPE declaration is not output if the XML docTypeDecl property is undefined Ex...

Страница 1056: ... field displays properties of the XML packet that loads into the SWF file The doc type declaration displays in my_txt Add the following ActionScript to your FLA or AS file var my_fmt TextFormat new TextFormat my_fmt font _typewriter my_fmt size 12 my_fmt leftMargin 10 this createTextField my_txt this getNextHighestDepth 0 0 Stage width Stage height my_txt border true my_txt multiline true my_txt w...

Страница 1057: ...XML xmlDecl 1057 See also XML docTypeDecl XML toString ...

Страница 1058: ...ng XML class entries See also XML class Property method or collection Corresponding XML class entry appendChild XML appendChild attributes XML attributes childNodes XML childNodes cloneNode XML cloneNode firstChild XML firstChild hasChildNodes XML hasChildNodes insertBefore XML insertBefore lastChild XML lastChild nextSibling XML nextSibling nodeName XML nodeName nodeType XML nodeType nodeValue XM...

Страница 1059: ...his restriction is that the server daemons that communicate with the XMLSocket object must also be assigned to port numbers greater than or equal to 1024 Port numbers below 1024 are often used by system services such as FTP Telnet and HTTP so XMLSocket objects are barred from these ports for security reasons The port number restriction limits the possibility that these resources will be inappropri...

Страница 1060: ...to a server Example The following example creates an XMLSocket object var socket XMLSocket new XMLSocket Method Description XMLSocket close Closes an open socket connection XMLSocket connect Establishes a connection to the specified server XMLSocket send Sends an XML object to the server Event handler Description XMLSocket onClose Invoked when an XMLSocket connection is closed XMLSocket onConnect ...

Страница 1061: ...turns Nothing Description Method closes the connection specified by XMLSocket object Example The following simple example creates an XMLSocket object attempts to connect to the server and then closes the connection var socket XMLSocket new XMLSocket socket connect null 2000 socket close See also XMLSocket connect ...

Страница 1062: ...e com specifying null for the host parameter is the same as entering the IP address for www yoursite com In SWF files running in a version of the player earlier than Flash Player 7 host must be in the same superdomain as the SWF file that is issuing this call For example a SWF file at www someDomain com can load variables from a SWF file at store someDomain com because both files are in the same s...

Страница 1063: ...e a connection could not be established Example The following example uses XMLSocket connect to connect to the host where the SWF file resides and uses trace to display the return value indicating the success or failure of the connection var socket XMLSocket new XMLSocket socket onConnect function success Boolean if success trace Connection succeeded else trace Connection failed if socket connect ...

Страница 1064: ...ction is closed by the server The default implementation of this method performs no actions To override the default implementation you must assign a function containing custom actions Example The following example executes a trace statement if an open connection is closed by the server var socket XMLSocket new XMLSocket socket connect null 2000 socket onClose function trace Connection to server lo...

Страница 1065: ...ing the constructor method the script defines the custom function to be executed when the onConnect event handler is invoked The function controls the screen to which users are taken depending on whether a connection is successfully established If the connection is successfully made users are taken to the main chat screen on the frame labeled startChat If the connection is not successful users go ...

Страница 1066: ...1066 Chapter 2 ActionScript Language Reference if socket connect null 2000 gotoAndStop connectionFailed else gotoAndStop waitForConnection See also function XMLSocket connect ...

Страница 1067: ...s is a useful if you re transmitting arbitrarily formatted data packets and you d prefer to manipulate the data directly when it arrives rather than have Flash Player parse the data as XML By default the XMLSocket onData method invokes the XMLSocket onXML method If you override XMLSocket onData with custom behavior XMLSocket onXML is not called unless you call it in your implementation of XMLSocke...

Страница 1068: ...tion was established if this is the first message received Each batch of parsed XML is treated as a single XML document and passed to the onXML method The default implementation of this method performs no actions To override the default implementation you must assign a function containing actions that you define Example The following function overrides the default implementation of the onXML metho...

Страница 1069: ...ately but the data may be transmitted at a later time The XMLSocket send method does not return a value indicating whether the data was successfully transmitted If the myXMLSocket object is not connected to the server using XMLSocket connect the XMLSocket send operation will fail Example The following example shows how you could specify a user name and password to send the XML object my_xml to the...

Страница 1070: ...1070 Chapter 2 ActionScript Language Reference ...

Страница 1071: ...71 APPENDIX Deprecated Language Elements The evolution of ActionScript has deprecated many elements of the language This appendix lists the deprecated items in alphabetical order and suggests alternatives ...

Страница 1072: ... string2 A string Returns Nothing Description Operator concatenates two or more strings The add operator replaces the Flash 4 operator Flash Player 4 files that use the operator are automatically converted to use the add operator for string concatenation when brought into the Flash 5 or later authoring environment Use the add operator to concatenate strings if you are creating content for Flash Pl...

Страница 1073: ...e logical AND operator Usage condition1 and condition2 Parameters condition1 condition2 Conditions or expressions that evaluate to true or false Returns Nothing Description Operator performs a logical AND operation in Flash Player 4 If both expressions evaluate to true the entire expression is true See also logical AND ...

Страница 1074: ...y to apply anti aliasing this smooths bitmaps if the SWF file does not contain animation and is the default value Specify 0 low quality to prevent anti aliasing Example Add a button instance on the Stage and name it myBtn_btn Draw an oval on the Stage using the Oval tool that has a stroke and fill color Select Frame 1 and add the following ActionScript using the Actions panel myBtn_btn onRelease f...

Страница 1075: ...led frame without moving the playhead to that frame Local variables do not exist after the script executes If variables are not declared inside a block but the action list was executed with a call action the variables are local and expire at the end of the current list If variables are not declared inside a block and the current action list was not executed with the call action the variables are i...

Страница 1076: ... favor of String fromCharCode Usage chr number Parameters number An ASCII code number Returns Nothing Description String function converts ASCII code numbers to characters Example The following example converts the number 65 to the letter A and assigns it to the variable myVar myVar chr 65 See also String fromCharCode ...

Страница 1077: ...operator Usage expression1 eq expression2 Parameters expression1 expression2 Numbers strings or variables Returns Nothing Description Operator comparison compares two expressions for equality and returns a value of true if the string representation of expression1 is equal to the string representation of expression2 false otherwise See also equality ...

Страница 1078: ... or equal to operator Usage expression1 ge expression2 Parameters expression1 expression2 Numbers strings or variables Returns Nothing Description Operator comparison compares the string representation of expression1 with the string representation of expression2 and returns true if expression1 is greater than or equal to expression2 false otherwise See also greater than or equal to ...

Страница 1079: ... the greater than operator Usage expression1 gt expression2 Parameters expression1 expression2 Numbers strings or variables Description Operator comparison compares the string representation of expression1 with the string representation of expression2 and returns true if expression1 is greater than expression2 false otherwise See also greater than ...

Страница 1080: ... file Specify 2 best quality to apply high quality with bitmap smoothing always on Specify 1 high quality to apply anti aliasing this will smooth bitmaps if the SWF file does not contain animation Specify 0 low quality to prevent anti aliasing Example The following ActionScript is placed on the main Timeline and sets the global quality property to always apply bitmap smoothing in non animated file...

Страница 1081: ... Operator inequality tests for the exact opposite of the equality operator If expression1 is equal to expression2 the result is false As with the equality operator the definition of equal depends on the data types being compared Numbers strings and Boolean values are compared by value Objects arrays and functions are compared by reference Variables are compared by value or by reference depending o...

Страница 1082: ... label that must be loaded before the next statement is executed statement s The instructions to execute if the specified scene or scene and frame are loaded Returns Nothing Description Action checks whether the contents of a specific frame are available locally Use ifFrameLoaded to start playing a simple animation while the rest of the SWF file downloads to the local computer The difference betwe...

Страница 1083: ...arameters value A number to be rounded to an integer Returns Nothing Description Function converts a decimal number to an integer value by truncating the decimal value This function is equivalent to Math floor if the value parameter is positive and Math ceil if the value parameter is negative See also Math floor Math ceil ...

Страница 1084: ...in favor of the less than or equal to operator Usage expression1 le expression2 Parameters expression1 expression2 Numbers strings or variables Returns Nothing Description Operator comparison compares expression1 to expression2 and returns a value of true if expression1 is less than or equal to expression2 false otherwise See also less than or equal to ...

Страница 1085: ...to perform the same operations Usage length expression length variable Parameters expression A string variable The name of a variable Returns The length of the specified string or variable Description String function returns the length of the specified string or variable Example The following example returns the length of the string Hello length Hello The result is 5 See also string delimiter Stri...

Страница 1086: ...as deprecated in Flash 5 in favor of the less than operator Usage expression1 lt expression2 Parameters expression1 expression2 Numbers strings or variables Description Operator comparison compares expression1 to expression2 and returns true if expression1 is less than expression2 false otherwise See also less than ...

Страница 1087: ...ll Description Read only property indicates the line number of the top line of visible text in a text field when the bottom line in the field is also visible The maxscroll property works with the scroll property to control how information appears in a text field This property can be retrieved but not modified See also TextField maxscroll TextField scroll ...

Страница 1088: ...s function was deprecated in favor of the String fromCharCode method Usage mbchr number Parameters number The number to convert to a multibyte character Returns A string Description String function converts an ASCII code number to a multibyte character See also String fromCharCode ...

Страница 1089: ...lability Flash Player 4 This function was deprecated in favor of the String class Usage mblength string Parameters string A string Returns A number Description String function returns the length of the multibyte character string ...

Страница 1090: ...function was deprecated in Flash 5 in favor of String charCodeAt Usage mbord character Parameters character The character to convert to a multibyte number Returns A number Description String function converts the specified character to a multibyte number See also String fromCharCode ...

Страница 1091: ...rs value The multibyte string from which to extract a new multibyte string index The number of the first character to extract count The number of characters to include in the extracted string not including the index character Returns A string Description String function extracts a new multibyte character string from a multibyte character string See also String substr ...

Страница 1092: ...file Specify 2 best quality to apply high quality with bitmap smoothing always on Specify 1 high quality to apply anti aliasing this will smooth bitmaps if the SWF file does not contain animation Specify 0 low quality to prevent anti aliasing This property can overwrite the global _highquality property Example The following ActionScript specifies that best quality anti aliasing should be applied t...

Страница 1093: ... in favor of the inequality operator Usage expression1 ne expression2 Parameters expression1 expression2 Numbers strings or variables Returns A Boolean value Description Operator comparison compares expression1 to expression2 and returns true if expression1 is not equal to expression2 false otherwise See also inequality ...

Страница 1094: ...yer 4 This operator was deprecated in favor of the logical NOT operator Usage not expression Parameters expression A variable or other expression that converts to a Boolean value Description Operator performs a logical NOT operation in Flash Player 4 See also logical NOT ...

Страница 1095: ...cal OR operator Usage condition1 or condition2 Parameters condition1 2 An expression that evaluates to true or false Returns Nothing Description Operator evaluates condition1 and condition2 and if either expression is true the whole expression is true See also logical OR bitwise OR ...

Страница 1096: ... function was deprecated in favor of the methods and properties of the String class Usage ord character Parameters character The character to convert to an ASCII code number Returns Nothing Description String function converts characters to ASCII code numbers See also String class ...

Страница 1097: ...of Math random Usage random value Parameters value An integer Returns An integer Description Function returns a random integer between 0 and one less than the integer specified in the value parameter Example The following use of random returns a value of 0 1 2 3 or 4 random 5 See also Math random ...

Страница 1098: ...croll property defines where the text field begins displaying content after you set it Flash Player updates it as the user scrolls through the text field The scroll property is useful for directing users to a specific paragraph in a long passage or creating scrolling text fields This property can be retrieved and modified Example The following code is attached to an Up button that scrolls the text...

Страница 1099: ...e string from which to extract the new string index The number of the first character to extract count The number of characters to include in the extracted string not including the index character Returns Nothing Description String function extracts part of a string This function is one based whereas the String object methods are zero based See also String substr ...

Страница 1100: ...particular frame in that clip For example you might assign tellTarget to buttons that stop or start movie clips on the Stage or prompt movie clips to jump to a particular frame In Flash 5 or later you can use dot notation instead of the tellTarget action You can use the with action to issue multiple actions to the same Timeline You can use the with action to target any object whereas the tellTarge...

Страница 1101: ...01 If you need to issue multiple commands to the ball instance you can use the with action as shown in the following statement on release with _parent ball gotoAndPlay 2 _alpha 15 _xscale 50 _yscale 50 See also with ...

Страница 1102: ...ghquality Description Property global specifies the level of anti aliasing applied to the current SWF file Specify 2 best quality to apply high quality with bitmap smoothing always on Specify 1 high quality to apply anti aliasing this will smooth bitmaps if the SWF file does not contain animation Specify 0 low quality to prevent anti aliasing See also _quality ...

Страница 1103: ...s Nothing Description Function turns anti aliasing on and off in Flash Player Anti aliasing smooths the edges of objects and slows down SWF playback This action affects all SWF files in Flash Player Example The following code could be applied to a button that when clicked would toggle anti aliasing on and off on release toggleHighQuality See also _highquality _quality ...

Страница 1104: ...1104 Appendix Deprecated Language Elements ...

Отзывы: