1. Trang chủ
  2. » Giáo Dục - Đào Tạo

flash 8 actionscript bible

867 201 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Flash 8 ActionScript Bible
Tác giả Joey Lott, Robert Reinhardt
Trường học Wiley Publishing, Inc.
Chuyên ngành Computer animation, Web sites—Design, Flash (Computer file), ActionScript (Computer program language)
Thể loại Book
Năm xuất bản 2006
Thành phố Indianapolis
Định dạng
Số trang 867
Dung lượng 11,79 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

729 Chapter 36: Introducing Flash Remoting.. 771 Chapter 40: Scripting for the Flash Stand-Alone Player... xxv Part I: Getting Started with Flash 8 ActionScript 1 Chapter 1: Introducing

Trang 2

Flash ®

8 ActionScript

Bible Joey Lott and Robert Reinhardt

Trang 4

Flash ®

8 ActionScript

Bible Joey Lott and Robert Reinhardt

Trang 5

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 WEB SITE 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 WEB SITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEB SITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ.

May there be peace within and among all beings This book is dedicated to the light that shines within you and without you

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

Published simultaneously in Canada

46256, (317) 572-3447, fax (317) 572-4355, or online at http://www.wiley.com/go/permissions.

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.

Library of Congress Cataloging-in-Publication Data

1 Computer animation 2 Web sites—Design 3 Flash (Computer file) 4 ActionScript (Computer program language)

I Lott, Joey II Title.

TR897.7.R464 2005

006.6'96—dc22

2005029253

Trademarks: Wiley, the Wiley 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 registered trademark of Macromedia, Inc in the United States and/or other countries 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.

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

Trang 6

About the Authors

Joey Lott has written several books on Flash and ActionScript He lives in Los Angeles Robert Reinhardt, Director of Multimedia Applications for Schematic (www.schematic.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) He has developed multimedia courses for educational facilities in Canada and

the United States and has been a featured speaker at several Web conferences Robert alsoprovides multimedia consulting through his company, [theMAKERS], and is a writing partnerfor CommunityMX.com

Credits Executive Editor

Quality Control Technicians

Laura Albert Leeann Harney

Proofreading and Indexing

TECHBOOKS Production Services

Trang 7

Contents at a Glance

Acknowledgments xxiii

Introduction xxv

Part I: Getting Started with Flash 8 ActionScript 1

Chapter 1: Introducing Flash 8 3

Chapter 2: Learning ActionScript Basics 7

Chapter 3: Constructing ActionScript 25

Chapter 4: Working with Functions 59

Chapter 5: Getting to Know Objects 75

Chapter 6: Debugging and Error Handling 117

Part II: Using Core Classes 147

Chapter 7: Working with Arrays 149

Chapter 8: Using Numbers 171

Chapter 9: Using Math 179

Chapter 10: Working with Dates and Times 189

Chapter 11: Working with Strings 211

Chapter 12: Applying Regular Expressions 225

Part III: Working with Display Objects 241

Chapter 13: Using Display Objects 243

Chapter 14: Working with Movie Clips 269

Chapter 15: Drawing Programmatically 297

Chapter 16: Transforming Colors 333

Chapter 17: Applying Filters 347

Chapter 18: Using the Bitmap API 365

Chapter 19: Working with Text Fields and Selection 397

Chapter 20: Formatting Text 451

Part IV: Scripting Player Control 469

Chapter 21: Managing Mouse and Key Interactivity 471

Chapter 22: Working with the Stage 493

Chapter 23: Using Context Menus 505

Chapter 24: Understanding the Capabilities and Security Objects 513

Chapter 25: Printing 527

Trang 8

Part V: Working with Media 539

Chapter 26: Programming Sound 541

Chapter 27: Managing Video 567

Part VI: Using Components 579

Chapter 28: Using UI Components 581

Chapter 29: Styling UI Components 637

Chapter 30: Creating Custom Components 651

Part VII: Managing Data 669

Chapter 31: Using Shared Objects 671

Chapter 32: Understanding LocalConnection Objects 681

Chapter 33: Programming with the XML and LoadVars Classes 689

Chapter 34: Using Persistent Socket Communications 713

Chapter 35: Using Web Services 729

Chapter 36: Introducing Flash Remoting 735

Chapter 37: Managing File Uploads and Downloads 743

Part VIII: Working with Flash in Context 751

Chapter 38: Working with Flash in the Web Browser 753

Chapter 39: Making Movies Accessible and Universal 771

Chapter 40: Scripting for the Flash Stand-Alone Player 785

Index 797

Trang 10

Acknowledgments xxiii

Introduction xxv

Part I: Getting Started with Flash 8 ActionScript 1 Chapter 1: Introducing Flash 8 3

Understanding the Capabilities of Flash 8 3

Looking at What’s New in Flash 8 4

Getting Started with Flash 8 ActionScript 6

Summary 6

Chapter 2: Learning ActionScript Basics 7

Introducing ActionScript 7

Learning What You Can Do with ActionScript 8

Creating Your First ActionScript 8

Understanding the Event Model: How ActionScript Works 9

Assigning Actions 10

Understanding the Actions Panel 13

Opening the Actions Panel 13

Working with the Actions Toolbox 15

Working with the Script Navigator 16

Working with the Script Pane 17

Managing Scripts 18

Setting Actions Panel Preferences 19

Working with Formatting 21

Using Code Hinting 22

Using the Help Panel 24

Summary 24

Chapter 3: Constructing ActionScript 25

Understanding Datatypes 25

Working with Strings 26

Working with Numbers 27

Using Booleans 28

Understanding the undefined and null Datatypes 28

Casting Data 28

Using Variables 28

Declaring Variables 29

Naming Variables 30

Using Expressions 33

Trang 11

viii Contents

Working with Operators 34

Working with Arithmetic Operators 34

Working with Assignment Operators 35

Working with Comparison Operators 36

Working with Logical Operators 39

Working with String Operators 40

Working with Miscellaneous Operators 40

Understanding Bitwise Operators 42

Considering Operator Precedence 48

Using Comments Effectively 48

Working with Statements 49

Understanding Statement Syntax 50

Using Statements That Control Flow: Control Structures 51

Summary 57

Chapter 4: Working with Functions 59

Understanding Programming with Functions 59

Defining Custom Functions 60

Calling Functions 61

Passing Parameters 61

Passing Parameters by Value or by Reference 63

Working with the arguments Property 64

Returning a Value from a Function 65

Referencing Functions 67

Creating Anonymous Functions 67

Understanding Scope 68

Variable Scope 68

Function Scope 69

Creating Recursion 69

