actionscript 2 - download.e-bookshelf.de fileabout the authors. nathan derksen. nathan derksen is a...

30
Beginning ActionScript 2.0 Nathan Derksen and Jeff Berg

Upload: others

Post on 15-Sep-2019

5 views

Category:

Documents


0 download

TRANSCRIPT

  • Beginning ActionScript 2.0

    Nathan Derksen and Jeff Berg

    01_577689 ffirs.qxp 3/15/06 10:54 PM Page iii

    File AttachmentC1.jpg

  • 01_577689 ffirs.qxp 3/15/06 10:54 PM Page ii

  • Beginning ActionScript 2.0

    01_577689 ffirs.qxp 3/15/06 10:54 PM Page i

  • 01_577689 ffirs.qxp 3/15/06 10:54 PM Page ii

  • Beginning ActionScript 2.0

    Nathan Derksen and Jeff Berg

    01_577689 ffirs.qxp 3/15/06 10:54 PM Page iii

  • Beginning ActionScript 2.0Published byWiley Publishing, Inc.10475 Crosspoint BoulevardIndianapolis, IN 46256www.wiley.com

    Copyright © 2006 by Wiley Publishing, Inc., Indianapolis, Indiana

    Published simultaneously in Canada

    ISBN-13: 978-0-7645-7768-0ISBN-10: 0-7645-7768-9

    Manufactured in the United States of America

    10 9 8 7 6 5 4 3 2 1

    1MA/QT/QU/QW/IN

    Library of Congress Cataloging-in-Publication Data:Derksen, Nathan, 1974-Beginning ActionScript 2.0 / Nathan Derksen and Jeff Berg.

    p. cm.“Wiley Technology Publishing.”Includes index.ISBN-13: 978-0-7645-7768-0 (paper/website)ISBN-10: 0-7645-7768-9 (paper/website)1. Computer animation. 2. Flash (Computer file) 3. Web sites--Design. 4. ActionScript (Computer program language) I.Berg, Jeff, 1975- II. Title. TR897.7.D493 2006006.6’96 –– dc22

    No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means,electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 ofthe 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorizationthrough payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the LegalDepartment, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, oronline at http://www.wiley.com/go/permissions.

    LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REPRESEN-TATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OFTHIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WAR-RANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BYSALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BESUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER ISNOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF PROFES-SIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BESOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HERE-FROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATIONAND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THEPUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOM-MENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED INTHIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN ANDWHEN IT IS READ.

    For general information on our other products and services please contact our Customer Care Department within theUnited States at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.

    Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are trade-marks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries,and may not be used without written permission. Macromedia Flash 8 copyright © 1995-2003. Macromedia, Inc., 600Townsend Street, San Francisco, CA 94103 USA. All Rights Reserved. Macromedia Flash are trademarks or registeredtrademarks of Macromedia, Inc. in the United States and/or other countries. All other trademarks are the property of theirrespective owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book.

    Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be availablein electronic books.

    01_577689 ffirs.qxp 3/15/06 10:54 PM Page iv

    www.wiley.com

  • About the Authors

    Nathan DerksenNathan Derksen is a Web media architect working in IBM’s Global Services division. Nathan has morethan 6 years of experience with IBM, and 9 years’ experience in the field of Web development. Mr. Derksenwas the technical editor for the book Animation and Effects with Macromedia Flash MX 2004 (Jen DeHaan,Macromedia Press), and is a moderator on the Macromedia Flash forum at www.flash8forums.com.Nathan can be reached through his personal site at www.nathanderksen.com.

    Jeff Berg Jeff Berg is a patent-winning digital media designer and Flash developer. He leads the development ofuser interfaces for rich Internet applications. Jeff leverages a fine arts degree to approach interface designand programming with problem-solving creativity. His user-centric approach includes self-imposedstandards for user experience, usability, and information design. Jeff’s visual background provides aunique position to work on projects with visual design concerns while maintaining concepts of designpatterns and object-oriented programming. Jeff currently is focusing on museum and public space pro-jects utilizing pervasive devices in handheld kiosk solutions. He lives in Chicago with his wife Kara andchildren Cary and Evie. Jeff maintains a web site at www.memoryprojector.com.

    01_577689 ffirs.qxp 3/15/06 10:54 PM Page v

  • For the love of my life, Renée.For my parents and my brother.

    For my dear grandpa, Otto.

    —Nathan Derksen

    To my wife Kara, my son Cary, and my daughter Evie.Thank you.

    —Jeff Berg

    01_577689 ffirs.qxp 3/15/06 10:54 PM Page vi

  • CreditsExecutive EditorChris Webb

    Development EditorsKelly HenthorneMaryann Steinhart

    Technical EditorSean Christmann

    Production EditorPamela Hanley

    Copy EditorKim Cofer

    Editorial ManagerMary Beth Wakefield

    Production ManagerTim Tate

    Vice President and Executive Group PublisherRichard Swadley

    Vice President and PublisherJoseph B. Wikert

    Project CoordinatorRyan Steffen

    Graphics and Production SpecialistsDenny HagerJennifer HeleineAlicia B. South

    Quality Control TechnicianLaura Albert

    Media Development Project SupervisorShannon Walters

    Media Development SpecialistAngela Denny

    Media Development CoordinatorLaura Atkinson

    Proofreading and IndexingTechbooks

    01_577689 ffirs.qxp 3/15/06 10:54 PM Page vii

  • Acknowledgments

    There are too many people to count who have given me support and well wishes as I have worked awayon this book. I would first like to acknowledge my parents for their constant love and support. Theyhave helped to make me who I am. They also inspired me to pursue computing science as a career, forwhich I am eternally grateful. I would also like to acknowledge my fiancée, Renée. She has beensupremely caring, supportive, and patient, has given me encouragement when I needed it. Through heractions she has been brought even closer to me than I could have imagined.

    I would also like to acknowledge Jen DeHaan (www.deseloper.com), who gave me the generous gift ofthe opportunity to write this book, as well as providing me with a forum to help the Flash developercommunity. I am very grateful for her generosity. I am also grateful for the whole support team at Wiley,including my editor, Maryann Steinhart, for her tireless efforts to make this book happen, and my tech-nical editor, Sean Christmann, who helped me with many valuable suggestions for improvementsthroughout the book.

    There is no way I could undertake the effort of writing this book on my own. A big thank-you goes toJeff Berg, who took on the daunting task of writing half of this book. He has been a great person to workwith, both with the book and at IBM: Jeff has always been available to bounce ideas off of, is very cre-ative with his solutions, and loves playing with the technology. He has also been a support on a personallevel and a friend.

    Thank you to Greg Charbonneau for making the time to take my photo for the cover. It was through thecamera I initially bought from him that I earnestly started photography as a hobby. Thank you to all myfriends and co-workers who regularly asked me about my book, and to my manager Elvyna who sup-ported my writing efforts. Finally, thank you also for all those in the Flash Lounge who have been mychampions, and who have been chomping at the bit to get an autographed copy of the book. At last it isready!

    —Nathan Derksen

    I want to thank my co-author, Nathan Derksen, for his support and guidance. Nathan, your attitude,knowledge, and dedication are an inspiration. Also wish to thank Jack Blanchard. Jack, you taught mewhat an if statement was so many years ago, and you continue to guide me to new discoveries.

    I could not have completed this project without the patient support of my wife Kara, the inspirationfrom my son Cary, and joy from my daughter Evie.

    —Jeff Berg

    01_577689 ffirs.qxp 3/15/06 10:54 PM Page viii

  • Contents

    Acknowledgments viiiIntroduction xxv

    Chapter 1: Getting Started with Macromedia Flash 1

    Introducing the Development Environment 1Tools Panel 2Properties Panel 2Timeline 3Keyframes and Animation 3

    About the Library and Symbols 4Working with Buttons 5Working with Movie Clips 7About Layers, Depth, and Levels 8

    Setting Up Your Scripting Environment 8Introducing the Actions Panel 8Exploring ActionScript Preferences 9

    Automatic Indentation 9Tab Size 10Code Hints 10Font 10Color 11ActionScript 2.0 Settings 11

    Exploring Auto Format Preferences 12Publishing a Project 13

    The Flash Tab 14The HTML Tab 15The Image Tabs 15

    Options for Detecting the Flash Player 16Summary 18Exercises 18

    Chapter 2: Getting Started with ActionScript 2.0 19

    Understanding Statements 19Using Simple Statements 19Using Compound Statements 20

    02_577689 ftoc.qxp 3/15/06 10:55 PM Page ix

  • x

    Contents

    Understanding Operators 20Using Operator Precedence 22Exploring Operator Associativity 22Understanding the Common Operators 23

    Using White Space 25Using Comments 26Introducing Variables 27

    Assigning Data to a Variable 28Viewing the Contents of a Variable 28Passing Data from Variable to Variable 29Naming Variables 29Introducing Constants 30Using Strong Variable Typing 30Exploring Data Types 33

    Distinguishing Primitive and Composite Data Types 34Passing by Value Versus Pass by Reference 35Duplicating Data for Composite Types 36

    Using Dot Syntax 37Discerning Special Variables and Keywords 38

    _root 38_level0 39_global 39this 39

    Working with Collections of Data 40Understanding Arrays 40

    concat() 42join() 43push() 43sort() 43splice() 45

    Exploring Associative Arrays and Objects 45Viewing the Object Class as a Container 46Revisiting the Associative Array 47

    Summary 50Exercises 51

    Chapter 3: Understanding ActionScript Expressions and Loops 53

    Making Decisions 53Expressions 54Building Expressions 55Using if..then..else 59Using switch..case 60

    02_577689 ftoc.qxp 3/15/06 10:55 PM Page x

  • xi

    Contents

    Understanding Loops 66The for Loop 66The for..in Loop 69The while Loop 70The do..while Loop 72Dealing with Loop Errors 76

    Off-by-One Errors 76Infinite Loops 77

    Summary 80Exercises 80

    Chapter 4: Exploring ActionScript Functions and Scope 83

    Functions 83Functions in Action 86An Alternate Syntax 87Passing Functions as Arguments 88

    Variable Scope 92Managing Variable Scope 95Side Effects 96

    Summary 98Exercises 99

    Chapter 5: Getting Started with Coding 101

    Introduction to Object-Oriented Programming 101Defining Object-Oriented Programming 101

    Classes Versus Objects 103Class Inheritance 106

    Goals of Object-Oriented Programming 106Coding Best Practices 107

    Understanding Variable Naming 107Making Variable Names Readable 107Making Boolean Variables into Questions 108Avoiding Reserved Words 108Distinguishing Variable Names from Class Names 110

    Variable Typing 110Type Casting 112

    Commenting 116Formatting Code 118Understanding Variable Scope 119

    Declaring All Global and Timeline Variables in One Place 119Creating an Object Just for Data 120

    02_577689 ftoc.qxp 3/15/06 10:55 PM Page xi

  • xii

    Contents

    Creating Access Functions 120Managing Data with Custom Classes 121

    Accessing Variables in Another Timeline 122Creating Your Own Functions 129

    Strongly Typing Function Arguments 129Avoiding Hard-Coded Movie Clip References 130Declaring Return Values 130Avoiding Oversized Functions 131Avoiding Entanglement 131Avoiding Duplication 133

    Summary 140Exercises 141

    Chapter 6: Setting Up Flash Projects 143

    Setting Up the Library 143Working with Bitmap Images 144

    Keep Images Organized on the Desktop 145Keep Images Organized in the Library 145Embed Images into Movie Clips 145

    Nesting Sections within a Movie Clip 148Using Keyframes to Manage Application State 149Keeping Code in External Files 151Using Script to Manage Application State 153

    Summary 157Exercise 157

    Chapter 7: Controlling Movie Clips 159

    The Movie Clip Revealed 159MovieClip Class Methods 160

    attachBitmap() 161attachMovie() 162beginFill() 162clear() 163createEmptyMovieClip() 163createTextField() 163duplicateMovieClip() 163endFill() 164getBytesLoaded() 164getBytesTotal() 165getURL() 166gotoAndPlay() 167hitTest() 167

    02_577689 ftoc.qxp 3/15/06 10:55 PM Page xii

  • xiii

    Contents

    lineStyle() 168lineTo() 169loadMovie() 169moveTo() 170play() 170removeMovieClip() 170setMask() 171startDrag() 171stop() 172stopDrag() 172swapDepths() 173unloadMovie() 173

    MovieClip Class Properties 174MovieClip Class Events 176

    Creating Movie Clips On-the-Fly 178Attaching Movie Clips from the Library 181Loading External Movies 184

    Loading Movies into Levels 184Loading Media into Existing Movie Clips 185Fully Qualified, Absolute, and Relative URLs 186

    Using Movie Clips as Masks 190Improving Movie Clip Performance 196

    Bitmap Caching 196Transparency 196Filters and Blending Modes 197Full Screen 197

    Summary 197Exercises 198

    Chapter 8: Pre-Loading Movies 199

    Using a Custom Pre-Loader 199Polling with onEnterFrame() Versus setInterval() 204Understanding the MovieClipLoader Class 205

    MovieClipLoader Class Events 205MovieClipLoader Class Methods 206

    addListener() 206getProgress() 207loadClip() 207removeListener() 208unloadClip() 208

    Implementing the MovieClipLoader Class 209

    02_577689 ftoc.qxp 3/15/06 10:55 PM Page xiii

  • xiv

    Contents

    Examining the Loader and ProgressBar Components 212Loader Component Method, Properties, and Events 212ProgressBar Component Method, Properties, and Events 213Implementing the Loader and ProgressBar Components 215

    Strategies for Using Pre-Loaders 217The Monolithic Movie Approach 217The Split-Up Movie Approach 221

    Summary 225Exercises 226

    Chapter 9: Working with Components 229

    New to Version 2.0 229Exploring Components 230

    Data Components 230FLV Playback and FLV Playback Custom UI Components 231Media Components for Flash Players 6 and 7 233User Interface Components 233

    Placing Components Manually 234Placing Components on the Stage with Script 237Scripting Components 242Summary 245Exercises 245

    Chapter 10: Interacting with the User 247

    Handling Events 247Creating a Listener Object 247Variation of Creating a Listener Object 254Creating a Listener Function 255Which Listener Technique Should You Use? 257

    Attaching Multiple Listeners to Multiple Components 262Organizing the Listeners 263Handling Events from Multiple Sources 264

    Manually Invoking Events in a Component 270Summary 271Exercise 272

    Chapter 11: Controlling Components 273

    Introducing the Component Inspector Panel 273Creating Data Bindings between Components Using the Bindings Tab 275Using an XML File as a Data Source 277

    02_577689 ftoc.qxp 3/15/06 10:55 PM Page xiv

  • xv

    Contents

    Controlling Component Appearance 281Using setStyle() to Change Component Styles 282

    Setting Styles Globally 282Setting Styles for a Component Type 283Setting Styles Using Custom Classes 283Style Search Order 283Available Styles 284Alert Style Names 286Custom Date Classes 287

    Skinning Components 290Summary 294Exercises 295

    Chapter 12: Debugging Debugged 297

    Types of Bugs 297Compile-Time Bugs 297Logic Bugs 298

    If Statement Logic Errors 298Uninitialized Variables 299Off-by-One Errors 301Fence Post Errors 301Infinite Loops 302Numerical Precision Errors 302

    Develop to Debug 303Make Your Code Readable 303Develop in Small Chunks 304Use Small Functions 304

    The Science of Debugging 305Develop a Theory 305Run an Experiment 306

    Using the Built-In Debugger 306Using the Trace Statement 311Commenting Out Code 312

    Analyze the Results 313Summary 314Exercises 314

    Chapter 13: Working with Vector Graphics 319

    Using the Drawing API 320Tools for Drawing Vectors with ActionScript 320

    lineStyle() 320beginFill() 322

    02_577689 ftoc.qxp 3/15/06 10:55 PM Page xv

  • xvi

    Contents

    beginBitmapFill() 322beginGradientFill() 323endFill() 324moveTo() 324lineTo() 325curveTo() 325clear() 325

    Drawing Vectors with ActionScript 325The Matrix Object 334Summary 334Exercises 334

    Chapter 14: Applying Filter Effects 335

    DropShadowFilter 336BlurFilter 337GlowFilter 337BevelFilter 338GradientGlowFilter 339GradientBevelFilter 339ConvolutionFilter 340ColorMatrixFilter 343DisplacementMapFilter 345Cloning Filters 346Applying Multiple Filters 346Applying Blending Modes 352Summary 353Exercises 353

    Chapter 15: Working Directly with Bitmap Data 355

    The Bitmap Object’s Methods 356applyFilter() 356clone() 356colorTransform() 356copyChannel() 357copyPixels() 357dispose() 357draw() 358fillRect() 358floodFill() 358generateFilterRect() 359

    02_577689 ftoc.qxp 3/15/06 10:55 PM Page xvi

  • xvii

    Contents

    getColorBoundsRect() 359getPixel() 359getPixel32() 360hitTest() 360loadBitmap() 360merge() 361noise() 361paletteMap() 362perlinNoise() 362pixelDissolve() 363scroll() 364setPixel() 364setPixel32() 364threshold() 365

    The bitmapData Object’s Properties 365Converting a Movie Clip into a Bitmap Image 366Manipulating Bitmap Data 366Summary 368Exercises 368

    Chapter 16: Using ActionScript for Animation 369

    Scripted Versus Non-Scripted Animation 369Creating Animations Using Keyframes 370Creating Animations Using ActionScript 372

    Moving a Movie Clip Using onEnterFrame() 372Moving a Movie Clip Using setInterval() 374

    Frame-Based Versus Time-Based Animation 376The Effect of Movie Frame Rate on Animation 376Which Technique Should You Use? 379Choosing a Frame Rate or Update Interval 379

    Creating Animation with Movie Clips 380Animating Multiple Movie Clips 381Adding Random Behavior 382Introducing Easing and Acceleration 387

    Easing Out 387Easing In 391

    Summary 402Exercises 402

    02_577689 ftoc.qxp 3/15/06 10:55 PM Page xvii

  • xviii

    Contents

    Chapter 17: Automated Transitions 403

    The Tween Class 403Absolute Versus Relative Tweens 404Built-In Easing Classes and Methods 404Tween Class Methods 405

    continueTo() 406fforward() 407nextFrame() 407prevFrame() 408resume() 408rewind() 409start() 409stop() 409yoyo() 410

    Tween Class Properties and Events 410Playing Tweens in Parallel 414Playing Tweens in a Sequence 417

    Animating with the Drawing API 425Summary 432Exercises 432

    Chapter 18: Handling Text 433

    Creating Text Fields with ActionScript 434Field Instance Names Versus Field Variable Names 434System Fonts and Embedded Fonts 434Creating a Text Field On-the-Fly 434

    Working with Text Display Properties 436antiAliasType 436sharpness 437thickness 437

    Rich Text Formatting Options 439Using TextFormat 439New Text Format Options for Flash 8 440

    Justification 440letterSpacing 440Kerning 441

    A Note about setNewTextFormat() 445Displaying HTML 446Image and SWF Support in HTML Text Fields 448Font Support 450Hyperlinks and the ASFunction Method 452

    02_577689 ftoc.qxp 3/15/06 10:55 PM Page xviii

  • xix

    Contents

    Using Cascading Style Sheets 453Creating a Cascading Style Sheet Object 454Associating a StyleSheet with a Text Field 454Define Styles Directly on a StyleSheet Object 456

    How to Define Tags, Class, and Properties 458Using CSS with XML 459Scroll Text Options 461

    Scrolling Text Using the TextArea Component 462Scrolling Text Using the ScrollBar Component 463

    Summary 469Exercises 470

    Chapter 19: Using ActionScript for Media 471

    Managing Images 471Smart Preloading 473Using the MovieClipLoader to Preload an Image 473

    Managing Sound 474Sound Class Methods 474Sound Class Events and Properties 476Creating a Sound Object 477Loading Library Sounds 477Loading External MP3 Files 478

    Using ID3 Tags 478Available Properties in the V2 Tags 478

    Streaming MP3 Audio 480Starting, Stopping, and Tracking Sound 480Event Sounds 483Controlling Volume, setPan, and setTransform 483

    Volume 483Pan 483Transform 483

    Working with the Microphone 489Microphone Class Methods 489Microphone Class Properties and Events 490Microphone Activity 492netStream 494

    Summary 494Exercises 495

    Chapter 20: Managing Video 497

    Terms, Technology, and Quality 497Data Rate 497Progressive — HTTP 498

    02_577689 ftoc.qxp 3/15/06 10:55 PM Page xix

  • xx

    Contents

    Streaming — Flash Communication Server 498Video Keyframes 498Variable Bit Rate 499Interlacing 499Frame Rate 499

    Creating Flash Video 500Converting a Video 500Loading an External Video 503Exporting to Video 503Loading an External FLV File 504

    The netStream Class 504The Video Class 506

    clear() 506attachVideo() 506Video Class Properties 506

    Controlling Video Position 508Using Transparency within Video 510Working with Video Quality 513

    Deblocking and Deringing 513Scaling and Transparency 514

    Working with a Camera 515The Camera Class Methods, Properties, and Events 515Creating a Camera Object 516Displaying a Camera Feed as Video on the Stage 517Security Pop-Up Considerations 522

    Summary 522Exercises 522

    Chapter 21: Using ActionScript to Communicate with a Server 523

    External Data and Usability Concerns 523Data Latency: Asynchronous Communication 524Using LoadVars 524

    Ampersand-Delimited Data 525LoadVars Class Methods 525Creating a LoadVars Object 527LoadVars Event Handlers 529

    onData() 529onLoad() 529

    Loading and Parsing Raw Text 531Summary 534Exercises 534

    02_577689 ftoc.qxp 3/15/06 10:55 PM Page xx

  • xxi

    Contents

    Chapter 22: Reading XML 535

    Using the Built-in XML Class 535All Wrapped Up in Tags 535CDATA and Character Formats 537

    The Flash XML Class 537XML Class Methods 538XML Event Handlers 541

    onData() 541onLoad() 542

    ignoreWhite: A Special Property 542Loading External XML Files 542Measuring Bytes 545

    A Note about Security and Locality 545getBytesTotal Isn’t Working! 548

    Understanding the Parent-Child Node Relationship 549Navigating an Example Node Tree 549Using Attributes 552

    Using the XML Socket Connection 552The XML in the XMLSocket Class 553Null Bytes 553XMLSocket Class Methods and Events 553

    sendAndLoad 556Using HTTP GET and POST 557

    Apples and Oranges 558How Will You Know? 558

    Using the XML Component 559Explaining Cross-Domain Security 562

    Understanding Why Flash Uses Domain Policies 563Knowing When Policy Files Are Required 564Setting Up Policy Files 564I’m Offering Web Services; I Want to Allow Any Domain! 567

    Considering HTTPS 567Load a Policy File from a Subfolder 568Using a Policy File with an XML Socket, without HTTP 569

    Using Shims and Proxies 570Proxies: Forcing Data Access 570Shims: Allowing Script Access 571

    Summary 573Exercises 574

    02_577689 ftoc.qxp 3/15/06 10:55 PM Page xxi

  • xxii

    Contents

    Chapter 23: Communicating Between the Macromedia FlashPlug-in and the Browser 577

    LocalConnection 577Creating a localConnection Object 579Security 581

    Storing Data Locally with Shared Objects 582Acceptable Data Types 584Using Shared Objects as Cookies 585Working with the User 587Managing Disk Space 587Sharing SharedObects 588

    Giving a Flash Movie Data on Startup with FlashVars 588Introduction to Flash Object and Embed Tag Parameters 589Adding FlashVars 590Creating FlashVars with JavaScript 591Passing FlashVars via a Servlet Page 593

    Summary 594Exercises 594

    Chapter 24: Putting JavaScript to Work 595

    Changing Security Settings 595Calling JavaScript from within Flash 597

    Introduction to getUrl() 598Creating a JavaScript Command with Nested Variables 598Considering Limitations 602

    Calling JavaScript Functions Using fscommand 602Calling Flash from JavaScript 604Basic JavaScript Methods and Events 606Using the Flash JavaScript Integration Kit 607

    Setting Up the Integration Kit 608Calling JavaScript Functions from ActionScript 608Calling ActionScript Functions from JavaScript 609

    Using the External API 612ExternalInterface Class Methods 612

    addCallback() 612call() 614

    Calling ActionScript Functions and Methods 615Calling an ActionScript Function from JavaScript 615Calling an ActionScript Method from JavaScript 616

    Calling JavaScript Functions from ActionScript 617Opening a Browser Window 618Setting and Getting Data Using ActionScript 619

    02_577689 ftoc.qxp 3/15/06 10:55 PM Page xxii

  • xxiii

    Contents

    Opening Browser Windows 629Using getURL() to Create Pop-Up Windows 629Use ExternalInterface to Create Pop-Up Windows 630Calling a JavaScript Wrapper Function 630Defining Browser Window Parameters 631

    Summary 635Exercise 635

    Chapter 25: Uploading and Downloading Files 637

    FileReference Class Methods 637Using browse() 638Using cancel() 638Using download() 639Using upload() 639FileReference Class Properties 640

    Downloading Files 641Uploading Files 645Summary 651Exercise 651

    Chapter 26: Communicating between the Flash Plug-in and the Operating System 653

    Using the System Object to Retrieve System Information 653System Object Limitations among Player Versions 655The setClipBoard Method 655

    Projectors, Flash Executables, and Other Executables 656Limitations 656Using fscommand to Call Projector Functions 656SDK 658Third Parties 658

    Summary 659Exercises 659

    Chapter 27: Creating Custom Classes 661

    Working with Classes 661Defining the Class 661Public Versus Private 663Defining the Constructor 665

    Passing Startup Data 666Defining Methods 669

    02_577689 ftoc.qxp 3/15/06 10:55 PM Page xxiii

  • xxiv

    Contents

    Defining Properties 675Working with Getters and Setters 676Implications of Getters and Setters 676

    Adding Functionality to Existing Classes 681Subclassing 681Static Library 682Composition 686

    Summary 695Exercises 695

    Appendix A: Exercise Answers 699

    Appendix B: Flash Keyboard Shortcuts 759

    Tools Panel 759Integrated Script Editor Shortcuts 760

    File Menu 760Edit Menu 761View Menu 761Tools Menu 761Control Menu 762

    Actions Panel Shortcuts 762Drawing IDE Shortcuts 763

    File Menu 763Edit Menu 763View Menu 764Insert Menu 765Modify Menu 765Text Menu 767Control Menu 767Window Menu 768Help Menu 769

    Index 771

    02_577689 ftoc.qxp 3/15/06 10:55 PM Page xxiv

  • Introduction

    Macromedia Flash began as a vector animation tool, designed to help put a bit more punch into other-wise motionless web pages. At the time, web pages were simple and data-driven sites were few, so ani-mation was one way to differentiate your pages from the rest of the crowd. Many people still hold theperception that Flash is only a tool for animation, in part due to the preponderance of Flash-based siteintros and a very visible presence in banner and pop-up ads. While it remains a very good tool for ani-mation, it has grown into a powerful means to do much more.

    Macromedia Flash is a full-fledged application development environment. The real focus on using Flash for coding came with version 6, which introduced a new coding and event model leading to acleaner, more flexible coding style. That version was the first major step in giving the developer powerto create many interesting and useful applications. Flash 7 added a major scripting update, resulting inActionScript 2.0. It provides a more structured, flexible, and maintainable programming style. Finally,Macromedia Flash 8 has expanded the offering, adding bitmap support, filters, and blending modes, fileupload and download capabilities, an interface for communicating with the browser, and much more.All of the add-ons can be manipulated with script, not just with visual tools within the developmentenvironment.

    The mature capabilities of Macromedia Flash 8 have the potential to redefine user interactions andusability on the Web. Flash enables you to develop full-fledged applications that either run in a webbrowser or run standalone as an executable.

    Regardless of whether you are just interested in dabbling with scripting, or you want to develop applica-tions with thousands of lines of code, ActionScript is for you. Want to build a major e-business applica-tion, to create a personal portfolio, to create a game, or to work with media? This book will help you out.If you’ve done any work with any other scripting language such as JavaScript or programming languagesuch as Java or Perl, you are already halfway there. Even if you’ve never touched a line of code, you stillcan learn to apply ActionScript to Macromedia Flash projects through the many examples shown in thesuccessful Wrox “Try It Out” format.

    Who This Book Is ForThe Macromedia Flash development environment is useful for a wide range of tasks, from creating marketing pieces, to creating a personal portfolio, to creating enterprise-level e-commerce applications,to creating games. As such, the diverse group of people who use it have different backgrounds, differentmixes of technical and artistic skills, and different goals. This book assumes no prior programming orMacromedia Flash development experience. If you do have basic knowledge of ActionScript, there isplenty of content about how to work with different aspects of Macromedia Flash with script. This bookincludes techniques for animating using only code, working with audio, video, and graphics, interactingwith the user, communicating with a server, and much more. This book also includes a primer on object-oriented programming, and the last chapter shows you how to create your own custom classes, a veryvaluable skill to acquire.

    03_577689 flast.qxp 3/15/06 10:55 PM Page xxv

  • xxvi

    Introduction

    Regardless of what you want to get out of Macromedia Flash, this book is a good starting point to getyou to where you want to go.

    How This Book Is StructuredBeginning ActionScript 2.0 teaches by example, using small, well-chosen programming examples, pre-sented in the Wrox trademark “Try It Out” format. By typing each example, running it, and examiningthe results, you gain experience with the entire process of coding, running, and debugging MacromediaFlash projects. Experience has shown that a hands-on approach is one of the most effective ways tolearn. In addition to the code samples, each example provides you with detailed descriptions of exactlywhat the code does, and why it was done that particular way. Where appropriate, the example overviewalso talks about some of the implications of developing code in that particular way, and with a mindtoward other ways of performing the same task.

    Here’s a breakdown of what this book provides:

    In Chapter 1, you learn the aspects of the development environment, including how to create, workwith, and publish a Macromedia Flash project. You create your first scripted project, put it in an HTMLwrapper, and make your project viewable on the Web.

    Chapters 2–4 take you right into the guts of the language. You learn all the aspects of ActionScript,including variables, data types, conditionals, loops, events, and errors. By the time you get through these chapters, you will have a good understanding of how to use the core aspects of the language.

    Chapters 5 and 6 get you up and running with ActionScript, explaining such things as where to placeyour code and how to structure your Macromedia Flash project. You learn simple coding conventionsthat will help you create projects that are easier to read and to update. You see different ways to struc-ture your project, learn the benefits and issues with each, and find out about some techniques that willhelp you through the debugging process.

    In Chapters 7 and 8, you start using ActionScript to work with a core Macromedia Flash technology:components. You find out all about components—how to apply them to your project, have them com-municate with each other, and customize their look on-the-fly through component styles. When you’vefinished these chapters, you’ll be well on your way to building form-based applications.

    Chapters 9–11 show you how to work with the core container: the movie clip. You explore how to createblank movie clips and how to draw in them on-the-fly, how to work with movie clips in the library, andhow to load external movie clips. You learn how to change variables and content in one movie clip fromanother and how to implement a movie pre-loader. You also study different ways to structure movieclips within a project. After you have completed this chapter, you will have a good understanding ofmany aspects the Macromedia Flash core building block.

    Chapter 12 teaches you some techniques for debugging code. You learn some of the methodology thatmakes debugging less of a hit-or-miss scenario, how to use the debugger, and how to use the outputpanel to get a better sense of what is going on with your code.

    Chapters 13–15 teach you how to work with drawing and to apply effects with ActionScript. You learnhow to use the drawing API, how to apply filters and blending modes, and how to work with the newBitmap class to manipulate individual pixels.

    03_577689 flast.qxp 3/15/06 10:55 PM Page xxvi

  • xxvii

    Introduction

    You extend your knowledge of the movie clip in Chapters 16 and 17. You learn the concepts of time-based and frame-based animation, and how to animate with ActionScript. That knowledge is extendedby adding basic physics to your animations, and is topped off by using the Tween class to simplify sometypes of animations. After finishing these chapters, you’ll know how to create scripted animations.

    In Chapter 18, you learn the intricacies of working with text, including the different types of text fields,issues related to embedding fonts into your project, and how to apply visual styles to text. Because texthandling is one of the largest sources of problems with new Macromedia Flash developers, this chapteris replete with annotated examples illustrating how to deal with this subject.

    Chapters 19 and 20 show you how to integrate images, sound, video, and live camera feeds into yourproject. You learn to work with features such as loading, streaming, and embedding media. Through thischapter, you get a good grasp of the various media management issues, and learn ways to deal withissues specific to working with different media types.

    Chapters 21 and 22 explain how to get your project to pass data between the web browser and a server.You learn the details of communicating with a server using a number of different communication tech-niques, including LoadVars and XML. Security issues are reviewed and solutions are presented for deal-ing with many of those issues.

    Chapters 23–25 provide techniques for communication between a movie and the browser, and betweenseparate movies. You learn to use new classes for communicating between the browser and theMacromedia Flash plug-in, for starting up movies on-the-fly with JavaScript, and for saving informationlong-term on the user’s computer. Cross-platform communication issues are addressed, so you canensure that your project will work in different browsers on different platforms.

    Chapter 26 examines the capabilities and limitations of working with the user’s operating system. Youlearn to retrieve information about the user’s operating environment through the System object. You learnto launch programs, open windows, and make your own system calls from a standalone projector. You alsosee examples of using third-party tools to greatly expand the capabilities of the projector. Basically, thischapter teaches you how to interact with the operating system from within the Macromedia Flash plug-in.

    Chapter 27 shows you how to create custom ActionScript classes, how to think in a more object-orientedway, and some techniques for working with your own classes.

    Each chapter ends with exercises for you to work on your own, and Appendix A provides solutions tothose exercises.

    What You Need to Use This BookThis book targets Flash 8, but because ActionScript 2.0 made its debut in Macromedia Flash MX 2004and because the language has not substantially changed in Flash 8, much of this book is also relevant tothose using Macromedia Flash MX 2004. A few features require Flash 8, and that’s noted as they’re used.You can use either Macromedia Flash MX 2004 or Flash 8 development environments, although thisbook assumes that you are using the professional version. You can download a fully functioning 30-daydemo of Flash 8 from www.macromedia.com/downloads. Flash player version 7 does exist for Linux,although version 8 is not yet available for Linux. Macromedia does not provide a Linux developmentenvironment. As a result, you need to use either at least Mac OS X 10.3 or at least Windows 2000 to runthe Flash development environment.

    03_577689 flast.qxp 3/15/06 10:55 PM Page xxvii

  • xxviii

    Introduction

    Although the script editor in the Flash development environment is quite suitable, you may want to usea separate text editor, preferably one that supports syntax highlighting for ActionScript 2.0. Chapter 1offers a number of suggestions for text editors that you may want to use.

    ConventionsTo help you get the most from the text, a number of conventions are used throughout the book.

    Asides to the current discussion are offset and placed in italics like this.

    As for styles used in the text:

    ❑ Important words are highlighted when introduced.

    ❑ Keyboard combination strokes are presented like this: Ctrl+A.

    ❑ Filenames, URLs, and code within the text appears in a special monofont typeface, like this:System.capabilities.

    Code blocks and examples appear in two different ways:

    In code examples, new code has a gray background.

    The gray background is not used for code that is less important in the presentcontext or that has been shown before.

    And in some instances, parts of a code example may be boldface to make it easier for you to spot achange from earlier code.

    Occasionally a code line won’t fit on one line in the book. In those instances, a code continuation charac-ter (@@ta) at the end of a line indicates that the next line is actually a continuation of it.

    Source CodeAs you work through the examples in this book, you can choose either to type in all the code manually,or use the source code files that accompany this book. All of the source code used in this book is avail-able for download at www.wrox.com. Once at the site, simply locate the book’s title (either by using theSearch box or by using one of the title lists) and click the Download Code link on the book’s detail pageto obtain all the source code for the book.

    Because many books have similar titles, you may find it easiest to search by ISBN; for this book, theISBN is 0-7645-7768-9.

    After you download the code, just decompress it with your favorite decompression tool.

    Information of importance outside of the regular text looks like this.

    03_577689 flast.qxp 3/15/06 10:55 PM Page xxviii