Flash CS4 Professional in 24 Hours- P14

Chia sẻ: Cong Thanh | Ngày: | Loại File: PDF | Số trang:30

0
50
lượt xem
8
download

Flash CS4 Professional in 24 Hours- P14

Mô tả tài liệu
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Flash CS4 Professional in 24 Hours- P14: The creation of this book could not have happened without the skill and patience of many, many people at Sams Publishing. Most of all, I want to thank Mark Taber for offering me this opportunity and Philip Kerman for writing such a great book. I also greatly appreciate the efforts of Songlin Qiu for keeping me on track and organized, not an easy task.

Chủ đề:
Lưu

Nội dung Text: Flash CS4 Professional in 24 Hours- P14

  1. What Other Web Tasks Can Flash Do? 381 Targeting Windows You probably noticed that when you clicked the button you created in the second task this hour, “Use navigateToURL to Create a Hyperlink,” not only were you hyperlinked to another page, but the new page appeared in a new browser window. When you made text hyperlinks in the subsequent two tasks, the new pages would replace the current browser window. To take control of this behavior, you can specify the optional window parameter with one of the standard HTML values: _self, _blank, _parent, _top. In HTML, window refers to the rectangular frame into which the user views a web page. Some pages have one big window whereas others are made up of an arrangement of several windows. Windows can be given names so you can specify into which window particular content should go. There are also some generic window names. Compare this to how you refer to houses in your neighborhood specifically by using addresses or by using generic terms such as “next door” and “across the street.” To specify a window when using navigateToURL, simply provide a second parameter containing the window name as a string. For example, in step 4 of the task “Use navigateToURL to Create a Hyperlink,” you can replace the second to the last line of code with: navigateToURL(new URLRequest(url), “_self”). That is, the first parameter is always the URLRequest and the sec- ond parameter (which is optional) can be any built-in window name (_self, _blank, _parent, _top) or any window you’ve previously named as in HTML frames. To specify a target window when using text hyperlinks (like you did in the task “Create a Text Hyperlink”), you can use the Target drop-down menu in the Properties panel to select from the built-in window names or enter the window name manually, as shown in Figure 20.6. Fi- nally, if you’re creating hyperlinks using dynamic text, you can use the standard HTML attribute called target. That is, you can use the following code in place of the code you entered in step 3 of the task “Use Dynamic Text to Create a Hyperlink”: my_txt.htmlText=”This is Hot.” One way to arrange several windows in HTML is by using framesets. One frameset can have as many frames as you want. Each frame can be designed to have specific dimensions and features, such as a menu bar or title bar. FIGURE 20.6 The Properties panel reveals a Tar- get drop-down menu after you’ve entered a text hyperlink.
  2. 382 HOUR 20: Linking a Movie to the Web Sending Email: The mailto: Command Although you have to use more advanced techniques to actually send email from a web page, here’s a quick-and-dirty way to do something close. The HTML command mailto: can be used in conjunction with navigateToURL to automatically open a user’s email program with a preaddressed email message. The user just needs to type a message, and then send the email message. It’s really simple. In step 4 of the task “Use navigateToURL to Create a Hy- perlink,” you can replace the code inside the goNow() function with: var url = “mailto:lynnbeighley@gmail.com” navigateToURL( new URLRequest(url), “_self” ) Here, lynnbeighley@gmail.com is the email address. If you select the Pub- lish Preview command, when the action is encountered, you should see that a new email message that’s already addressed is created. The user only needs to type the message, and click Send. The only catch is the user must have a default email program identified on his computer. Most people do. If you want the email message to pop up with the subject and body content already created, you can change the simple mailto: string for the URL to something like this: mailto:lynnbeighley@gmail.com?subject=Subject goes here&body=Body goes here Simply replace lynnbeighley@gmail.com with the address you want the message sent to; replace Subject goes here with whatever subject line you want; and replace Body goes here with whatever message you want in the body of the email message. Using Flash Inside a Larger Website Although you can create a website entirely in Flash, sometimes it’s not nec- essary or even desirable. Often, you just want to use Flash to supplement a more conventional website. In the following sections, you learn several ways to use Flash within a larger website. This should help spark some ideas that you can use in your own website.
  3. Using Flash Inside a Larger Website 383 Pop-Up Windows You can supplement a plain HTML website by simply including a link to a Flash web page. Imagine a web page that has text, images, and a simple hy- perlink (in HTML, A HREF) that points to a page you created with Flash’s Publish command. This is the basic hyperlink you’ve seen a million times on the web. Somewhere in your HTML file you include this: Click for Flash sample This creates a line of hypertext on your website that, when clicked, opens up the HTML file that contains your published Flash movie. You can even make this link cause the Flash site (in this case, published.html) open up in a new, blank window: Click for Flash sample If you’re creating your web page by using Dreamweaver, you can use the Properties panel to specify the link and target settings, as shown in Figure 20.7. The Link and Target fields are equivalent to the URL and Window fields, respectively, in the getURL parameters of Flash. FIGURE 20.7 Using Dreamweaver, you can turn text into hypertext via the Proper- ties panel. Properties panel Target field Link field You can add some sophistication to this link from a regular site. The preced- ing methods cause the browser to hyperlink to another page. However, one
  4. 384 HOUR 20: Linking a Movie to the Web technique that might be appropriate is to pop up a new browser window that has specific features. For example, the pop-up window can be sized to your specifications instead of being the same size as the current browser window. You can specify other features to remove or disable certain browser attributes, such as resizing, viewing the buttons, and so on. This in- volves a little JavaScript attached to a line of hypertext. Here’s an example: click here! The key portion of this script is window.open(). The first parameter is the filename you want to open (in this case, animation.html). The second pa- rameter is the arbitrary name you’re giving this window, and the third pa- rameter is a string full of the features you’re including. In this case, only the width and height are specified in pixels. You can find more features that can be included here in a good JavaScript reference. If you want to allow the user to close the window that has popped up in another way besides using the browser’s close button, you can provide some simple JavaScript to perform the task. For example, you can make a Flash animation file called animation.fla with the movie size set to 300×300, and then publish it to .swf and .html files. Then, you can open the HTML file you created (animation.html) by using a text editor (such as Notepad). At the very end of the file are these lines: You’re inserting some JavaScript to close the window between and . Here’s the result: Close Although the movie is 300×300, the window.open code creates a window that’s 300×335 to make room for the hypertext (Close). This shows how a little JavaScript in an HTML file can close a window, but what does it have to do with Flash? Not much, except that it’s an effect you
  5. Using Flash Inside a Larger Website 385 might want to try. Let’s now look at a technique that enables you to execute JavaScript from inside Flash. For example, what if you want a button cre- ated in Flash that executes the window.close() code? There are two basic ways: the javascript: method, which works when you publish to Flash Player 6 or 7, and the newer ExternalInterface class. You can simply re- place the URL for any navigateToURL() method. For example, this code triggers the JavaScript window.close() from Flash: var url = “javascript:window.close()” navigateToURL( new URLRequest(url), “_self” ) All you do is start with javascript: and follow with the actual JavaScript code. This technique works well on the most recent browsers. The ExternalInterface object approach is more elegant, but does require a bit of code. The advantages include the fact that it’s much easier to pass pa- rameters. For example, spawning a new window via window.open involves passing additional details, so it’s tricky when using the javascript: method. To trigger JavaScript directly from inside a Flash .swf you use the call() method, but you need to first import the ExternalInterface class. Provided you’ve placed a button on stage with the instance name closeButton, this code closes the window when the user clicks it: import flash.external.ExternalInterface; closeButton.addEventListener(MouseEvent.CLICK, goNow) function closeNow ( evt ) { ExternalInterface.call(“window.close”) } The window.close() JavaScript is simple; it doesn’t require any parame- ters. Where the ExternalInterface becomes easier is when you need to pass parameters. For example, the following code enables a button instance named openButton to spawn a new window (like the code in the first ex- ample in this section, but this code goes inside your Flash movie): openButton.addEventListener(MouseEvent.CLICK, openNow) function openNow ( evt ) { ExternalInterface.call(“window.open”, “animation.html”, “thename”, ➥“width=300,height=335”); } Note this code also requires the import statement and the html file called animation.html shown in the previous example. One last detail related to pop-up windows: The HTML that the Publish feature creates is solid and works great. However, it’s not necessarily what you want to use in every case. You learn in Hour 24 how to change the exact behavior of Publish.
  6. 386 HOUR 20: Linking a Movie to the Web However, one tiny adjustment worth making that is especially applicable to the animation.html file used in the example: You should change the top part of the HTML file () to this: This edit positions the Flash movie with no margins. Without this adjust- ment, the 300×300 Flash movie would get cut off in a 300×300 window. In Hour 24, you learn how this edit can be incorporated as the default, so you don’t have to make the edit by hand every time. Uploading Files to a Web Server Probably the most critical step in this entire hour involves actually upload- ing all the necessary files to a web server. Although you can test your files on your computer, other people aren’t able to see your creation unless you put it on a web server. A web server is a computer that is connected to the Internet and is configured to enable others to view files through common Internet means, usually a browser. Your computer is likely connected to the Internet, but unless you’re running server software and have the right kind of connection, other people aren’t able to browse the web pages on your hard drive. However, many service providers provide space on their web servers for subscribers to upload files. The process of uploading might be simple if you are running a web server on your computer. Maybe you work at a company where the process is as simple as copying files to another computer’s hard drive. In the simplest of cases, you copy the .swf and .html files to the hard drive, making sure you put them both in the same location. If you have an Internet service provider (ISP) that gives you a certain amount of disk space on its web server, you can simply copy the files to the appropriate location. Your ISP should be able to give you more information, but the most common way of uploading files involves using a File Transfer Protocol (FTP) program. There are several popular (and free) FTP programs that enable you to specify an FTP address, a login name, and a password to gain access to a server, where you can copy and move files. Also, Dreamweaver has a built-in feature to upload files. A simple (although not ideal) way to upload files is to use Internet Explorer, and type into the ad- dress box ftp://login:password@ftp.server.com/, where login is your
  7. Summary 387 login name, password is your password, and ftp.server.com is your ISP’s CAUTION server name. Check with your ISP, but this method should enable you to Many Web Servers Are copy files from your hard drive to the ISP’s server—all you do is drag files Case Sensitive into the Internet Explorer window. Because many web servers use UNIX file-naming conventions and UNIX is case sensitive, your best bet is to keep all your file- Summary names lowercase from the start. For example, if your .fla is You’ve learned a lot this hour and not everything you learned involved called myMovie.fla and you publish it, Flash creates files Flash! That’s okay because the emphasis of this hour is on what to do with named myMovie.html and your Flash movies when you’re ready to distribute them to the world. Al- myMovie.swf. This is asking for though you can certainly create amazing Flash movies that never go on the trouble because if you change web, it doesn’t take much effort to get them onto the web when you’re ready. the .swf to mymovie.swf, the HTML file might not find it. The Although some of Publish’s details aren’t discussed until Hour 24, you did general rule is simple: Keep all see how it exports the necessary .swf and .html files through Publish and filenames entirely lowercase. Publish Preview. Displaying your Flash content on a web page can be as simple as clicking a button. However, you’ve also learned how to use navigateToURL() to include hyperlinks to other web pages. You can use the same technique to send JavaScript commands straight from Flash. You’ve explored several aspects of HTML, including the A HREF tag, which is the equivalent of Flash’s navigateToURL action, tables, and frames. Hope- fully, this overview has inspired you to learn a little more about HTML and to try using it with your Flash projects. In any case, the tricky part isn’t fig- uring out how to get something done—it’s figuring out and deciding what you want to attempt. As with many things in life, after it’s clear where you’re headed, it’s usually easy to get your task done. Q&A Q. When I use Publish Preview, everything looks great, but when I put the files on my web server, they don’t work. Why? A. Here’s a rundown of a few of the common problems. Did you use any uppercase characters in any of the filenames? If so, you should try us- ing all lowercase because your server might be case-sensitive, and some FTP programs automatically rename files to all lowercase. Did you copy all the correct files to the server? Did you put all the files in the right locations (such as the .swf file in the same folder as the .html file)? Is your server properly configured for Flash’s MIME setting? (If you want to learn more about this setting, check out Adobe’s TechNote 4151—type technote 4151 into the search field at www.adobe.com.)
  8. 388 HOUR 20: Linking a Movie to the Web Q. Can I have more than one Flash movie on a web page? A. Of course; you can have as many as you can track. For example, it might make sense in a table to have a Flash movie in two different cells. You could also design a frameset where one Flash movie is contained in a frame that never reloads, contains background music, and a bunch of other Flash movies load into frames that change. Whatever you want, it can probably be done. Workshop The Workshop consists of quiz questions and answers to help you solidify your understanding of the material covered in this hour. You should try to answer the questions before checking the answers. Quiz 1. If you select the Publish command and nothing seems to happen, is something wrong? A. Yes. Publish has a bug and doesn’t actually work. B. Possibly. You need to be connected to the Internet for this com- mand to work. C. No. Publish simply exports the files selected in the Publish Set- tings dialog box. If you want to see the results, try using Publish Preview or find the exported files. 2. Is it necessary to use the navigateToURL method only when the user clicks a button? A. Yes. Otherwise, you wouldn’t know exactly when the user wanted to navigate to a new web page. B. No. You could also put navigateToURL on a keyframe so the user goes to another page as soon as the frame is reached C. No. You can use navigateToURL keyframes and not respond to the user clicking a button.
  9. Workshop 389 3. If you read all the material in this hour, you should have a good ground- ing in HTML. A. True. It was concise, yet comprehensive. B. False. If you didn’t know HTML before this hour, you probably still don’t—but at least you know some of the potential. C. False. Only when you finish this book do you become an HTML pro. 4. Is using the navigateToURL method the only way to create a hyperlink? A. Yes, except if you do it in HTML. B. No. At least 20 other Components ship with Flash under the web category. C. No. There are also some ways to create hyperlinks with text. Quiz Answers 1. C. Publish creates files, but you don’t see anything unless you first find the files created. Publish Preview creates files and immediately previews them in your browser. 2. B. The navigateToURL method can be associated with any event (in- cluding a button click) as well as be placed in a keyframe. 3. B. The idea of this hour wasn’t to teach HTML, but rather to point those with some HTML experience in the right direction and give oth- ers an idea of what’s possible. 4. C. When the Properties panel is set to Static Text, you can specify a URL for the web page to jump to when the link is clicked. Also, the Dynamic and Input styles can have HTML styles, effectively enabling you to write HTML in Flash.
  10. This page intentionally left blank
  11. HOUR 21 Designing a Website to Be Modular It’s possible to create a huge website entirely with one giant Flash file. WHAT YOU’LL LEARN IN However, separating the site into modular segments has distinct advan- THIS HOUR: tages: You can have portions of the site load as needed instead of making . How to use the Loader every visitor download everything; several team members can work on the class to play one movie same site simultaneously; you can update portions of the site as they inside another or dis- change instead of having to reedit one master file; and you can create dif- play an external image ferent versions of the site for different languages by swapping out portions (.jpg, .gif, or .png) with language-specific content. There are other reasons modularity is good, . How to play external but it comes down to efficiency, your productivity, and the user experience. MP3 sounds This hour covers several ways a Flash site can be modularized as well as . How the URLLoader and some of the issues you need to consider in deciding when and where to URLVariables classes modularize. enable you to import the contents of text files Although the technical concepts covered this hour are not particularly diffi- cult, the Flash features discussed are strict and unforgiving. As long as you use the correct syntax, you’ll be fine. Ultimately, the difficulty comes in decid- ing the appropriate use of such features. It’s easy to learn how these features work, but it’s more difficult to decide when to use them and where to use them. For each feature, you first learn how it works, and then look at practical uses. Loading Movies or Images The Loader class enables one Flash movie to play another. Basically, the sec- ond movie plays on top of the first. It’s easiest to understand, though, if you think of one movie as the host and the other movie (the one that’s loaded on top of the host) as the submovie. The movie you put into your DVD player can play on only the TV screen. Think of the TV as the host Flash movie, and think of the video you put into your DVD as loaded on top of it.
  12. 392 HOUR 21: Designing a Website to Be Modular One reason to do this in Flash is because you might have several submovies that only play one at a time. You might want to give the user the choice as to which submovie to play. All you need to do is trigger the Loader when the user clicks a button. It’s sort of like a jukebox, where each record or CD is a separate submovie. The reason the Loader is beneficial is that only the submovies the user requests have to download. Let’s look at some of the technical issues with the Loader, and then you can try it. First, only .swf files can execute the Loader’s load method. There- fore, you have to use Test Movie to generate the host .swf to see the results. Into the host .swf, you can load other .swfs as well as image files (JPG, GIF, or PNG). Realize if you plan to load movies, they need to first be exported as .swf files. Finally, when you use the Loader, you must specify into what target movie clip the loaded movie or image should appear. You make the loaded content appear onstage with the addChild() method. The addChild() method effectively creates a movie clip at runtime. You don’t see anything until you issue addChild(). Flash contains a display list, which is a list of all the objects onstage. In fact, each movie clip has its own display list; after all, you can stack multiple movie clips inside of one movie clip. The addChild() method is a method of the movie clip class. Let’s say you called the loader myLoader, and you have a clip onstage called myClip. You could use the code myClip.addChild(myLoader), and the loaded movie gets added on top of all other clips in the myClip instance. If you say addChild(myLoader, then the loaded movie gets added on top of everything in the current Timeline. As an alternative, you can use addChildAt() and specify an index number. This enables you to replace any one other instance that’s already in the display list because only one object can appear in any one slot at a time. That is a brief explanation of the display list, but it’s something you need to know to understand the task you’re about to do. In the next task, you see how to load movies into a clip already onstage. ▼ TRY IT YOURSELF In this task, you use the Loader class to selectively enable the user to Load a Movie download just the segments he is interested in. Follow these steps: 1. The name of the game for this task is organization. Create a new empty folder into which you save and export all your movies. You are making three colored tweens plus the main hosting file. 2. Create a new Flash File (ActionScript 3.0). Set both the movie’s width and height to 300. Use Modify, Document (or press Ctrl+J) to do this.
  13. Loading Movies or Images 393 Make sure that Ruler Units is set to Pixels by selecting Modify, TRY IT YOURSELF ▼ Document, and then choosing Pixels. Load a Movie 3. Create a simple tween of your choice, and make the tweening object entirely red. Save the movie as red.fla in the folder you created in step 1. Use Test Movie, which exports a movie called red.swf to the same folder as your red.fla file. 4. Use Save As to name the file green.fla, and change the color of the tweening object to green. You might need to change the color in each keyframe. Remember to save, and then use Test Movie to create the .swf. 5. Repeat step 4, but create a file with everything blue. 6. You should have three .fla files and three .swf files (red, green, and blue for each), as shown in Figure 21.1. Close all the Flash files. Then create a new Flash File (ActionScript 3.0), and save it as main.fla in the same folder. Set this document’s size to 500×500. This main file loads movies into a clip. FIGURE 21.1 From each of your three .fla files, you need to create a corresponding .swf. 7. Draw a square exactly 300×300 by drawing a rectangle, and then us- ing the Info panel to change its dimensions to 300×300. Make sure a line is around the box, and then delete the fill. Select the entire out- line, and convert to it a symbol. Make it a Movie Clip, name it box, and select the top-left Registration option. Name the instance on the Stage myClip in the Properties panel. 8. Drag a Button component onto the Stage either from Window, Common Libraries, Buttons or the Components panel, and use the Properties panel to give it the instance name redButton. Edit the button if it was from the Library, or use the Parameters tab if it’s a component to change the button’s label to Red. 9. Select the first keyframe in the movie, and open the Actions panel. Type the following lines of code: var myLoader:Loader = new Loader() myClip.addChild( myLoader ) redButton.addEventListener(MouseEvent.CLICK , clickRed)
  14. 394 HOUR 21: Designing a Website to Be Modular ▼ TRY IT YOURSELF function clickRed ( evt ){ Load a Movie myLoader.load( new URLRequest(“red.swf”) ) } The first line creates an instance of the Loader class (theLoader). Then, it issues addChild() to put that loader in the myClip instance. By using addEventListener(), we broadcast the CLICK event from the redButton instance to the clickRed() function. Finally, inside the clickRed() function, we trigger load(), and specify the file to load red.swf fashioned as a URLRequest. CAUTION 10. Save your Flash file. If you don’t, it won’t be able to load the .swf files we already created. Test the movie. Notice the loaded movie is regis- Everything Is a tered perfectly. That’s because the loaded movie loads with its upper- URLRequest left corner aligned with the clip’s registration point. (In this case, it’s It’s natural to think the follow- the upper-left as specified when you created the clip in step 7.) ing code would work, but it doesn’t: 11. Make two more buttons with the instance names greenButton and myLoader.load(“red.swf”). blueButton, and add the following code below the code you already You must remember that all have in Frame 1: requests are in the form of a greenButton.addEventListener(MouseEvent.CLICK , clickGreen) URLRequest instance (that is, function clickGreen ( evt ){ myLoader.load ( new myLoader.load( new URLRequest(“green.swf”) ) URLRequest (“red.swf”)). } blueButton.addEventListener(MouseEvent.CLICK , clickBlue) function clickBlue ( evt ){ myLoader.load( new URLRequest(“blue.swf”) ) } You can tweak the task you just completed to display images. In addition to loading .swf files, you can load images in the following formats: .jpg (both regular and progressive encoded JPGs), .gif, and .png. The .gif format has been used very widely, and .png is great because it supports alpha channels—meaning portions of the loaded image overlay objects under- neath. To load images, change the first parameter in the .swf filenames to .jpg filenames. For example, in step 9, change red.swf to read someimage.png. You need a matching image name instead of someimage.png in the same folder.
  15. Determining When a Movie Is Fully Loaded 395 Determining When a Movie Is Fully Loaded Now that you know how to load an image or .swf, you need to know how to unload it. First, you should learn how to determine whether a movie that’s loading has completed loading. This is important if the movie that’s loading is large. It’s good design to allow the user to see that a movie is in- deed downloading. You might actually want to make the user wait for it to fully load. All these things require you to determine whether a loading movie has downloaded. The best way to determine whether a movie has loaded is to set up a lis- tener that waits for the COMPLETE event to fire from the Loader, but that doesn’t happen until the .swf or image is fully loaded. You can also listen for the PROGRESS event to get up-to-the-minute information about how the downloading is progressing. The only catch is the PROGRESS event is broad- cast from the Loader’s contentLoaderInfo property, not the Loader itself. This way, you can display information to the user, such as a progress bar. That’s just what we do in the next task. In this task, you listen for events that get broadcast from the Loader class TRY IT YOURSELF ▼ to display the download progress in the ProgressBar component and then Use the Loader Class in a custom horizontal graphic. Follow these steps: to Display Progress 1. First, create the submovie that will be loaded. Set the document prop- erties by pressing Ctrl+J to 300×300. Then, create a linear animation that starts in Frame 2. To do this, click Frame 2, select Insert, Timeline, Keyframe (or press F6), and then build the animation that plays through many more frames (at least to Frame 60). Using an em- bedded video clip would be ideal because you want something that takes a little while to download. To that end, consider importing a sound and making it start on Frame 2 to make the file big. 2. Select the first frame of this submovie and open the Actions panel. Type stop(), so this movie stops on Frame 1 while the rest of the movie downloads. 3. Make a new layer, and in the last frame of that layer (Frame 60), click and then insert a keyframe by pressing F6. With the last frame se- lected, open the Actions panel, and type gotoAndPlay(2);, so the movie loops, but not all the way back to the start where there’s a stop action.
  16. 396 HOUR 21: Designing a Website to Be Modular ▼ TRY IT YOURSELF 4. In a new folder, save this movie as submovie.fla, and then use Test Use the Loader Class Movie by pressing Ctrl+Enter to create a .swf named submovie.swf. to Display Progress When you use Test Movie, the movie just sits on Frame 1; you control this issue from the movie into which it loads. 5. Now, create a new Flash File (ActionScript 3.0), and save the file as main.fla in the same location where submovie.fla is saved. Drag a ProgressBar component onto the stage. Use the Properties panel to set its instance name to myProgressBar. 6. Select the first keyframe in the Timeline, and open the Actions panel. Type the following code, but don’t include the line numbers as we’ve included those for reference only: 1 var myLoader:Loader = new Loader() 2 myProgressBar.source = myLoader.contentLoaderInfo; 3 myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, ➥contentLoaded) 4 function contentLoaded(evt){ 5 addChild( myLoader ) 6 var clip:MovieClip = myLoader.content as MovieClip 7 clip.play() 8 myProgressBar.visible = false 9 } 10 myLoader.load( new URLRequest(“submovie.swf”) ) A couple notes are in order because this isn’t identical to the previous task. In line 2, you’re associating the ProgressBar component with the Loader, or rather the contentLoaderInfo property of the Loader. Line 3 sets up a listener for when the COMPLETE event fires, and it trig- gers the homemade contentLoaded() function. We’re waiting until that function triggers to issue addChild(), so we don’t see anything while it loads. Naturally, the ProgressBar is visible during the load, but does get hidden on line 8 when it’s no longer needed. In line 7, we want to tell the loaded clip to play, but we need to start with the tricky code in line 6. This gets a reference to the content property of the myLoader instance and ensures it’s treated as a Movie Clip. Finally, after everything is set up, line 10 issues the load() method to begin loading the submovie.swf. 7. This task is complete, but we want to show how you can make your own progress bar. Arguably, a homemade progress bar is no better than the component version; in fact, you need to do more code. But if you want to make a custom graphic or something other than a growing bar, you could.
  17. Determining When a Movie Is Fully Loaded 397 8. In the main.fla, you draw a rectangle for the progress bar. Select the TRY IT YOURSELF ▼ Rectangle tool, turn off Object Drawing, and then draw a rectangle. Use the Loader Class Select only the fill to leave behind the stroke, and then select Modify, to Display Progress Convert to Symbol (or press F8). Select the upper-left registration point so when the rectangle scales, it scales from the left. You can call the symbol Progress, and then name the instance progress_mc. 9. Finally, select the first keyframe in the main.fla, and replace the code from earlier in this task with the following code, which we explain next: 1 var myLoader:Loader = new Loader() 2 myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, ➥contentLoaded) 3 function contentLoaded(evt){ 4 addChild( myLoader ) 5 var clip:MovieClip = myLoader.content as MovieClip 6 clip.play() 7 progress_mc.visible = false 8 } 9 10 myLoader.contentLoaderInfo.addEventListener- ➥(ProgressEvent.PROGRESS, monitorProgress) 11 function monitorProgress(evt){ 12 var percent = evt.bytesLoaded / evt.bytesTotal 13 progress_mc.scaleX = percent 14 } 15 16 myLoader.load( new URLRequest(“submovie.swf”) ) The main difference with this code from the equivalent code from step 6 is that there’s no ProgressBar component. This means you need to broadcast the PROGRESS event from the Loader’s contentLoaderInfo property. In line 10, we’re directing that PROGRESS event to the homemade function monitorProgress(). In- side that function, we’re setting the scaleX property of the progress_mc instance based on how many bytes have loaded versus how many total bytes. 10. Test the movie. The movie should work well. If you really want to test it, put it on a web server, and try running it from a slow connection. While testing, you can also select View, Simulate Download.
  18. 398 HOUR 21: Designing a Website to Be Modular Playing External Sounds You can play MP3 sounds that reside outside a movie. This means your movie can stay small and load sounds only as the user requests them. Also, you can swap out and replace the original MP3 files without needing to re-import them into Flash. There are a few subtleties in how it works, but the script is easy enough to learn. The next task shows you how to make a jukebox application. ▼ TRY IT YOURSELF In this task, you build a mini-jukebox from which users can select songs to Play an External MP3 play. Follow these steps: 1. Find a few MP3 files, and place them in a new folder. Name the files song1.mp3, song2.mp3, and song3.mp3. 2. Create a new Flash File (ActionScript 3.0), and save it as jukebox.fla in the same folder where the MP3s reside. Drag a List component onto the Stage, and give it an instance name songList. Use the Free Trans- form tool to make the list nice and wide. 3. Put this script in the first keyframe of the movie: 1 songList.addItem( {label: “Title of song one”, filename: ➥“song1.mp3” } ) 2 songList.addItem( {label: “Title of song two”, filename: ➥“song2.mp3” } ) 3 songList.addItem( {label: “Title of song three”, filename: ➥“song3.mp3” } ) 4 5 songList.addEventListener(Event.CHANGE, playSong) 6 var mySound:Sound 7 var soundChannel:SoundChannel; 8 function playSong( evt ){ 9 if (soundChannel != null ){ 10 soundChannel.stop() 11 } 12 mySound = new Sound() 13 mySound.load( new URLRequest ( ➥songList.selectedItem.filename ) ) 14 soundChannel = mySound.play() 15 } Naturally, you can replace the titles for the songs in lines 1–3. The Label property is visible in the List component, but the filename property makes up for this. These filenames are hidden in the list, but we extract it from the selectedItem property way down on line 13 when we finally load the sound. Every time the user selects a song, the homemade playSong() function triggers. The funky part appears on lines 9–11. There we see whether a soundChannel is currently active, in which case the stop() method stops the current sound. Without this if statement, each time the user selects a song, it would play on top of the previous song.
  19. Loading External Text 399 Loading External Text After beginning this hour with exciting exercises loading images, .swfs, and MP3s, it might seem anticlimatic to study loading plain old text. How- ever, if you keep the text that appears in your movie external, you can make updates without reopening Flash. Also, you can design your project so your clients can make edits by simply editing a text file. Designing your movie to use external text means you need to decide what elements are worthy of keeping external. A bit of programming is involved, too, but it can be well worth the upfront work. It’s likely that you want to store more than just one large block of text in an external file. For example, you might want to store captions for multiple images in your movie. Or, perhaps you plan to localize or translate your project to other languages, and the labels for each button need to be trans- lated. A simple way to store multiple blocks of text is as name/value pairs. Each block of text is named—for example, image1Caption, image2Caption, and so on. Each named block of text also has a matching value, such as “This is my first photo.” Each name/value pair is separated by an amper- sand (&). This name/value pair format is also called a URL encoded string. You see how this looks in the first step of the following task. In this task, you display a headline and caption loaded from a text file. Fol- TRY IT YOURSELF ▼ low these steps: Load Text from File 1. Like so many tasks this hour, you want to start with an empty folder on your computer. Use a text editor, such as Notepad, to create a text file with the following contents: headline=Welcome to Our Company&caption=This is all the info about our company Save this text file as data.txt. 2. Now, in Flash, create a new Flash File (ActionScript 3.0), and save it in the same folder where the data.txt file resides. 3. Use the Text tool to create three text fields. For all the fields, use the Properties panel to change the Text type to Dynamic Text and the Line type to Multiline. You can make other adjustments such as font and size. Finally, be sure to give one text field the instance name loading_txt; another one headline_txt; and the last one caption_txt.
  20. 400 HOUR 21: Designing a Website to Be Modular ▼ TRY IT YOURSELF 4. Select Frame 1, and open the Actions panel. Enter the following code, Load Text from File which loads the data.txt file: 1 headline_txt.text = ““ 2 caption_txt.text = ““ 3 loading_txt.text = “loading” 4 var myURLLoader:URLLoader = new URLLoader() 5 myURLLoader.addEventListener(Event.COMPLETE, textLoaded) 6 var myURLVariables:URLVariables; 7 function textLoaded (evt){ 8 myURLVariables = new URLVariables( myURLLoader.data ) 9 headline_txt.text = myURLVariables.headline 10 caption_txt.text = myURLVariables.caption 11 loading_txt.text = ““ 12 } 13 myURLLoader.load( new URLRequest(“data.txt”) ) This code clears two of the text fields and displays the text Loading in the other. Even though this data loads quickly, it’s good practice to tell users the reason for the delay. To load the data, you’re creating an in- stance of the URLLoader class, which is saved in a variable we’re call- ing myURLLoader. To pull out the variables contained in the text file, we need a URLVariables instance, which we create and save in the myURLVariables variable on line 6. Notice line 5 directs the COMPLETE event to the homemade function textLoaded(). There, we extract the data property from the myURLLoader instance to create a new URLVariables instance. Finally, on lines 9 and 10, it gets easier because we can simply grab the headline property and caption prop- erty (the names of the variables in the text file) and use those to pop- ulate the text fields. 5. Test your movie. With the .swf and data.txt files in hand, you can make edits to the data.txt file and never need to edit the .fla or generate a new .swf. After publishing, remember to upload the data.txt file, too. We have a couple of parting notes about loading text into your movie. First, you might want to externally store data that isn’t directly displayed on- screen. In this task, we displayed the actual words in that file, but the data.txt file could include any data. For example, you could store exter- nally numbers that are used to set some initial values—perhaps the frame number on which a Movie Clip should begin. The point is you can read data into your movie, and then do whatever you want with it.
Đồng bộ tài khoản