Overloading a Function 70

Writing for Reusability 71

Using Built-In Functions 71

Creating Interval Functions 72

Summary 74

Chapter 5: Getting to Know Objects 75

Introducing Objects 75

Understanding Object Blueprints 75

Creating an Object 76

Accessing Object Properties 77

Accessing Object Methods 78

Working with Static Properties and Methods 78

Adding New Object Properties 79

Adding New Object Methods 79

Defining Event-Handler Methods 80

Telling Objects to Talk to Themselves 81

Displaying the Time with an Object 81

Working with MovieClip Objects 83

Displaying the Time Using a Movie Clip 84

Creating Interval Methods 85

Trang 12

Contents

Understanding the Object Class 86

Creating Object Literals 86

Accessing Associative Array Keys and Values 87

Looping through Object Properties 88

Creating Custom Classes 89

Understanding the Purpose of Custom Classes 89

Working with the Classpath 90

Making AS Files 92

Creating a Simple Class 92

Defining Properties for a Class 93

Defining Methods for a Class 96

Creating a Constructor 96

Adding Static Properties to a Class 97

Adding Static Methods to a Class 98

Making Your First Class 98

Working with Advanced Class Topics 105

Organizing Your Classes with Packages 106

Extending Classes 108

Creating Interfaces 110

Making Dynamic Classes 115

Summary 115

Chapter 6: Debugging and Error Handling 117

Troubleshooting Your Flash Application 118

Discovering Computer System Issues 118

Encountering Bugs in Flash 118

Detecting Errors in the Flash Document 119

Finding Errors in Your Application 120

Detecting Naming Conflicts and Problems 120

Finding Conflicts in Frame Actions 122

Importing Images, MP3s, and Video 122

Publishing Your Movies 123

Including Hidden Layers 124

Fixing Blurry Text 124

Considering External Issues 125

Finding Help in the Flash Community 126

Preventing Errors 127

Planning before Development 127

Using Versioning 127

Testing Your Movie 128

ActionScript Placement 129

Working with Compatible Actions 130

Catching Errors Programmatically 131

Working with Basic try/catch Statements 131

Understanding Error Objects 133

Throwing Exceptions 134

Debugging Your Flash Application 134

Using the Output Panel 134

Debugging Using the Debugger 137

An Exercise in Debugging 143

Summary 145

Trang 13

x Contents

Chapter 7: Working with Arrays 149

Creating Ordered Structures 149

Creating Arrays 150

Adding Values to an Array 151

Removing Elements from an Array 154

Reading Data from Arrays 155

Using Different Types of Arrays 156

Working with Single-Dimension Arrays 156

Working with Parallel Arrays 156

Working with Multidimensional Arrays 158

Working with Arrays of Objects 158

Converting Arrays to Lists 159

Creating New Arrays from Existing Arrays 160

Concatenating Arrays 160

Extracting Subsets of Array Elements 160

Sorting Arrays 161

Sorting Simply 161

Sorting More Complexly 161

Sorting Arrays of Associative Arrays 166

Summary 170

Chapter 8: Using Numbers 171

Understanding Number Types 171

Integers and Floating-Point Numbers 171

Decimal Numbers 172

Other Bases for Numbers 172

Converting Strings to Numbers 173

Casting to a Number 174

Converting to a Number with Precision 174

Detecting When a Number Is Not a Number 175

Dealing with Infinite Values 176

Handling Minimum and Maximum Values 176

Working with Number Instances 176

Summary 177

Chapter 9: Using Math 179

Performing ActionScript Math 179

Learning about ActionScript Math 179

Working with the Math Constants 180

Finding Absolute Values 180

Rounding and Truncating Numbers 181

Generating Random Numbers 182

Finding the Greater or Lesser of Two Numbers 183

Working with Exponents and Square Roots 183

Using Trigonometric Functions in ActionScript 184

Summary 188

Trang 14

Contents

Chapter 10: Working with Dates and Times 189

Working with Computer Dates 189

Creating a Date Object 191

Getting the Current Date and Time 191

Making a Date Based on Epoch Milliseconds 192

Making a Date Based on Year or Month 192

Working with Date Objects 194

Get Methods 196

Set Methods 198

Inherited Methods 200

Static Methods 200

Working with Advanced Date and Time Issues 201

Creating a DateTime Object 208

Working with Date Methods 208

Performing Date Math 208

Displaying the Date 209

Creating a DateTime Object from a Date Object 209

Parsing a Date String into a DateTime Object 209

Detecting Leap Years 209

Summary 210

Chapter 11: Working with Strings 211

Understanding Primitives and Objects 211

Getting and Setting Primitive Values 212

Joining Strings 213

Escaping Characters 213

Nonvisible Characters 214

Avoiding Common Mistakes 215

Working with Character Codes 216

Determining the Number of Characters 216

Working with Substring Values 217

substr 217

substring 218

slice 218

charAt 218

Finding Substrings 219

Getting a Character Code 220

Using Character Codes to Get Characters 220

Converting a String into an Array 220

Changing the Case of a String 221

Passing String Values to and from Applications 222

Summary 223

Chapter 12: Applying Regular Expressions 225

Understanding Regular Expressions 225

Looking at How Regular Expressions Work 226

Case-Sensitivity, Global Pattern Matching, and Multiline Matches 226

Creating More Complex Patterns 227

Trang 15

xii Contents

Working with the RegExp Class 232

If You Know JavaScript 232

Creating a Regular Expression Object 233

Matching Using a Regular Expression Object 234

String Methods and Regular Expressions 238

The Top-Level RegExp Object 239

Summary 240

Part III: Working with Display Objects 241 Chapter 13: Using Display Objects 243

Creating Display Objects at Authoring Time 244

Addressing Display Objects 244

Targeting Nested Instances 245

Working with Absolute Addressing 245

Working with Relative Addressing 246

Accessing Nested Instances with Array-Access Notation 247

Handling Events 248

Handling Button Events 249

Handling MovieClip Events 249

Focus Events 250

Using MovieClip Objects as Buttons 250

Practicing Targeting 251

Working with Appearance Properties 253

Working with Coordinates 253

Working with Dimensions 254

Working with Self-Describing Properties 259

Tweening Programmatically 259

Starting a New Tween 260

Adding Easing to Programmatic Tweens 260

Pausing and Resuming Tweens 262

Additional Methods for Tween Objects 263

Adding Listeners to Tween Objects 263

Enabling Button-Like Behavior 264

Tab-Switching, Focus, and Menus 265

MovieClip-Specific Tab-Switching and Focus-Related Properties 266

Tracking Objects As Menus 267

