Robert Reinhardt, Director of Multimedia Applications for The Content Project www .contentproject.com, is internationally regarded as an expert on multimedia application development, par
Trang 2Flash ™
Robert Reinhardt and Joey Lott
Trang 4Flash ™
Trang 6Flash ™
Robert Reinhardt and Joey Lott
Trang 7Flash™ MX 2004 ActionScript Bible
Copyright © 2004 by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
Library of Congress Control Number: 2004103173
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REPRESENTATIONS
OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES
OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ
For general information on our other products and services or to obtain technical support, please contact our Customer Care Department within the U.S at (800) 762-2974, outside the U.S at (317) 572-3993 or fax (317) 572-4002
Wiley also publishes its books in a variety of electronic formats Some content that appears in print may not be available in electronic books
Trademarks: Wiley, the Wiley Publishing logo, and related trade dress are trademarks 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 Flash is a trademark of Macromedia, Inc All other trademarks are the property of their respective owners Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book
Copyright © 1999–2003 Macromedia, Inc., 600 Townsend Street, San Francisco, CA 94103 USA All Right Reserved
Macromedia and Flash are trademarks or registered trademarks of Macromedia, Inc in the United States and/or other countries
Trang 8Robert Reinhardt, Director of Multimedia Applications for The Content Project (www
.contentproject.com), is internationally regarded as an expert on multimedia application
development, particularly in Macromedia Flash Robert is the lead author of the Flash Bible series and Flash ActionScript Bible (Wiley), as well as Macromedia MX: Building Rich Internet Applications (Macromedia Press) He has developed multimedia courses for educational facili
ties in Canada and the United States and has been a featured speaker at several Web conferences Robert also provides multimedia consulting through his company, [theMAKERS]
Joey Lott has written several books on Flash and ActionScript He lives in Los Angeles
Trang 9Executive Editor Project Coordinator
Chris Webb April Farling
Development Editor Graphics and Production Specialists
Kezia Endsley Beth Brooks
Lauren Goddard
Troy Gardner Jennifer Heleine Steve Nowicki Kristin McMullan
Nancy Rapoport Quality Control Technicians
Luann Rouff John Greenough
Andy Hollandbeck
Mary Beth Wakefield Carl Pierce
Charles Spencer
Vice President &
Executive Group Publisher Permissions Editor
Richard Swadley Laura Moss
Vice President and Media Development Specialist
Bob Ipsen
Proofreading and Indexing Vice President and Publisher TECHBOOKS Production Services Joseph B Wikert
Executive Editorial Director
Mary Bednarek
Trang 10To the future of expression on the Internet and the Web
We owe it to ourselves to continually share our ideas
and experiences with one another
— Robert
May there be peace within and among all beings
May all recognize that which is
— Joey
Trang 12Flash has become an important and pervasive feature of the Web Consider the numbers:
In June 2003 an NPD Research study showed that 97.4 percent of Web users have Flash installed on their computer The study was conducted roughly a year after the release of the Flash Player 6 and showed that version 6 of the player was already available on more than
86 percent of Web users’ computers The Flash Player is preinstalled in Internet Explorer and other browsers But that doesn’t explain why more than 86 percent of Web users had version
6 a year after its release At the time, IDC Research estimated there were 448 million people using the Web A year after the release of the version 6 player, something like 386 million of those people had version 6 The statistics don’t show how many people downloaded the player and how many found that it came with their browser, but it’s a safe bet that hundreds
of millions of player downloads had to take place to get the player onto so many machines so quickly
The pervasiveness of the Flash Player has a lot to do with how widely Flash is used But it is not the only driving force In 2003, during the course of history-making world events, large media sites made extensive use of Flash to provide multimedia coverage of these events and background information At the same time, individuals created Flash animations and games that were used to express views across the political spectrum Flash was then, and is now, an important vehicle for providing an expressive and dynamic Web It is used for almost everything Advertisers love Flash advertisements because they are difficult to ignore Educators use Flash to create compelling online learning objects that enliven courses and provide online simulations Artists are always finding new uses for Flash, and institutions such as museums rely on it more and more Cartoonists continue to discover Flash and are constantly pushing the envelope of animation length and quality Flash front-ends to online applications are popping up everywhere and allow you to do everything from booking a hotel reservation to making banking transactions
The capacity of Flash to deliver compelling experiences on the Web encourages people to download the latest player In turn, the near ubiquity of the Flash Player encourages designers and developers to make regular use of Flash The two trends continue to feed off and reinforce each other
Internet technologies are constantly appearing, evolving, and in some cases disappearing Each new technology takes time to learn and apply effectively As each technology evolves, keeping up with it takes more time and effort, as does learning how to apply it to old problems and how to use it to solve new ones At some point designers and developers have to make big choices It just isn’t possible to learn every Web technology in depth After the baseline requirements of learning HTML and style sheets, creating effective Web images, and learning some JavaScript, what comes next? Just keeping up with the abbreviations can be irritating In no particular order: XML, XML-RPC, XUL, MXML, SQLXML, SVG, EPML, SMIL, WSDL, SOAP, WAP, WMA, EJB, J2EE, SAX, JAX-RPC, LDAP, PHP, CFML, and on and on
Trang 13Web designers and developers naturally gravitate to systems that are capable of reaching the greatest number of people, provide the richest set of capabilities, and are still cost effective
to use In other words, designers and developers need systems that provide ubiquity, utility, and usability
Flash has evolved from a vector-based animation tool to an amazingly rich, flexible, and integrated design and development environment Today you can seamlessly blend unique vector-based animation with images, components such as the Datagrid and Tree components, progressive download and streaming audio and video, real-time communications, and connectivity to every type of enterprise-class computing system Flash works with many of the technologies already mentioned and provides some of its own for good measure, such as AMF and RTMP The power of the Flash authoring system does not lie only in the fact that it does one or two things well It delivers so many features in one integrated development and delivery system with which both designers and developers can effectively work As Flash continues to evolve, the need to bring together a complex variety of difficult-to-integrate systems and tools continues to diminish
At the core of both the Flash development process and delivery system is the ActionScript language and interpreter Designers often make extensive use of ActionScript to simplify their Flash movies and provide the kind of fine-grained control they need for visual elements Developers use ActionScript to make increasingly full-featured Web-based applications with rich user interfaces and excellent responsiveness to the user’s actions ActionScript can accommodate the needs of both designers and developers because it is based on JavaScript (also known as ECMAScript)
ECMAScript/JavaScript is first and foremost a scripting language It was designed from the beginning to provide easy-to-use object scripting capabilities In Flash, that means it is relatively simple to do things such as attach a behavior to a button that in turns manipulates another object such as an animation running within a Movie Clip The ActionScript code to add a behavior that manipulates an object is short and simple, and the Flash authoring environment makes it easier still However, ActionScript is not restricted to scripting objects It is possible to build large and complex applications using traditional object-oriented design and development methods that are realized in ActionScript With the release of the 2004 Flash products, ActionScript has evolved further to increase support for advanced object-oriented development without sacrificing the language’s utility for designers
Learning to work with ActionScript is an essential Flash skill How far you go with ActionScript and how you approach learning the language will vary depending on your background — especially how much computer programming you already know However you approach learning ActionScript, you will constantly be working with both the language and the objects
it allows you to manipulate — especially Movie Clips Flash MX 2004 ActionScript Bible provides
an excellent roadmap to the language and the variety of objects it allows you to create and manipulate The two authors bring a great deal of practical experience to the book and are also accomplished teachers and learners I first met Robert Reinhardt when he was a first-year student at Ryerson University Robert was the kind of student professors pray for He is intelligent, inquisitive, and remarkably energetic As I have with so many students who have graduated from Ryerson, I completely lost track of Robert after he got his degree Some years later when I finally decided to learn something about Flash I asked one of my colleagues which
book I should read I was told to buy Reinhardt and Lentz’s Flash 4 Bible When I realized that
Trang 14write a number of books on different facets of programming in Flash and with Robert has
produced a book I’m happy to sneak my name into by writing these few pages Flash MX 2004 ActionScript Bible shows a concern for the needs of designers and developers who want to
learn ActionScript through experimentation and exploration Enjoy
Trang 16If you’ve picked up this book, then you are undoubtedly familiar with Flash Since Macromedia first acquired the program, Flash has become increasingly popular to the point where there are few people who don’t know what Flash is Flash applications, sometimes referred to as Flash movies, can be deployed in many types of environments But by far the most popular use of Flash is on the Web The reason is simple: Flash provides a much more robust and interactive experience than HTML can The opportunities that Flash provides appeal to a wide audience — from artists to corporations It offers a medium for expressing creativity, ideas, and messages in unique and innovative ways Whether it is an artist wanting to create interactive art, an organization wanting to provide resources and information, a company wanting
to sell products, a group wanting to create a real-time interactive community, or a university wanting to create collaborative learning experiences, Flash is the medium of choice
But as Flash has evolved, and as the demands of the community have grown, so have the complexities and intricacies of the application This is true of ActionScript more than any other aspect of Flash In its early versions ActionScript, the programming language within Flash, consisted of nothing more than a few commands that could be applied via menus only Flash 5 marked a huge step in the evolution of ActionScript In Flash MX, ActionScript adapted
to the wants of the developers by providing more programmatic control within a Flash application And Flash MX 2004 represents another big leap in ActionScript
Using Flash MX 2004, you can do a great many things programmatically All of the ActionScriptbased features from previous versions of Flash are still available For example, you can still send and load variables and XML and use Flash Remoting You can still load MP3s at runtime You can still load SWF and JPEG content, but Flash MX 2004 provides you with an improved way of doing so Using Flash MX 2004 you can still display HTML, but new is the cascading style sheet (CSS) support that enables you to effectively apply formatting Flash MX 2004 replaces the older printing functions with the new PrintJob class to afford you more control The list goes on and on In fact, it took us an entire book to provide you with all the information!
Macromedia Flash MX ActionScript Bible was the first edition, and we’ve updated it to produce
this second edition But this book is much more than just a basic update to its previous incarnation Although we made every effort to make the first edition as good as possible, in the time that has passed since its publication, we have learned a lot We’ve listened to your feedback And we think you will find that this new edition is filled with valuable and accurate information that is well organized, readable, and practical We’ve done our best to provide in-depth research combined with practical, working knowledge
Some of the features you’ll find in this book are:
✦ Comprehensive coverage of ActionScript: We’ve included just about everything you
could think of, and a few things you probably didn’t think of We’ve attempted to make sure the information is relevant, practical, and significantly more than just a basic reference We have included coverage of basic ActionScript syntax; all the built-in commands, functions, and classes; and even some coverage of related technologies such as Flash Remoting
Trang 17✦ Complete coverage of ActionScript 2.0: ActionScript 2.0 is new in Flash MX 2004, and
we’ve detailed it in depth You’ll find descriptions of the syntax, best practices, and beginner, intermediate, and advanced topics
✦ Working examples and exercises: We know that one of the best ways to learn
ActionScript is to practice writing it So throughout the chapters you can find lots of exercises that you can use to practice the concepts as you read them You’ll find the completed files on the CD-ROM that accompanies this book in case you get stuck and want to see the working examples
✦ Practical expertise and advice: Theory is useful up to a point But if you want to use
Flash and ActionScript to build a working application, you’ll need more than that While
we provide all the theory, we also back it up with explanations, tips, and advice based
on practical experience building professional applications
✦ Continuing community and support: The official Web site for the book is www
flashsupport.com There you’ll find updates and notes about the book as well as support forums for readers so you can ask any questions you might have
We encourage your feedback In fact, we’ve set up a system so that you can submit feedback
on specific chapters Your comments will help us make the next edition even better You can find the feedback application at www.flashsupport.com/feedback
How to Get the Most Out of This Book
You can read and utilize this book in many ways If you are a beginning programmer or even
if you’re just new to ActionScript, we encourage you to read Parts I and II first We also recommend that you read Chapter 9 Following that, you can browse the chapters and sections that most interest you ActionScript is a large subject, and you will likely find that you will master one part at a time
If you already know ActionScript from previous versions of Flash, but you don’t yet know ActionScript 2.0, you will likely find it helpful to follow the same advice that we offer to beginning coders Part II is probably the most important section for you to start with, however Intermediate and advanced ActionScript developers can still benefit from the book You can turn to any chapter for a reference For example, even an advanced ActionScript developer might not necessarily know all the details about a particular class If you want to learn more about a class, or just brush up on it, read the chapter for reference
Keep the book on your desk Read sections over and over Try the exercises You’ll learn more each time At first, just getting a MovieClip object to move across the screen may be difficult But upon returning to that section months later, you will undoubtedly discover something you didn’t notice before
Conventions Used in the Book
Throughout the book when we refer to application menus, the menu names and nested menu items are separated by arrow icons For example, to open a new Flash document within Flash
MX 2004 you can select the New option from the File menu We indicate that in the text by suggesting you choose File ➪ New
Trang 18Web Resource
On the CD-ROM
Tip Tips offer you extra information that further explains a given topic or technique, often sug
gesting alternatives or workarounds to a listed procedure
Notes provide supplementary information to the text, shedding light on background pro
cesses or miscellaneous options that aren’t crucial to the basic understanding of the material
When you see the Caution icon, make sure you’re following along closely to the tips and techniques being discussed Some external applications might not work exactly the same with Flash on different operating systems
If you want to find related information to a given topic in another chapter or section, look for the cross-reference icon
The New Feature icons point out any differences between Flash MX 2004 and ActionScript 2.0 and previous versions
When you see this icon, you will find Web URLs that point to further information about the topic at hand
Also, many code samples that are printed in this book have lines of code that are too long to fit on one line These lines of code are broken into two or more lines and end with the line continuation symbol, Æ This symbol should not be typed into the actual code of your Flash
document Simply continue to type the following line(s) of code on the same line in the Actions panel For example, you would type the following line all on the same line in the Actions panel:
mcPhoto._accProps.description = “Picture of attendees at the round table Æ
discussion”;
Because Flash MX 2004 is available for both the Windows and Mac OS X operating systems, when applicable we provide keyboard shortcuts for both In many cases the Ctrl key in a Windows environment is analogous to the Command key on the Macintosh, which we repre
sent using the Ô symbol You’ll also notice that many keyboard shortcuts are denoted using
a + symbol when Flash requires that you press several keys at the same time For example, the notation Shift+N indicates that you should press and hold the Shift key while then press
ing the N key
Trang 19How This Book Is Organized
We’ve reorganized this edition of the book in ways that we think will make it most approachable and helpful The ten parts of the book are outlined in the following sections
Part I: Conceptualizing Flash
When you are first starting to develop ActionScript-rich Flash applications, you’ll want to make sure that you are planning the projects appropriately Part I provides you with the information you need to put Flash into the context of application development, and it helps you to plan your projects appropriately
Part II: Laying the ActionScript Foundation
When you build a building, the first thing you do is lay the foundation Doing so helps to ensure a sturdy base from which something can be created Part II aims to provide you with the basic information and practical exercises that can assist you in getting a fundamental understanding of ActionScript You’ll learn all about how ActionScript works, where to place
it, how to write it, syntax, structure, and much more
Part III: MovieClip, Button, and Drawing API
The MovieClip class is one of the primary classes in ActionScript Part III introduces you to the MovieClip class (which includes the Drawing API — which enables you to draw programmatically) And because the Button class is so closely related to MovieClip, you will also learn all about how to use the Button class as well
Part IV: The Core Classes
The core classes provide important, yet non-visual functionality within your Flash applications The classes include Array for grouping and indexing data, Math for performing advanced mathematical operations, Date for working with date and time values, String for working with textual values, and the wrapper classes Number and Boolean Part IV looks at each of these classes (and related functions) in depth
Part V: The Movie Classes
Part V looks at each of the classes that have some kind of visual representation within an application (minus MovieClip and Button, which are discussed in Part III) or handles user interaction within the application This group includes classes such as Color for adjusting color and TextField for working with visual text It also includes other assorted classes such
as Mouse for working with the mouse interaction, ContextMenu for controlling the items in the right-click/Ô-click menu, and PrintJob for printing Flash content
Part VI: The Audio and Video Classes
Flash MX 2004 has increased multimedia support The Sound class is supported as previously
In addition, Flash MX 2004 enables you to load FLV video files programmatically without the
Trang 20Part VII: The Data Classes
Although Flash was originally an animation medium, it has steadily grown to supported more and more data capabilities In Part VII you can read about the classes that support sending and loading data, including coverage of the SharedObject, LocalConnection, XML, LoadVars, and XMLSocket classes
Part VIII: Using Components
Components are an important part of Flash MX 2004 By encapsulating functionality, compo
nents can provide a simple drag and drop solution to what might otherwise require hundreds
or even thousands of lines of code In Part VIII you’ll learn about the user interface components that are included with Flash as well as how to create your own components
Part IX: Working with Flash in Other Environments
Part IX discusses how Flash can interact with the environment in which it is being played back For example, you’ll get a chance to learn how to use Flash within a Web browser as well
as how you can issue special commands when publishing a stand-alone player version of your application
Part X: Creating Flash Applications
Once you’ve learned the basics, Part X shows you how to put it all together when creating complete applications You’ll get a chance to read about how to optimize and manage the download and presentation of content, special tips for working with data exchange, working with Web services, and creating user input forms with Flash
CD-ROM Chapter
Be sure to check the CD-ROM for an additional chapter that wasn’t added to the printed ver
sion of the book You’ll find extra information such as how to perform pattern matching using the RegExp class
Appendix
The appendix contains information regarding the CD-ROM that accompanies this book
Getting in Touch with Us
The official Web site for this book is:
www.flashsupport.com
Trang 21At the site you’ll find updates, notes, and more Additionally, you can find support forums so
you can post and answer questions and get to know others in the Flash Bible and ActionScript Bible community
We appreciate your feedback If you have found this book to be helpful, please let us know And if you have suggestions for ways we might improve subsequent editions, please let us know that as well You can contact us by e-mail at the following addresses:
✦ Robert: fmx2004@flashsupport.com
✦ Joey: joey@person13.com
Getting in Touch with Macromedia
Macromedia wants to constantly improve Flash in ways that help you The only way they get
to know how you are using Flash (or how you’d like to use Flash) is if you send them feedback The more feedback you can provide to them, the better equipped they are to adapt Flash to your requests In order to hear from you, Macromedia has set up a system by which you can submit your feedback at:
www.macromedia.com/support/email/wishform/?6213=9
If there are features that work particularly well for you, let them know If there are features that are not working for you, let them know And if there are things that Flash does not do that you’d like it to do, then let Macromedia know that as well
To support the Flash community Macromedia has created a searchable registry that allows clients to find Flash developers by location or by services offered To create a custom developer profile, register yourself at:
www.macromedia.com/locator Regardless of your geographic location, you always have access to the global Flash community for support and the latest information through the Macromedia Online Forums:
http://webforums.macromedia.com/flash You can also visit Macromedia’s new Designer & Developer Center, where you can find the latest news and tutorials for Macromedia MX software:
www.macromedia.com/devnet For inspiration and motivation, check out the site of the day, weekly features, and case studies at:
www.macromedia.com/showcase
Trang 22This book represents the collective efforts of many people, all of whom have contributed
in some way to make it as good as it can be We thank everyone at John Wiley & Sons for helping with each step of the process Thanks go to Chris Webb, the acquisitions editor for this project, for his guidance and assistance, and for acting as a liaison to make sure that the best interests of the book were kept in mind at the publisher This book is also, in large part, made possible by Kezia Endsley, our development editor, who has gone over every word, coordinated schedules, and ensured that the book is of the highest quality possible Thank you, Kezia
We thank our agent, David Fugate, for being there and for assisting when needed
Of course, this book about Flash wouldn’t even exist without the hard work of the people at Macromedia who continue to develop and promote Flash Many thanks to the developers, engineers, and support staff at Macromedia Particularly we thank Lucian Beebe, Gary Grossman, Nigel Pegg, Nivesh Rajbhandari, Erica Norton, Mike Shroeder, Barbara Herbert, and Heather Hollaender
Troy Gardner and Steve Nowicki provided their support throughout the book by editing the chapters for technical content Thank you, Troy and Steve, for double-checking all the code and all of our claims to make sure that the book is as technically accurate as it can be Many thanks are due to the many developers, designers, artists, coders, and other members
of the Flash community You’ve pushed the limits You’ve innovated You’ve inspired In particular we thank those people with whom we have shared dialogues throughout the writing of this book Thanks go to Peter and Jen deHaan, Chafic Kazoun, Tom Muck, and Shane Elliott
We especially thank you It is the readers who make this book what it is Thank you for your questions, your comments, and your feedback
Robert’s acknowledgments: I couldn’t have completed this revised edition without my part
ner, Snow Dowd I thank her for her encouragement and support during the long nights and lost weekends I spent updating this book I extend my deepest gratitude to Joey Lott, whose vast knowledge of Flash programming makes this book the valuable resource that it is I also thank all of the wonderful people at The Content Project who have enriched my breadth and depth of Flash design and programming Without their collaboration, I wouldn’t have as many exciting opportunities to push the limits of Flash experiences
Joey’s acknowledgments: I thank Robert for having offered me the opportunity to write this
book with him I’d like to thank my parents and sister for their love and support I’d like to give thanks to that which cannot be put into words — that which is the very essence of all being
Trang 23Foreword ixPreface xiiiAcknowledgments xix
Part I: Conceptualizing Flash 1
Chapter 1: An Introduction to Flash MX 2004 3Chapter 2: Working with Web Technologies and Interactive Models 19Chapter 3: Architecture for Flash Movies 39
Part II: Laying the ActionScript Foundation 63
Chapter 4: Learning ActionScript Basics 65Chapter 5: Constructing ActionScript 91Chapter 6: Working with Functions 125Chapter 7: Programming with Objects and Classes 143Chapter 8: Error Handling and Debugging 185
Chapter 9: MovieClip and Button Classes 219Chapter 10: The Drawing API 261
Chapter 11: Using the Array Class 295Chapter 12: The Number Class 317Chapter 13: The Math Class 325Chapter 14: Working with Dates and Times 341Chapter 15: Working with Strings 367
Chapter 16: The Color Class 381Chapter 17: The TextField and Selection Classes 395Chapter 18: Using the TextFormat Object and Style Sheets 441Chapter 19: The Mouse and Key Classes 459Chapter 20: The Stage and ContextMenu Classes 503Chapter 21: The System Class and the Capabilities and Security Objects 529Chapter 22: The PrintJob Class 539
Trang 24Chapter 23: The Sound Class 563Chapter 24: The NetStream and Video Classes 599
Chapter 25: The SharedObject and LocalConnection Classes 615Chapter 26: The XML and LoadVars Classes 631Chapter 27: The XMLSocket Class 657
Chapter 28: Using V2 UI Components 673Chapter 29: UI Component Style and Focus Management 731Chapter 30: Creating Your Own Components 745
Chapter 31: Working with Flash in the Web Browser 769Chapter 32: Making Movies Accessible and Universal 779Chapter 33: Scripting for the Flash Stand-Alone Player 795
Chapter 34: Managing and Loading Flash Content 813Chapter 35: Sending and Loading Data 847Chapter 36: Using the Built-In Web Service Functionality 865Chapter 37: Making Flash Forms 873
Appendix A: What’s on the CD-ROM 889Index 893
Trang 26Foreword ix Preface xiii Acknowledgments xix
1 Part I: Conceptualizing Flash
Chapter 1: An Introduction to Flash MX 2004 3
Considering Flash MX 2004 in Context 3Understanding the Capabilities of Flash MX 2004 4Flash MX Pro 2004 5Improvements to the User Interface 5ActionScript 6Flash Player 7 Improvements 8Product Integration 11Templates 11Shared Libraries 11Understanding the Framework 12Movie Playback 13File Types in Flash MX 2004 13Moving Data Using Flash 14Applying Flash MX 2004 14Planning Flash Development 15Summary 17
Where Flash Fits into the Ever-Evolving Web 19Expecting the Best Experience 19Flash Player Statistics 21
To Flash or Not to Flash? 22Competing Technologies 26
An Overview of Companion Technologies 28The Web Saga: HTML Lives! 28Scripting on the Client Side: JavaScript 28Transmitting and Storing Data 29Visualizing Multimedia Potential 36Linear Presentations 36Interactive Presentations 36Data-Driven Presentations 36Data-Driven Applications (or RIAs) 36Summary 37
Trang 27An Overview of Flash Development 39Creating a Flash Plan 40Design Documents 40Functional Specifications 41Making Flowcharts 42Gantt Charts 44Considering Flash Architecture Solutions 44Flash as Specialty Content: Multipage HTML 44Flash as the Backbone: One-Page HTML 45Using DHTML with Flash 45Considering Data Architecture Solutions 46Internal Data Storage 46External Data Storage 47Organizing Assets for Production 49Naming Conventions 49File Formats 50Folder Hierarchies 50Using the Project Panel in Flash MX Pro 2004 51Establishing a Project and a Site 52Adding Files to the Project 56Committing and Editing Files in the Project 57Adding New Files to the Project 59Publishing the Entire Project 60Summary 60
63 Part II: Laying the ActionScript Foundation
Chapter 4: Learning ActionScript Basics 65
Introducing ActionScript 65Learning What You Can Do with ActionScript 66Creating Your First ActionScript 66Understanding the Event Model: How ActionScript Works 68Assigning Actions 68Understanding the Actions Panel 71Opening the Actions Panel 71Working with the Actions Toolbox 73Working with the Script Navigator 74Working with the Script Pane 75Managing Scripts 77Setting Actions Panel Preferences 78Working with Formatting 80Using Code Hinting 80Using the Help Panel 82Summary 90
Understanding Datatypes 91Working with Strings 92Working with Numbers 93Using Booleans 94
Trang 28Declaring Variables 95Naming Variables 97Using Expressions 99Working with Operators 100Working with Arithmetic Operators 101Working with Assignment Operators 101Working with Comparison Operators 103Working with Logical Operators 105Working with String Operators 106Working with Miscellaneous Operators 107Understanding Bitwise Operators 109Considering Operator Precedence 114Using Comments Effectively 115Working with Statements 116Understanding Statement Syntax 116Using Statements That Control Flow: Control Structures 117Summary 123
Understanding Programming with Functions 125Defining Custom Functions 126Calling Functions 127Passing Parameters 127Passing Parameters by Value or by Reference 129Working with the arguments Property 129Overloading a Function 131Returning a Value from a Function 131Referencing Functions 133Creating Function Literals 133Understanding Scope 134Variable Scope 134Function Scope 135Creating Recursion 136Writing for Reusability 137Using Built-in Functions 138Creating Interval Functions 139Summary 141
Introducing Objects 143Understanding Object Blueprints 143Creating an Object 144Accessing Object Properties 145Accessing Object Methods 146Working with Static Properties and Methods 146Adding New Object Properties 147Adding New Object Methods 147Defining Event Handler Methods 148Telling Objects to Talk to Themselves 148Displaying the Time with an Object 149
Trang 29Working with MovieClip Objects 151Displaying the Time Using a Movie Clip 152Creating Interval Methods 153Understanding the Object Class 154Creating Object Literals 155Accessing Associative Array Keys and Values 155Looping Through Object Properties 156Creating Watched Variables 157Creating Custom Classes 159Understanding the Purpose of Custom Classes 159Working with the Classpath 159Making AS Files 161Creating a Simple Class 161Defining Properties for a Class 162Defining Methods for a Class 165Creating a Constructor 166Adding Static Properties to a Class 167Adding Static Methods to a Class 168Making Your First Class 168Working with Advanced Class Topics 172Organizing Your Classes with Packages 173Extending Classes 175Creating Interfaces 177Making Dynamic Classes 179Using the CustomActions Class 180Writing the Custom Action XML File 181Installing the Actions 181Listing the Custom Actions 183Removing Custom Actions 183Summary 184
Troubleshooting Your Flash Application 185Discovering Computer System Issues 186Encountering Bugs in Flash 186Detecting Errors in the Flash Document 187Finding Errors in Your Application 187Detecting Naming Conflicts and Problems 188Providing an Accurate Scoping Path 190Checking Paths 191Finding Conflicts in Frame Actions 191Importing Images, MP3s, and Video 191Publishing Your Movies 192Including Hidden Layers 193Fixing Blurry Text 193Considering External Issues 194Finding Help in the Flash Community 195Preventing Errors 196Planning Before Development 196Saving Your Documents Incrementally 197Testing Your Movie 197ActionScript Placement 198Working with Compatible Actions 198
Trang 30Throwing Exceptions 203Debugging Your Flash Application 203Using the Output Panel 203Debugging Using the Debugger 207
An Exercise in Debugging 213Summary 215
Creating MovieClip and Button Objects at Authoring Time 219Addressing MovieClip and Button Objects 220Targeting Nested Instances 220Working with Absolute Addressing 221Working with Relative Addressing 222Accessing Nested Instances with Array-Access Notation 223Handling Events 224Handling Button Events 224Handling MovieClip Events 225Using MovieClip Objects as Buttons 226Practicing Targeting 227Working with Appearance Properties 228Working with Coordinates 229Working with Dimensions 230Working with Self-Describing Properties 232Enabling Button-Like Behavior 233Tab-Switching, Focus, and Menus 233MovieClip-Specific Tab-Switching and Focus-Related Properties 234Tracking Objects as Menus 235Affecting Timeline Playback 235Creating MovieClip Objects Programmatically 236Understanding Stacking Order Within Flash Movies 236Creating Duplicate MovieClip Objects 238Adding MovieClip Objects from the Library Programmatically 239Working with Init Objects 241Creating Empty MovieClip Objects 242Removing Programmatically Generated MovieClip Objects 243Loading External Content 243Loading SWF Content 243Loading JPEG Content 245Monitoring Loading 245Unloading Content 247Opening Web Pages 247Creating Draggable MovieClip Objects 248Telling Flash to Start Dragging a MovieClip 249Telling Flash to Stop Dragging a MovieClip 250Determining Where an Object Is Dropped 250Checking for Overlapping 250
Trang 31Working with Coordinate Spaces 251Creating Scriptable Masks 252Practicing Attaching and Dragging MovieClip Objects 252Practicing Checking for Overlaps and Loading Content 255Summary 260
Introducing the Drawing API 261Setting a Line Style 261Moving the Pen Without Drawing 262Drawing a Straight Line 262Drawing a Curve 263Adding a Simple One-Color Fill 264Adding a Simple Gradient Fill 264Adding Complex Gradient Fills 266Clearing Previously Drawn Graphics 270Working with a Drawing Utilities Class 270Getting Started with DrawingUtils 270Drawing Rectangles 271Drawing Circles 272Drawing Regular Polygons 272Drawing Fills 273Practicing Dynamic Masking 275Practicing Responsive Objects 278Practicing Drawing 287Summary 291
Creating Ordered Structures 295Creating Arrays 296Adding Values to an Array 297Removing Elements from an Array 299Reading Data from Arrays 301Using Different Types of Arrays 302Working with Single-Dimension Arrays 302Working with Parallel Arrays 302Working with Multidimensional Arrays 304Working with Arrays of Objects 304Converting Arrays to Lists 305Creating New Arrays from Existing Arrays 306Concatenating Arrays 306Extracting Subsets of Array Elements 306Sorting Arrays 307Sorting Simply 307Sorting More Complexly 307Sorting Arrays of Associative Arrays 312Summary 316
Trang 32Integers and Floating-Point Numbers 317Decimal Numbers 318Other Bases for Numbers 318Converting Strings to Numbers 319Casting to a Number 320Converting to a Number with Precision 320Detecting When a Number Is Not a Number 321Dealing with Infinite Values 321Handling Minimum and Maximum Values 322Working with Number Instances 322Creating a NumberPlus Class 323Summary 324
Performing ActionScript Math 325Learning About ActionScript Math 325Utilizing the with Statement to Make Code More Readable 326Working with the Math Constants 326Finding Absolute Values 327Rounding and Truncating Numbers 327Generating Random Numbers 328Finding the Greater or Lesser of Two Numbers 329Working with Exponents and Square Roots 330Using Trigonometric Functions in ActionScript 331Calculating Natural Logarithms and Exponentials 334Creating MathUtils 335Using Math to Draw and Animate 336Summary 340
Working with Computer Dates 341Creating a Date Object 343Getting the Current Date and Time 343Making a Date Based on Epoch Milliseconds 344Making a Date Based on Year or Month 344Working with Date Objects 346get Methods 348set Methods 350Inherited Methods 352Static Methods 353Working with Advanced Date and Time Issues 353Creating a DateTime Object 360Working with Date Methods 360Performing Date Math 360Displaying the Date 361Creating a DateTime Object from a Date Object 361Parsing a Date String into a DateTime Object 361Detecting Leap Years 361Displaying the Time and Date 361Summary 365
Trang 33Understanding Primitives and Objects 367Getting and Setting Primitive Values 368Joining Strings 369Escaping Characters 369Nonvisible Characters 370Avoiding Common Mistakes 371Working with Character Codes 372Determining the Number of Characters 372Working with Substring Values 372substr 373substring 373slice 374charAt 374Finding Substrings 374Getting a Character Code 375Using Character Codes to Get Characters 375Converting a String into an Array 376Changing the Case of a String 377Passing String Values to and from Applications 377Summary 378
An Introduction to the Color Class 381Creating a New Object 381Referring to the Color Class Methods 383Understanding the Color Class 383Setting a Solid Color 384Retrieving Solid Color Information 386Controlling the Absolute Color of a Movie Clip 388Applying Advanced Color Effects to Movie Clips 391Summary 393
Understanding Types of Text 395Dynamic Text 395Input Text 396Creating TextField Objects 396Making Text at Authoring Time 396Making Runtime Text 398Working with TextField Object Basics 399Understanding Basic TextField Properties and Methods 399Adding Text 400Managing Multiline Text 401Resizing a TextField Object 402Making Text Non-Selectable 403
Trang 34Creating Password Text 405Changing Text Color 406Removing Text 407Creating a Simple Notes Application 407Using HTML with TextField Objects 409Rendering HTML in Text 410Inserting Special Characters into HTML Fields 410Adding Hyperlinks to Text 413Adding Mail Links 414Calling JavaScript Functions 414Calling ActionScript Functions from Text 414Embedding Content in Text 415Creating an HTML-Based Information Viewer 417Scrolling Text 418Scrolling Text Vertically 418Scrolling Text Horizontally 420Using Events for Text Fields 421Detecting Text Changes 421Detecting Focus Changes 421Detecting Scrolling 422Creating a Scrolling Text Viewer 423Adding Listeners to TextField Objects 425Detecting Text Changes 425Detecting Scrolling 425Working with Fonts 426Embedding Fonts 426Using Flash Device Fonts 431Inserting Special Characters into Editable Text Fields 432Creating a Random Letter Displayer 433Understanding the Selection Class 435Working with Focus 435Working with Selection 437Replacing Selected Text 438Working with Tab Order 439Enabling and Disabling Tab-Initiated Focus 439Changing Tab Order 439Summary 440
Working with TextFormat 441Creating a TextFormat Object 442Assigning Formatting to a TextField Object 442Understanding Formatting Properties 444Determining Text Metrics 450Getting the TextFormat 451Working with Cascading Style Sheets 452Understanding CSS 452Creating a StyleSheet Object 454
Trang 35Adding Styles with ActionScript 454Applying Styles to Text 454Formatting an HTML Article with CSS 455Loading External CSS 456Formatting HTML with CSS Loaded from an External File 457Summary 458
More Prebuilt Classes 459Using the Mouse Class to Control the Cursor 460Method Overview of the Mouse Class 461Method Overview of Mouse Listeners 462Showing and Hiding the Mouse Cursor 465Attaching a Custom Graphic to the Cursor 467Using updateAfterEvent() for Mouse Moves 470Using the Mouse Wheel to Control an Object’s Position 472Processing Keypresses with the Key Class 475Property and Method Overview of the Key Class 475Capturing Keypresses 477Determining the Key Code 483Nudging a MovieClip Object with the Arrow Key 486Using setInterval() and onKeyDown for Keypresses 489Detecting Keypress Combinations 493Playing a Flash Animation with a Keypress 496Summary 500
Controlling the Movie’s Stage 503Property Overview of the Stage Class 504Working with the Width and Height of a Flash Movie 508Method Overview of the Stage Class 512Controlling Placement of Elements According to Stage Size 513Removing a Listener Object from the Stage Class 516Using the ContextMenu Class 517Controlling Flash Player’s Built-in Menu 518Building Custom Menu Items with the ContextMenuItem Class 520Summary 528
Using the Top-Level System Functionality 529Setting the Clipboard Contents 529Showing the Flash Player Settings 530Determining How Local Settings and Data Are Saved 531Using Code Pages 531Creating a Catch-All Status Handler 532Determining the Client Computer’s Capabilities 532Getting Audio and Video Capabilities 533Determining Versions 534Getting Screen and Resolution Information 535When Loading SWF Content 536Summary 538
Trang 36Problems with Web Browser Printing 539Providing Proof with Printing 540Creating Art with Output 540Expanding the Potential of Small Documents 540Controlling Printer Output from Flash 542Overview of the PrintJob Class 542Retrieving the User’s Page Settings with PrintJob.start() 542Determining the Print Target and Its Formatting Options 545Potential Problems with the Flash Printed Output 553Adding Print Functionality to Movies 554Creating a Dialog Box for Print Notification 554Working with Hidden Content 558Summary 560
An Introduction to the Sound Class 563Creating a New Sound Object 564Understanding Sound Resources and Timelines 564Scripting Audio with the Sound Class 568Property and Method Overview of the Sound Class 568Properties of the Sound Class 569Reading an MP3 File’s ID3 Tags with Sound.id3 570Loading Methods of the Sound Class 571Playback Methods of the Sound Class 575Transformation Methods of the Sound Class 577Creating and Playing a Linked Sound File 580Loading an External MP3 File 583Controlling the Volume of a Sound Object 588Applying Advanced Effects to Sound Objects 592Making a Looping Playlist 595Summary 597
Working with Flash Video Files 599Making an FLV File in Flash MX 2004 600Using RTMP to Access FLV Files 602Using HTTP to Access FLV Files 603Loading FLV Files into a Flash Movie 604Building an HTTP Connection to an FLV File 605Displaying the NetStream Output in a Video Object 605Checking Status Messages from the NetStream Class 607Scripting Basic Controls for a NetStream Object 609Summary 612
Trang 37Part VII: The Data Classes 613
Saving Data with Shared Objects 615
A Little Bit of Cookie History 616Understanding Local Shared Object Anatomy 616Creating a Local Shared Object 616Setting Values within the Shared Object 617Saving the Shared Object to the Client 617Retrieving the Data 620Conflicts, Domains, and Paths 620Remembering States with Shared Objects 621Communicating with the LocalConnection Class 626Creating a Sending Movie 626Creating a Receiving Movie 627Confirming Receipt 628Sending and Receiving Across Domains 628Summary 630
Working with XML 631XML’s Origins 632Uses of XML 632Writing Well-Formed XML 633XML Declaration 634Tags 634Attributes 635DTD 636Using XML Objects 637Traversing the XML Tree 638Building a Document Tree 644Loading and Sending XML 646Loading and Sending Data with LoadVars 650Creating a LoadVars Object 650Loading Data 650Sending Data 651Sharing Data Across Domains 653Setting Up a Policy File 653Working with a Proxy Script 654Summary 655
Ways of Transmitting Data 657Transmitting Data via HTTP 657Transmitting Data via Sockets 658The Socket Endpoints 658The Server 659The Client 660
Trang 38Installing the Socket Server 663Setting Up the Client 663
Getting Started with V2 Components 673
Naming Component Instances 675Working with the Component Inspector Panel 676Working with the Component APIs 677Understanding the Fundamental UI Component APIs 678Working with Common Component Functionality 679Looking at the Standard Form UI Components 681Working with Button Components 681Working with Label Components 682Working with TextArea Components 685Working with CheckBox Components 686
Working with List Components 693Looking at the Standard Content Display Management Components 697Working with ScrollPane Components 697Working with Loader Components 702Working with ProgressBar Components 702Working with Accordion Components 704Working with DataGrid Components 708
Working with Menu Components 716Working with MenuBar Components 722
Trang 39Working with Component Styles 731Introducing UI Component Styles 732Working with Colors 736Setting Instance Styles 737Setting Instance Styles with a Style Object 737Setting Class Styles 738Setting Global Styles 738Practicing Applying Styles 739Managing Focus 741Creating a FocusManager Instance 741Assigning Tab Order 742Setting Focus Programmatically 742Setting Default Buttons 743Summary 744
Understanding Component Anatomy 745Making Your First Component 746Dispatching Events 750Working with Component Metadata 751Understanding Metadata Tag Use 751Using Inspectable 751Using InspectableList 752Using IconFile 752Practicing Making an Event Dispatching Component 753Building Components Based on the v2 UI Architecture 755Extending v2 Architecture Classes 756Creating v2 Component Movie Clip Symbols 757Practicing Making a v2 Architecture Component 757Working with Styles 761Practicing Working with Styles 762Summary 765
Understanding Flash and HTML 769Passing Initialization Values to Flash from HTML 772Calling JavaScript Functions from Flash 773Sending JavaScript Calls with getURL 773Ensuring Complete Browser Compatibility 774Detecting the Flash Player in Web Browsers 776Manual Player Detection 776Automated Player Detection 776Summary 778
Trang 40Section 508 780W3C Standards 780Microsoft Active Accessibility (MSAA) 781Reviewing Current Assistive Technologies 781Window-Eyes 782JAWS 782Setting Accessibility Options 783Exploring the Accessibility Panel 783Accessible Components 788Tabbing 788Using Keypress Actions 788Detecting and Controlling Accessibility Options with ActionScript 789Checking the State and Presence of a Screen-Reader 789Checking the User’s Browser for Accessibility Compliance 790Scripting Accessibility Properties Dynamically 791Making the Most of Your Accessible Movie 792Summary 793
Using the Stand-Alone Player 795Benefits of the Stand-Alone Environment 796Limitations of the Stand-Alone Environment 797Applying fscommand() Actions with Stand-Alones 798Overview of Commands and Arguments 798Adding Controls to Projector Movies 799Preventing Access to the Desktop 806Executing Other Applications 808Expanding the Potential of the Stand-Alone Projector 808Summary 809
Planning the Scope of Your Project 813Conceptualizing the Master Movie and Flash Content 813Constructing a Flash Asset Architecture 815Loading Content into Flash Movies 821Overview of Objects and Methods 821Building a Basic Preloader for a Flash Movie 824Making a Multipurpose Preloader 831Using Shared Libraries for Font Management 837Preloading a Shared Library 844Summary 845