Summary 267

Chapter 14: Working with Movie Clips 269

Affecting Timeline Playback 269

Creating MovieClip Objects Programmatically 270

Understanding Stacking Order within Flash Movies 270

Creating Duplicate MovieClip Objects 272

Adding MovieClip Objects from the Library Programmatically 273

Working with Initialization Objects 275

Creating Empty MovieClip Objects 276

Removing MovieClip Objects 277

Trang 16

Contents

Loading External Content 277

Loading SWF Content 278

Loading Image Content 279

Monitoring Loading 280

Unloading Content 281

Opening Web Pages 281

Creating Draggable MovieClip Objects 283

Telling Flash to Start Dragging a MovieClip 283

Telling Flash to Stop Dragging a MovieClip 284

Checking for Overlapping 284

Working with Coordinate Spaces 285

Creating Scriptable Masks 286

Practicing Attaching and Dragging MovieClip Objects 286

Practicing Checking for Overlaps and Loading Content 289

Optimizing Playback with Cached Bitmap Surfaces 293

Summary 296

Chapter 15: Drawing Programmatically 297

Introducing the Drawing API 297

Setting a Line Style 297

Moving the Pen without Drawing 301

Drawing a Straight Line 301

Drawing a Curve 302

Adding a Simple One-Color Fill 302

Adding a Bitmap Fill 303

Working with Gradients 306

Clearing Previously Drawn Graphics 309

Working with a Drawing Utilities Class 309

Getting Started with DrawingUtilities 310

Drawing Rectangles 310

Drawing Circles 311

Drawing Regular Polygons 312

Drawing Fills 312

Practicing Dynamic Masking 315

Practicing Responsive Objects 318

Practicing Drawing 326

Summary 331

Chapter 16: Transforming Colors 333

Working with Matrix Transforms 333

Using Matrix Transformations 336

Working with Color Transforms 340

Applying Color Transforms 341

Getting and Setting the Color 341

Tinting a MovieClip 342

Resetting Colors 343

Transforming Colors 343

Summary 345

Trang 17

xiv Contents

Chapter 17: Applying Filters 347

Applying a Filter 348

Adding the Bevel Filter 349

Adding the Blur Filter 350

Adding the Drop Shadow Filter 351

Adding the Glow Filter 352

Adding the Gradient Bevel Filter 353

Adding the Gradient Glow Filter 354

Adding the Color Matrix Filter 354

Adding the Convolution Filter 360

Adding the Displacement Map Filter 361

Adding More Than One Filter 362

Rotating Objects with Filters 363

Summary 364

Chapter 18: Using the Bitmap API 365

Constructing a BitmapData Object 365

Using the Constructor Method 365

Loading a Library Item 366

Displaying BitmapData Images 366

Working with BitmapData Properties 367

Copying Images 368

Copying from MovieClips 368

Loading BitmapData Images 372

Copying from BitmapData Objects 374

Applying Color Transformations 382

Applying Fills 383

Applying Rectangular Fills 383

Applying Flood Fills 383

Applying Effects 384

Replacing Colors with Threshold 384

Using Pixel Dissolves 386

Remapping the Color Palette 387

Making Noise 389

Adding Noise 389

Adding Perlin Noise 391

Applying Filters 394

Summary 395

Chapter 19: Working with Text Fields and Selection 397

Understanding Types of Text 397

Dynamic Text 397

Input Text 398

Creating TextField Objects 398

Making Text at Authoring Time 398

Making Runtime Text 400

Working with TextField Object Basics 401

Understanding Basic TextField Properties and Methods 401

Adding Text 402

Managing Multiline Text 402

Resizing a TextField Object 404

Trang 18

Contents

Making Text Unselectable 405

Setting Border and Background 405

Creating Input Text 406

Managing Input 406

Creating Password Text 407

Changing Text Color 408

Removing Text 409

Creating a Simple Notes Application 409

Using HTML with TextField Objects 411

Rendering HTML in Text 412

Inserting Special Characters into HTML Fields 413

Adding Hyperlinks to Text 414

Adding Mail Links 416

Calling JavaScript Functions 416

Calling ActionScript Functions from Text 417

Embedding Content in Text 417

Creating an HTML-Based Information Viewer 419

Scrolling Text 421

Scrolling Text Vertically 422

Scrolling Text Horizontally 423

Scrolling Text with Scrollbars 423

Scrolling by Pixels 425

Using Events for Text Fields 429

Detecting Text Changes 429

Detecting Focus Changes 429

Detecting Scrolling 430

Adding Listeners to TextField Objects 431

Detecting Text Changes 431

Detecting Scrolling 431

Working with Fonts 432

Embedding Fonts 432

Using Flash Device Fonts 437

Inserting Special Characters into Editable Text Fields 437

Working with Advanced Anti-Aliasing 438

Setting the Anti-Aliasing Type 438

Setting the Grid Fit Type 439

Creating a Random Letter Displayer 442

Understanding the Selection Class 444

Working with Focus 444

Working with Selection 445

Replacing Selected Text 447

Working with Tab Order 448

Enabling and Disabling Tab-Initiated Focus 448

Changing Tab Order 448

Summary 449

Chapter 20: Formatting Text 451

Working with TextFormat 451

Creating a TextFormat Object 452

Assigning Formatting to a TextField Object 452

Understanding Formatting Properties 454

Determining Text Metrics 460

Getting the TextFormat 461

Trang 19

xvi Contents

Working with Cascading Style Sheets 462

Understanding CSS 462

Creating a StyleSheet Object 464

Adding Styles with ActionScript 464

Applying Styles to Text 465

Formatting an HTML Article with CSS 465

Loading External CSS 466

Formatting HTML with CSS Loaded from an External File 467

Summary 468

Part IV: Scripting Player Control 469 Chapter 21: Managing Mouse and Key Interactivity 471

Using the Mouse Class to Control the Cursor 471

Working with Mouse Listeners 472

Showing and Hiding the Mouse Cursor 475

Attaching a Custom Graphic to the Cursor 477

Using updateAfterEvent( ) for Mouse Moves 479

Detecting Key Events with the Key Class 481

Property and Method Overview of the Key Class 482

Detecting Key Events 482

Determining Which Key Is Causing the Event 483

Nudging a MovieClip Object with the Arrow Key 486

Dealing with Key Repeater Settings 488

Detecting Keypress Combinations 490

Summary 492

Chapter 22: Working with the Stage 493

Controlling the Movie’s Stage 493

Understanding the Viewing Area 493

Changing the Scale Behavior with Stage.scaleMode 495

Controlling the Movie’s Alignment with Stage.align 495

Reporting the Movie’s Width with Stage.width 496

Reporting the Movie’s Height with Stage.height 496

Detecting a New Player Size 500

Controlling Placement of Elements According to Stage Size 501

Summary 503

Chapter 23: Using Context Menus 505

Controlling the Standard Flash Player Context Menu Display 505

Using the ContextMenu Class 506

Controlling Flash Player’s Built-in Menu 507

Building Custom Menu Items with the ContextMenuItem Class 508

Summary 512

Trang 20

Contents

Chapter 24: Understanding the Capabilities and Security Objects 513

Using the Top-Level System Functionality 513

Setting the Clipboard Contents 514

Showing the Flash Player Settings 514

Determining How Local Settings and Data Are Saved 515

Using Code Pages 515

Creating a Catch-All Status Handler 515

Determining the Client Computer’s Capabilities 516

Getting Audio and Video Capabilities 516

Determining Versions 518

Getting Screen and Resolution Information 519

Working with Player Security When Loading SWF Content 520

Using the IME 523

Checking for the IME 523

Enabling the IME 524

Setting the Conversion Mode 524

Converting Strings 524

Summary 525

Chapter 25: Printing 527

Why Print from Flash? 527

Controlling Printer Output from Flash 529

Introducing the PrintJob Class 529

Starting a Print Request 529

Determining the Print Target and Its Formatting Options 530

Potential Issues with the Flash Printed Output 533

Adding Print Functionality to Applications 533

Summary 538

Part V: Working with Media 539 Chapter 26: Programming Sound 541

An Introduction to the Sound Class 541

Creating a New Sound Object 541

Understanding Sound Resources and Timelines 542

Scripting Audio with the Sound Class 542

Loading Methods of the Sound Class 543

Managing Playback 546

Reading an MP3 File’s ID3 Tags 549

Applying Sound Transforms 550

Attaching and Managing Playback of a Sound 553

Loading MP3 Sounds 556

Managing Volume and Pan 559

Working with ID3 Data 562

Summary 566

Trang 21

xviii Contents

Chapter 27: Managing Video 567

Working with Flash Video Files 567

Making an FLV File with the Flash Video Encoder 567

Using RTMP to Access FLV Files 568

Using HTTP to Access FLV Files 569

Loading FLV Files into a Flash Movie 570

Adding a Video Object 570

Building an HTTP Connection to an FLV File 570

Displaying the NetStream Data in a Video Object 571

Checking Status Messages from the NetStream Class 571

Retrieving Metadata 572

Scripting Basic Controls for a NetStream Object 572

Pausing FLV Playback 572

Jumping to Specific Points 573

Stopping the Video 573

Displaying Playback Progress 573

Configuring Video Dimensions 574

Building a FLV Playback Application 574

Adding Captions 575

Summary 577

Part VI: Using Components 579 Chapter 28: Using UI Components 581

Introducing the Components Panel 581

Adding New Component Instances 582

Naming Component Instances 583

Setting Component Parameters 584

Working with the Component Inspector Panel 584

Working with the Component APIs 585

Understanding the Fundamental UI Component APIs 585

Working with Listener Objects 585

Working with Common Component Functionality 587

Looking at the Standard Form UI Components 588

Working with Button Components 588

Working with Label Components 589

Working with TextInput Components 590

Working with TextArea Components 592

Working with CheckBox Components 593

Working with RadioButton Components 594

Working with ComboBox Components 596

Working with List Components 600

Working with NumericStepper Components 603

Looking at the Standard Content Display Management Components 604

Working with ScrollPane Components 604

Working with Window Components 606

Working with Loader Components 609

Working with ProgressBar Components 610

Trang 22

Contents

Looking at the Professional UI Components 611Working with Accordion Components 612Working with the Alert Component 613Working with DataGrid Components 615Working with DateChooser Components 619Working with DateField Components 621Working with Menu Components 622Working with MenuBar Components 629Working with Tree Components 631Summary 635

Chapter 29: Styling UI Components 637

Working with Component Styles 637Introducing UI Component Styles 638Working with Colors 642Setting Instance Styles 643Setting Instance Styles with a Style Object 643Setting Class Styles 644Setting Global Styles 645Practicing Applying Styles 645Managing Focus 648Creating a FocusManager Instance 648Assigning Tab Order 648Setting Focus Programmatically 649Setting Default Buttons 649Summary 650

Chapter 30: Creating Custom Components 651

Understanding Component Anatomy 651Making Your First Component 652Working with Component Metadata 656Understanding Metadata Tag Use 656Using Inspectable 656Using InspectableList 657Using IconFile 657Using Metatags with the Slider Component 658Dispatching Events 660Dispatching Events from the Slider Component 661Working with Compiled Components 662Compiling Clips 663Exporting SWC Files 663Using Live Preview 663Setting the Dimensions of a Component 663Adding Live Preview to the Slider Component 664Distributing and Installing Components 667Installing Components 667Using the Extension Manager 668Summary 668

Trang 23

xx Contents

Chapter 31: Using Shared Objects 671

Saving Data with Shared Objects 671

A Little Bit of History 671Understanding Local Shared Object Anatomy 672Creating a Local Shared Object 672Setting Values within the Shared Object 672Saving the Shared Object to the Client 673Retrieving the Data 675Conflicts, Domains, and Paths 676Remembering States with Shared Objects 677Summary 680

Chapter 32: Understanding LocalConnection Objects 681

Creating a Sending Movie 681Sending Parameters 682Checking the Status of a Send 682Creating a Receiving Movie 682Confirming Receipt 683Sending and Receiving across Domains 684The Sending Movie 684The Receiving Movie 684Summary 687

Chapter 33: Programming with the XML and LoadVars Classes 689

Working with XML 689XML’s Origins 690Uses of XML 690Writing Well-Formed XML 691XML Declaration 692Tags 692Attributes 693DTD 694Using XML Objects 695Traversing the XML Tree 697Building a Document Tree 702Loading and Sending XML 704Loading and Sending Data with LoadVars 707Creating a LoadVars Object 707Loading Data 707Sending Data 708Sharing Data across Domains 709Configuring a Policy File 710Working with a Proxy Script 710Summary 711

Trang 24

Contents

Chapter 34: Using Persistent Socket Communications 713

Ways of Transmitting Data 713Transmitting Data via HTTP 713Transmitting Data via Sockets 714The Socket End Points 714The Server 715The Client 716Working with XMLSocket Objects in Flash Clients 716Creating a Socket Connection to the Server 717Sending and Receiving Data 718Closing a Socket Connection 718Creating a Chat Client 719Installing the Java Runtime Environment 719Installing the Socket Server 719Setting Up the Client 720Summary 727

Chapter 35: Using Web Services 729

Working with Web Services 729Calling Web Services with WebService 730Taking a Flash Survey 731Dealing with Security Issues 732Summary 733

Chapter 36: Introducing Flash Remoting 735

Introducing Flash Remoting 735The Flash Remoting Client 736The Flash Remoting Gateway 736Flash Remoting Services 736Writing Flash Remoting ActionScript 736Using NetConnection 737Using the ActionScript 2.0 API 738Using the NetConnection Debugger 739Taking a Flash Survey 740Summary 741

Chapter 37: Managing File Uploads and Downloads 743

Introducing FileReference 743Uploading Files 744Selecting a File to Upload 744Determining When a File Is Selected 745Retrieving File Properties 745Uploading a File 746Adding Uploading Capabilities to an Application 747Downloading a File 749Summary 749

Trang 25

xxii Contents

Chapter 38: Working with Flash in the Web Browser 753

Understanding Flash and HTML 753Passing Initialization Values to Flash from HTML 755Communicating with JavaScript and Flash 757Calling JavaScript Functions from Flash — The Simple Ways 757Using ExternalInterface with Flash 8 758Using the Flash/JavaScript Integration Kit 764Detecting the Flash Player in Web Browsers 769Manual Player Detection 769Automated Player Detection 769Summary 770

Chapter 39: Making Movies Accessible and Universal 771

Standardizing Accessibility Concerns 771Section 508 772W3C Standards 772Microsoft Active Accessibility (MSAA) 773Reviewing Current Assistive Technologies 773Window-Eyes 774JAWS 774Setting Accessibility Options 774Exploring the Accessibility Panel 775Accessible Components 778Tabbing 779Using Keypress Actions 779Detecting and Controlling Accessibility Options with ActionScript 780Checking the State and Presence of a Screen Reader 780Checking the User’s Browser for Accessibility Compliance 781Scripting Accessibility Properties Dynamically 781Making the Most of Your Accessible Movie 782Summary 784

Chapter 40: Scripting for the Flash Stand-Alone Player 785

Using the Stand-Alone Player 785Benefits of the Stand-Alone Environment 786Limitations of the Stand-Alone Environment 787Applying fscommand( ) Actions with Stand-Alones 787Overview of Commands and Parameters 787Adding Controls to Projector Movies 789Preventing Access to the Desktop 794Executing Other Applications 794Expanding the Potential of the Stand-Alone Projector 795Summary 795Index 797

Trang 26

Thanks to Margot Maley Hutchinson of Waterside for picking up this project.

The Flash team at Macromedia continues to be a great resource, and we’d like to thank everyperson on the team for the help they provided In particular, we’d like to thank Gary Grossman,Erica Norton, Matt Wobensmith, Werner Sharp, Nivesh Rajbhandari, Mike Downey, Jen deHaan,and Peter deHaan

The Flash community is a great resource Many thanks to those that are willing to ask tions, speak about differing points of view, challenge popular wisdom, and publish theirinvestigations and discoveries That makes learning ActionScript so much more accessible

ques-And thank you It is you, the readers that make this book possible ques-And your comments help

improve each edition

Joey’s acknowledgments: Robert, my friend, thank you for everything Thank you for seeing

the potential, and for opening the opportunity to work on this book Thank you to my parents,

my sister, and everyone that has given so generously of their friendship, love, and support.Thanks from beyond the beyond for all that is

Trang 28

Flash has begun to mature as a product, and ActionScript has begun to mature as a guage That represents both opportunity and challenge to you As a mature language,ActionScript provides a broad spectrum of features and functionality The possibilities arelimitless: There is great opportunity to build new, innovative, useful, and interesting applica-tions using Flash and ActionScript However, with that opportunity comes the challenge oflearning how to use ActionScript effectively If you want to express your thoughts and feelingswell, you need the right language for communicating them Likewise, with ActionScript thechallenge is to learn the language so that there is a natural flow of expression that is seamlessfrom its conception to its manifestation in code

lan-Our goal with this book is to provide you with the resources to learn the language so that you can express yourself elegantly and eloquently We make every attempt to meet you rightwhere you are in your journey, and to provide you with the support to get where you want to

go As you can see by the page count of this book, ActionScript is not a short topic In fact,

if you’re new to ActionScript it may seem overwhelming However, it’s our intention to makelearning ActionScript accessible In this book, you’ll find that we’ve organized the topics in away that we feel is most accessible to readers

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 might benefit from a review of basic programming, we encourage you to read Part I first.Parts II and III are essential for nearly anyone who wants to use ActionScript Whether you’renew to programming or simply new to ActionScript, you’ll want to read those chapters.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

Intermediate and advanced ActionScript developers can also benefit from the book You canturn to any chapter as a reference Even an advanced ActionScript developer might not knowall the details about a particular topic, or what’s changed in the newest version of Flash Ifyou want to update your knowledge, learn more about a topic, or just brush up on it, read thechapter for reference

Keep the book on your desk Read sections over and over Try the exercises You’ll learn moreeach time At first, just getting a MovieClip object to move across the screen may be difficult.But upon returning to the same exercise months later, you will undoubtedly discover some-thing you didn’t notice before

Trang 29

xxvi Introduction

Conventions Used in the Book

Throughout the book, when we refer to application menus, the menu names and nested menuitems are separated by arrow icons For example, to open a new Flash document within Flash

8, you can select the New option from the File menu We indicate that in the text by ing you choose File ➪ New

suggest-Although the icons are pretty standard and self-explanatory (they have self-explanatorylabels), here’s a brief explanation of what they are and what they mean

Tips offer you extra information that further explains a given topic or technique, often gesting alternatives or workarounds to a listed procedure

sug-Notes provide supplementary information to the text, shedding light on background cesses or miscellaneous options that aren’t crucial to the basic understanding of the material

pro-If you want to find related information to a given topic in another chapter or section, look forthe cross-reference icon

When you see this icon, you will find Web URLs that point to further information about thetopic at hand

This icon points out files or other material available on the book’s web site

This icon indicates a new important feature to the specific application

Also, many code samples that are printed in this book have lines of code that are too long tofit on one line These lines of code are broken into two or more lines and end with the linecontinuation symbol, ; This symbol should not be typed into the actual code of your Flashdocument Simply continue to type the following line(s) of code on the same line in the Actionspanel For example, you would type the following line all on the same line in the Actions panel:mPhoto._accProps.description = “Picture of attendees at the round table ;discussion”;

Because Flash is available for both the Windows and Mac OS X operating systems, whenapplicable we provide keyboard shortcuts for both In many cases the Ctrl key in a Windowsenvironment is analogous to the Command key on the Macintosh, which we represent usingthe Ô symbol You’ll also notice that many keyboard shortcuts are denoted using a + symbolwhen Flash requires that you press several keys at the same time For example, the notationShift+N indicates that you should press and hold the Shift key while then pressing the N key

New

Feature

Web Resource

Cross-Reference

Note Tip

Trang 30

Introduction

How This Book Is Organized

We’ve reorganized this edition of the book in ways that we think will make it most able and helpful The eight parts of the book are outlined in the following sections

approach-Part I: Getting Started with Flash 8 ActionScript

When you build a building, the first thing you do is lay the foundation Doing so helps toensure a sturdy base from which something can be created Part I aims to provide you withbasic information and practical exercises that can assist you in getting a fundamental under-standing of ActionScript and programming in general You’ll learn all about how ActionScriptworks, where to place it, how to write it, syntax, structure, and much more

Part II: Using Core Classes

In Part II you’ll learn about some of the core classes in ActionScript Flash 8 ActionScript isbased on the ECMA specification Although ActionScript introduces features beyond thescope of the ECMA specification, it also incorporates the core functionality Therefore, thecore classes are those classes that are part of the ECMA specification—classes such as Array,Date, Number, and Math You’ll use the core classes in nearly every ActionScript project

Part III: Working with Display Objects

Flash has a library of classes for representing data visually Those classes define objects that

wecall display objects—objects such as movie clips, buttons, text fields, and so forth In Part III

you’ll learn about working with display objects You learn basics such as using buttons, movieclips, and text fields You’ll also learn more advanced topics such as programmatic drawing,filter effects, and working with bitmap data

Part IV: Scripting Player Control

In Part IV you can learn about working with player-level classes You’ll learn to script mouseand key detection, work with context menus, and determine how content will scale within theplayer You’ll also learn how to print Flash content, and how to detect the user’s Flash Playercapabilities

Part V: Working with Media

Some of the most popular features of Flash involve working with media such as sound andaudio In Part V you can read about using the Sound class to programmatically work withsound You’ll also learn how to use the NetStream and Video classes to work with video

Part VI: Using Components

By encapsulating functionality, components can provide a simple drag-and-drop solution towhat might otherwise require hundreds or even thousands of lines of code In Part VI you’lllearn about the user interface components that are included with Flash, as well as how to create your own components

Trang 31

xxviii Introduction

Part VII: Managing Data

Part VII discusses how to manage data using ActionScript Flash Player has many data capabilities, and in Part VII you can read about each You’ll learn how to send data acrossFlash Player instances using LocalConnection, and how to store locally persistent datausing SharedObject You’ll also learn how to use URL-encoded data and XML data, how towork with socket connections, web services, Flash Remoting, and file uploads and downloads

Part VIII: Working with Flash in Context

Flash content can be used in many contexts While the possibilities are limitless, you can readabout some common ways in which you’re likely to use Flash content In Part VIII you learnhow to use Flash content in a browser, how to make content accessible, and how to buildstand-alone Flash content

Getting in Touch with Us

The official web site for this book is:

www.rightactionscript.com/asb

At the site you’ll find code examples, updates, notes, and more

You can also find the code examples at:

www.wiley.com/go/actionscriptbible

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 usknow that as well You can contact Joey by email at 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, the better equipped they are to adapt Flash to yourrequests In order to hear from you, Macromedia has set up a system by which you can sub-mit your feedback at:

www.macromedia.com/support/email/wishform/?6213=9

If there are features that work particularly well for you, let Macromedia know If there are features that are not working for you, let them know And if there are things that Flash doesnot do that you’d like it to do, let Macromedia know that as well

Regardless of your geographic location, you always have access to the global Flash communityfor support and the latest information through the Macromedia Online Forums:

http://webforums.macromedia.com/flashYou can also visit Macromedia’s new Designer & Developer Center, where you can find the latest news and tutorials for Macromedia software:

www.macromedia.com/devnetFor inspiration and motivation, check out the site of the day, weekly features, and case studies at:www.macromedia.com/showcase

Trang 32

Getting Started with Flash 8

Chapter 3

ConstructingActionScript

Chapter 4

Working with Functions

Chapter 5

Getting to KnowObjects

Chapter 6

Debugging and Error Handling

I

Trang 34

Introducing Flash 8

With Flash 8, you can build a tremendous variety of projects —from games to commerce applications to prototypes andbeyond Regardless of the type of project, there are some commonthreads when building Flash applications One of those commonthreads is the subject of this book — ActionScript In this chapter,we’ll look at the sorts of things you can do with ActionScript in Flash

8 We’ll also discuss the new features so that you can get a sense ofwhat topics you’ll be able to learn in this book

Understanding the Capabilities

of Flash 8

The Macromedia Flash authoring tool was originally an animationtool, but it is so much more than that today From the early dayswhen it was known as FutureSplash to the Flash 8 version today,Flash has always excelled as a vector-drawing and animation tool

Even though animation is still a large part of what Flash does, now it

is only a fraction of the Flash toolset Here are the broad categoriesavailable in Flash 8 authoring:

✦ Vector graphics — Vector drawings are made up of many lines

and curves and fills, each defined by a set of coordinates andthe paths along them These paths — vectors — are describedvia mathematical functions Because mathematical formulasare used to store and create the image, they are resolution-independent and can be resized arbitrarily smaller or largerwith no loss of quality Also, images based on calculations aregenerally smaller in file size than bitmap images, which is anadvantage for bandwidth-limited Web delivery

✦ Bitmap graphics — Bitmap (a.k.a raster) images are made up

of a grid of pixels Every pixel’s color and location in the gridmust be stored individually, which usually (but not always)means larger file sizes than images made of vector calculations

Although Flash handles bitmap graphics, the program is notbuilt for direct image manipulation on a pixel level; rather, Flash

is primarily an image handler Flash can retain JPEG sion of imported JPEG files, as well as apply lossless or customlossy compression to imported bitmap images

Trang 35

4 Part I ✦ Getting Started with Flash 8 ActionScript

✦ Animation — Flash is an excellent tool for vector animation, given that the native file

format is vector-based Color and alpha effects can be applied over time by usingFlash’s built-in tweening, by using a series of manually modified keyframes, or by con-trolling symbols with ActionScript Time-based animations can also be streamed sothat playback can begin before the entire Flash movie has downloaded into the FlashPlayer

✦ Multimedia authoring — Flash can import a wide range of media formats in addition to

standard vector and bitmap image formats For example, Flash is capable of importingvideo directly into the authoring environment Flash can also import audio files in mostcommon formats at author-time or dynamically stream MP3 audio at runtime Both ofthese can be used to enhance your productions and animations You can manipulatethese assets with ActionScript and add interactive functionality to them

✦ Dynamic content — Flash can incorporate dynamically loaded information into your

productions Text, images, and MP3s can be loaded into the movie at runtime, andinformation can also be sent from the movie to a server or database

✦ Rich Internet Applications — Since the release of Flash MX, Macromedia has coined

the term Rich Internet Applications, or RIAs, to refer to a new breed of Web tions that use Flash Player technology to access sophisticated enterprise-level serverapplications Several technologies have been developed by Macromedia, includingFlash Remoting and Flash Communication Server (also known as FlashCom, or FCS),

applica-to add enterprise-level features applica-to Flash content Flash Remoting is the fastest means

of sending and receiving data from a Flash movie to server-side applications, whereasFlash Communication Server can enable simultaneous interaction among several users

in real time FlashCom can also deliver live or prerecorded audio/video to Flash movies

as well

The preceding list is only a general overview of some of the capabilities of Flash Don’t thinkthat you have to be limited by that list Flash can be a great tool for rapid prototyping ofapplications, it’s often an easy way to build simple utility applications (data viewers/parsers,slideshow presentations, etc.), and you’ll likely find more unusual ways to use Flash as well

Looking at What’s New in Flash 8

Flash is a product that practically defies definition Flash 8, the latest version of Flash, doesn’t

do anything to help anyone impose limits on the application It adds new functionality,improved compile time, improved player performance This section offers a look at some ofthe new features of Flash 8

✦ Improved text rendering — One of the features of Flash Player 8 that Macromedia likes

to brag about is the new Saffron text engine Saffron is a technology that significantlyimproves font rendering at small point sizes Flash Player 8 integrates the new textengine seamlessly, and you will likely notice font-rendering improvements without anyextra coding It also adds a few new properties to text fields that enable you to managethe font rendering programmatically In Flash Player 8, you can programmatically con-trol the font thickness and sharpness You can also control how the text aligns to thepixel grid, which enables text to appear more legibly at smaller font sizes

✦ Programming bitmaps — One of the neatest new features of Flash 8 is the BitmapData

class The BitmapData class lets you work with bitmaps programmatically You cancopy nearly any graphical data to a BitmapData object — whether from a movie clip

or even from a video frame — and apply lots of effects or modify the pixels

Trang 36

Chapter 1 ✦ Introducing Flash 8

✦ Bitmap caching — Although one of the benefits of Flash Player is that it can render

vector data (which is much more bandwidth-friendly than raster graphics), it can alsohave difficulty rendering complex vector data When a vector movie clip moves, FlashPlayer redraws the artwork from the vector data Even if the movie clip simply movesone pixel to the left, Flash Player has to redraw the entire movie clip For simple vec-tors, that’s okay But when the vectors are complex, it can be difficult for Flash Player

The effect is that animations can playback slowly or unevenly

Flash Player 8 introduces bitmap caching Using bitmap caching, you can tell FlashPlayer to treat a movie clip like a bitmap surface rather than a vector That means thatwhen the movie clip moves, the bitmap surface is simply translated, and Flash Playerdoesn’t have to redraw anything Used judiciously, the bitmap caching feature can drastically improve playback of some animations

✦ Blend Modes — Blend modes let you specify how an object will appear in relation to

everything underneath it

✦ Filters — Filters offer a vast new array of runtime-applied effects, from blurs and drop

shadows to complex color transforms Filters enable effects that Flash alone simplycould not accomplish previously The filters are scriptable, and you can programmati-cally adjust the settings at runtime in order to achieve animated effects

✦ Improved JavaScript and browser interaction — Integrating Flash into a container was

frequently dubious at best The new ExternalInterface class simplifies and improvesFlash Player connectivity to the container application In many cases, that means Webbrowsers and JavaScript Using ExternalInterface, not only can you call JavaScriptfunctions from Flash, but you can reliably call ActionScript functions from JavaScript

as well

✦ File uploading and downloading functionality — Until Flash 8, HyperText Markup

Language (HTML) forms had one major advantage over Flash in that they allowed theuser to browse to and upload a file, while Flash did not However, Flash 8 resolves thatissue with the new FileReference class Using FileReference, it is possible to allow auser to open a file browse dialog box and upload that file to a server from Flash You nolonger have to use pop-up HTML forms or any of the workarounds devised previously

✦ Loading PNG, GIF, and Progressive JPEG files — Flash Player 6 and Flash Player 7 were

capable of loading nonprogressive JPEG content at runtime However, they did not loadprogressive JPEG, GIF, or PNG content — all of which are supported in Flash Player 8

Using the same APIs used to load standard JPEG files, you can now load any of thoseformats at runtime

✦ IME — For those building applications for use with non-ASCII character sets, the IME

class provides improved support for input method editors (IMEs)

✦ New drawing features — Flash Player 8 has new drawing features that translate to

the ActionScript drawing API Specifically, Flash Player 8 lets you manage options likewhether or not to scale the thickness of lines as the container movie clips are scaled,what type of line end caps to use (round, square, or none), and how to join lines(round, bevel, or using miter joints)

New to Flash Player 8, you can also apply gradients to lines, and there are advancedcontrols over gradients in general Plus, you can apply bitmap fills programmatically

✦ New video codec — Flash Player 8 supports a new video codec — On2 VP6 The new codec

not only means better-quality video, but it also supports alpha channel encoding Thatmeans that you can playback Flash video with an encoded alpha channel, and content onlayers underneath the video will be displayed through transparent sections of the video

Trang 37

6 Part I ✦ Getting Started with Flash 8 ActionScript

Getting Started with Flash 8 ActionScript

Flash is far too complex and intricate a topic to discuss in complete detail within one book

For that reason, the Flash 8 ActionScript Bible focuses on ActionScript, rather than the Flash

IDE and related topics such as timelines, motion and shape tweens, making symbols, and thelike I assume that if you are reading this book you are already familiar and comfortable withthe basics of the Flash IDE and the associated concepts You don’t have to be a Flash expert

to learn from this book However, you do need to know what keyframes and movie clip bols are

sym-For a great general reference on Flash, see the latest edition of the Flash Bible series from

Wiley Publishing

Assuming that you’re comfortable with the basics of Flash, the next chapter introduces you

to the basics of ActionScript

We’d like to know what you thought about this chapter Visit www.rightactionscript.com/asb/commentsto fill out an online form with your comments

Trang 38

Learning ActionScript Basics

Before you can effectively start working with anything new, youfirst have to do a few things:

✦ Gather a general overview of the topic, understanding thescope of what you can hope to accomplish

✦ Learn the basic mechanics of the medium In other words, you want to have a broad understanding of how the pieces fit together to make a whole

✦ Familiarize yourself with the tools of the trade, so to speak

You want to be comfortable with the environment within which you are working

This chapter covers each of these fundamentals so you can beginworking with ActionScript First, you learn about what ActionScript isand what it can do Then, you read about how ActionScript functions

at a very high level And last, you become familiar with the Actionspanel, which is the initial “command center” for ActionScript withinFlash

Introducing ActionScript

ActionScript is the programming language used to send instructions

to your Flash movie It is how you “talk” to your Flash movie, telling itexactly what you want it to do The more effectively and fluently youare able to communicate in ActionScript, the more effective you will

be in creating Flash movies that do what you want

This book uses the terms coding, scripting, and programming

interchangeably Although each is sometimes used in a more cific context, nothing is implied by using one term over the other

spe-in each spe-instance

To help you understand what ActionScript is, it is helpful to stand the similarities between ActionScript and something youalready know — human languages Any human language is merely acollection of symbols and sounds used to represent ideas The same

under-is true of any programming or scripting language ActionScript, forexample, is merely a collection of words and symbols with the pur-pose of communicating instructions to the Flash movie Additionally,human languages have syntax and vocabulary that are specific tothat language, but not wholly dissimilar to those of other languages

to author your code

Trang 39

8 Part I ✦ Getting Started with Flash 8 ActionScript

The same is true of scripting languages Not only is ActionScript similar to other scripting languages in many ways, but you may also find that with the right perspective it is quite similar to the English language

Programming languages are in many ways remarkably similar to the languages humans use

to communicate Therefore, although hearing a foreign language might seem like gibberish

at first, with a little training, you can begin to share your ideas with people in a language theyunderstand It is much the same with ActionScript Think of this book as your language teacher.You’ll start in this chapter by developing an understanding of the ActionScript culture, theenvironment, and the tools you can use to begin your ActionScript journey Then, in Chapter 3you look at and investigate the parts of speech and the syntax and structure With these fun-damentals under your belt, you’ll be well on your way to communicating with Flash

ActionScript is based on the ECMA-262 specification, although it does not adhere to it fully If youwant to learn more, you can read about it at the ECMA web site at www.ecma-international.org

Learning What You Can Do with ActionScript

Before you dive into the details of ActionScript, let’s first briefly discuss what you can do with

it Presumably, you already have at least some minimal experience with Flash, and you arefamiliar with the playback of the timeline The default behavior in Flash is such that when

an SWF (the compiled Flash movie format) is opened in a player, the timeline begins to playautomatically In many cases, this is not, in and of itself, problematic However, when the play-head reaches the end of the timeline, it then loops back to the beginning of the timeline andstarts playing it again Often you want an animation to play only one time and then stop atthe end To prevent the Flash movie from looping the playback, you actually have to give itthe instruction to stop You can do this by placing one line of code on the last frame Thatone line of code looks like this:

stop();

With this first command, you can see that ActionScript really can read very much like English.The command (or statement) stop() instructs the Flash movie to stop playback Of course,you can do many more complex things with ActionScript besides a simple stopping of theplayback Using ActionScript, you can load external data into your movie for the purposes

of creating dynamic, user-specific customizations or even e-commerce applications UsingActionScript, you can create nonlinear, interactive presentations and animations The possi-bilities with ActionScript are practically limitless, and they allow you to create Flash applica-tions with tremendous potential In fact, there is very little that you can think up that cannot

be accomplished with ActionScript

Creating Your First ActionScript

All right, so far this all sounds great, right? We’ve suggested that ActionScript is perhaps notgoing to be as difficult and baffling as it might seem at first We’ve even shown you a sampleActionScript statement that reads pretty much just like plain English But there’s still nothinglike a working example to demonstrate a point

So, let’s create your first ActionScript In this example, we introduce a statement that canprove invaluable during Flash development The trace() statement causes Flash to display

a message in the Output panel when you are playing the movie in the test player Although

Web Resource

Trang 40

Chapter 2 ✦ Learning ActionScript Basics

the trace() statement is not used during production, it is a great way to perform simpledebugging (more complex debugging is covered in Chapter 6), and it is an excellent firststatement for learning ActionScript

When you use the trace() statement, you need to tell Flash what message you want to play in the Output panel To do this, you simply place the quoted message within the openingand closing parentheses For example:

dis-trace(“All the world’s a stage”);

Technically, the value between the parentheses of a statement such as trace() does notneed to be a quoted value, as in the previous example However, it does need to evaluate to

a string You can find more discussion of this topic in Chapter 3 in the discussion of variablesand datatypes

Now that you’ve looked at the trace() statement, you may be wondering where this statementgoes so that Flash will do something with it At this point, you have the statement ready to go,but you need to actually “speak” it to Flash to get Flash to do what you want — which is todisplay the message in the Output panel

The most fundamental technique for adding ActionScript code to a Flash movie is to use the Actions panel We’ll examine this panel in much more detail later in this chapter (see

“Understanding the Actions Panel”) For the purposes of getting up and running withActionScript in this example, simply complete the following steps You’ll read about the theory in more depth in just a moment

1 Open a new Flash document.

2 Select the first keyframe of the default layer of the main timeline.

3 Open the Actions panel by choosing Window ➪ Actions or by pressing F9.

4 The right portion of the Actions panel is the Script pane Type the following code into

the Script pane:

trace(“All the world’s a stage”);

5 Test the movie by choosing Control ➪ Test Movie or by pressing Ctrl+Enter (Windows)

or Ô+Enter (Macintosh)

When you’ve tested the movie in this way, you should see the Output panel open and displaythe following:

All the world’s a stage

If the Output panel does not open and display the message, make sure that trace() actionshave not been omitted You can do this by selecting File ➪ Publish Settings In the Publish

Settings dialog box, select the Flash tab, and make sure that Omit trace actions is not checked.

Understanding the Event Model: How ActionScript Works

In the simplest form, ActionScript can be viewed as simple commands, called statements,

given to the Flash player This is not unlike giving commands to a trained dog The difference

is that (one hopes) Flash responds the same way to the same commands with consistency,whereas Rover might not be so easily persuaded to sit or roll over when he has the idea ofchasing the mail carrier

Tip Note

Ngày đăng: 01/06/2014, 09:57

TỪ KHÓA LIÊN QUAN

w