logo
468x60-2-495


  • Home
  • Privacy Policy
  • About
search
top
Jun 29, 2012 Posted on Jun 29, 2012 in Hints and Tips | 10 comments

Intro to Dart: Creating a Marquee

In this tutorial, I’ll introduce you to Dart and how to start using it. In the course of the article we’ll build a simple JavaScript-based image marquee without writing a single line of JavaScript – just Dart.

Note: This tutorial was originally published in March 2012, as a freebie for our Facebook fans.


Project Preview

We will be building the following simple marquee, a screenshot of which is shown below. Click on the image to launch a working example of the project.

Click the image to launch the project

Step 1: Install the Dart Editor

Let’s get started building out little marquee. From here on out, we’ll be much more hands-on, and I’ll take the time explain the new stuff along the way.

First things first; we can write Dart in any old text editor, really, but the most convenient way to get started and to immediately run your project in a browser (via JavaScript compilation) is to install the Dart Editor.

Head to http://www.dartlang.org/docs/getting-started/editor/, which should automatically detect your OS and present you with the appropriate download link. It’s not a small download, around 65 MB at this writing, so get it started before continuing to read.

The Dart Editor is rather bare-bones. It’s built on Eclipse, and I hope that eventually it will be offered as an Eclipse plug-in for those with an existing Eclipse installation. But for now, it’s a self-contained Eclipse modification that does Dart and not much else.

It offers a few of the features that Eclipse workspaces typically offer, such as language-aware completion. The big advantage it brings, though, is a fairly simple way to start and run a Dart project.

Once the download completes, extract the ZIP file and you’ll have a dart folder. You can place this wherever you like; I’ve moved mine to my Applications folder.


Step 2: Create a Dart Project

Let’s open up the Dart Editor application. You’ll find it just inside that dart folder you just unzipped.

Once it launches, you’ll be presented with a “Welcome” page, which provides a jumping-off point to some sample projects. These are certainly worth taking a look, but we’ll skip past them for now and first get a little more familiar with the language.

The first thing you'll see when opening Dart Editor

Go to the File menu and choose New Application… or click on the top-left icon in the toolbar:

The 'New Application' tool bar button

In the resulting window, enter a name for the project (I’m using DartMarquee). It will want to store the project in a folder named dart in your home directory, but you can change that by clicking on the Browse… button. Note that whichever folder you choose, Dart Editor will create a new folder in the selected folder, using the name you’ve given for the project. Inside of that there will be a few files created for you, also using the name of the project you supplied.

Also be sure the “Web Application” is selected, not “Server Application.”

The 'New Application' window

Step 3: Run the Hello World Example

The default project created for you is a simple Hello World example. You may as well see what happens before we start building our (slightly) more complicated project. Run the application by either choosing Tools > Run from the menu, pressing Command-R (Mac) or Control-R (PC), or by clicking on the green “play” button in the tool bar:

The 'Run' Button

You may expect this open up in your default browser, but – surprise! – Google’s Chromium browser will open (not to be confused with Chrome; Chromium has a blue-ish monochrome icon, not Chrome’s colorful icon). Chromium has built-in support the the Dart language.

Chromium

This is not the process I mentioned earlier where Dart files are compiled into JavaScript; this is the Dart VM running regular Dart code, which is cool, but not terribly useful for those of us currently building JavaScript applications. We’ll make the project compile to JavaScript next.


Step 4: Add a JavaScript Launch

If you change the run settings, then we can get Dart to compile to JavaScript. To change these settings, choose the Tools > Manage Launches… menu, press Command-Shift-M (Mac) or Control-Shift-M (PC), or click and hold the downward arrow next to the Run tool bar button, and choose Manage Launches… from the pop-up menu.

The Manage Launches option int he tool bar

In the window that appears, you’ll see the default launch created for you, which has the Chromium icon. To create a new launch, click on the new document icon, which will display a pop-up menu.

New Launch targets

Choose Dart Web Launch from the menu. In the top field at the right, give it a meaningful name, like DartMarquee JS or something to designate that we’re going for a JavaScript rendition in another browser.

Under Launch Target, click Browse… next to HTML file:. A window will open that presents all (one) HTML files present in your project. Click on DartMarquee.html and then click OK.

Under Browser you can choose to leave the default checked, or uncheck that option and then specify a browser with the Select… button. The browser choice shouldn’t matter too much, although I will be using some CSS3 tricks so a modern browser would be ideal.

Click Apply and then Close.

Now run the project again, but this time be sure to do it by clicking and holding on the Run tool bar button, and then selecting your new launch target. You should now get the same Hello World application in the browser of your choosing, which will be using JavaScript compiled from Dart. In fact, you’ll see a new file show up in your file list: DartMarquee.dart.js. This is the compiled JavaScript file.

Now that you’ve run the new launch once, future Runs will remember this decision and launch the JavaScript version.

But we’re not done yet. The HTML file is set up to include the Dart file, along with another JavaScript file that interprets Dart files in the browser (which is super-cool, but not the best for production applications). We need to edit the HTML file to use the compiled JavaScript file, not the Dart files.


Step 5: The HTML

Your new project should open with DartMaquee.dart in the main editor area. We’ll get to that soon enough, but let’s get our HTML page set up. Double-click on DartMarquee.html in the file list on the left, and it will open in a new tab in the editor.

Dart Editor is really only aware of the Dart language, which is too bad. You’ll notice that the HTML file opens without any syntax coloring or intelligence about the language. It’s good enough for our purposes now, but feel free to open this file (and any other non-Dart file) in the text editor of your choosing. We won’t be spending too much time in non-Dart files, so I’ll just be editing them in Dart Editor for this tutorial.

The body markup is not what we want, but first let’s update those <script> tags as mentioned in the last step. You can delete the first <script> tag altogether; that’s the once that includes the Dart file directly. Delete this line:

<script src="http://dart.googlecode.com/svn/branches/bleeding_edge/dart/client/dart.js"></script>

(Hint: line numbers aren’t enabled by default, but that’s one of the few options available under Preferences).

The script is the in-browser runtime for Dart; one pretty nifty feature is that you can write Dart without compiling it to JavaScript, and have browsers run it anyway. You just need to include dart.js. Of course, this makes for some extra overhead and impacts performance. Pretty cool trick, though.

Now let’s change the remaining <script> tag to load our compiled JavaScript file. Change this:

<script type="application/dart" src="DartMarquee.dart"></script>

To this:

<script src="DartMarquee.dart.js"></script>

If you like, run the project again, and use the developer tool to ensure that the JavaScript file is loading, and the other two are not.

Now, change that <h2> tag into a <div>, and give it an id of marquee.

<div id="marquee"></div>

You can leave the <h1> if you like; sometimes it’s nice to have page identification.

Finally, we need to link to a CSS file (which we’ll create in the next step). In the <head> add a <link> tag:

<link rel="stylesheet" href="DartMarquee.css">

The application will not work, because we’ve removed the <h2> that was targeted by the Dart code, not to mention that we still need a CSS file. Let’s do that next.


Step 6: The CSS

We’ve linked to a non-existent CSS file, so let’s address that. In the Files area of Dart Editor, right-click, and choose New File: from the menu (you can also find New File… in the File menu).

In the resulting window, you may need to ensure that the DartMarquee project is selected in the middle area. Then enter DartMarquee.css for the file name, and click on Finish.

The New File window

This file will be ready to edit in the main editor area, but as with HTML files, CSS files aren’t intelligently supported with syntax by Dart Editor. Feel free to do your CSS editing in your preferred text editor. Or, since we’re really not here to delve into the CSS, just copy and paste form below into Dart Editor:

#marquee {
    width: 600px;
    height: 400px;
    background-color: #111;
}

.mainImage {
    height: 300px;
    background-color: #666;
    position: relative;
}
.mainImage img {
    display: block;
    position:absolute;
    left: 0px;
    top: 0px;
    -webkit-transition: opacity 0.6s ease-out;
       -moz-transition: opacity 0.6s ease-out;
        -ms-transition: opacity 0.6s ease-out;
         -o-transition: opacity 0.6s ease-out;
            transition: opacity 0.6s ease-out;
}
.mainImage img.fade_away {
    opacity: 0;
}

.thumbContainer {
    height: 100px;
    background-color: #DDD;
}

.button {
    width: 100px;
    height: 100px;
    background-color: #eee;
    position: relative;
    float: left;
}

.button .border {
    width: 90px;
    height: 90px;
    position: absolute;
    opacity: 0;
    border: 5px solid orange;
    -webkit-transition: opacity 0.3s ease-out;
       -moz-transition: opacity 0.3s ease-out;
        -ms-transition: opacity 0.3s ease-out;
         -o-transition: opacity 0.3s ease-out;
            transition: opacity 0.3s ease-out;
    cursor: pointer;
}
.button:hover .border {
    opacity: .5;
}
.button.selected .border {
    opacity: 1;
}

Again, we’re not here to discuss CSS. I’ll point out that I’m using CSS3 transitions for the button hovers and the main image changes. Otherwise, it should be fairly straightforward.

Run the project one more time, or simply reload from the browser; at this point there won’t be any JavaScript to re-compile. If you run from Dart Editor, be sure to switch back to the HTML or Dart file; Dart Editor doesn’t know what to do when you “Run” from a CSS file.

You should see a large dark rectangle. Doesn’t look like much yet, but you’re on the right tack.


Step 7: Preparing the Images

One more housekeeping task, and that’s to make our images readily accessible, so that we can see them when we’re ready to write that code.

In the download package, you’ll find a folder named images. Copy or move this folder from the download archive to your project folder, so that’s sitting at the same level as your other files. You’ll probably need to use the Finder/Explorer for this task, as Dart Editor doesn’t (yet) support importing or drag-and-drop of existing files. They’ll show up in your file list once you get them in place, though.

The project structure so far

Now we can get into some Dart code. That’s next!


Step 8: The main() Function

Open up the DartMarquee.dart file in the editor. You’ll see three main blocks of code:

The three main sections in the default Dart file

The third block is the main function, and this is a required part of your Dart project. Dart will look for this function as an entry point to execution. Contrast this with JavaScript where scripts are simply executed from top to bottom. You can certainly replicate this methodology in JavaScript, but the key difference is that you don’t have to, and if you do you have to call main() yourself; in Dart, it’s expected that you have the main function, as it will be called for you once Dart in ready to begin execution of your application.

This won’t be a foreign concept to you if you’ve programmed in C or Java, or even in ActionScript 3 and used the Document class. The nice thing about it is that there is a standardized, expected place to begin the execution of your code.


Step 9: Classes

Dart brings with it proper classes, which you may end up preferring to JavaScript’s class-ish-ness prototype system. Take a look at the second block of code in DartMarquee.dart. This is the meat of the program right now, and is a class with two methods declared. We’ll be ditching a large part of this code. We’ll get into the syntax as we go, but for now, hollow out this class so that it looks like this:

class DartMarquee {

    DartMarquee() {
    }

}

What this leaves is the class declaration and the constructor. The class declaration begins with class, which is followed by the name of the class. That this class is named DartMarquee is purely a function of the template used in the application creation process in DartEditor. It’s important to know that just because this file is named “DartMarquee.dart” does not mean that there has to be a class name DartMarquee inside. We’re not going to change it, because it makes sense, but Dart is like PHP or Ruby in that you can put as many class definitions as you like in a single file, and the naming doesn’t need to match the file name (as it does in ActionScript).

The class definition is then contained between the curly braces. Inside of that, we have a constructor. This is a function that is run when a new object is instantiated from this class. Typically one puts set-up code in a constructor. Note that the name of the constructor needs to match the name of the class, otherwise it’s not a constructor, and is a regular method instead.

Everything else you add to a class should go in between the two curly braces denoting the class.

You’ll notice that back in the main function, a DartMarquee object is instantiate with this line:

new DartMarquee().run();

This should look like object-oriented JavaScript. The .run() then calls the run method on the newly-created object. We just removed that method, so go ahead and change that line to this:

new DartMarquee();

Step 10: Imports

Something I’m pretty excited about with Dart, as someone coming from JavaScript, is the ability to easily import and use other code into your project. The first block of our default code uses a single import statement:

#import('dart:html');

This imports a built-in Dart library, one that deals specifically with HTML pages and giving us access to DOM manipulation functionality. We’ll be importing other libraries as we need them, including one that we’ll write ourselves.

When our Dart project is compiled to JavaScript, all of the disparate Dart code is converted and concatenated into a single JavaScript file. It’s smart enough to not include the same library twice, so you can import libraries from other files and not worry about them conflicting with or duplicating code in the final product.

Our DartMarquee.dart file should look something like this now:

#import('dart:html');

class DartMarquee {

    DartMarquee() {
    }

}

function main() {
    new DartMarquee();
}

Step 11: Add a Property to the Class

Let’s finally write code. We’re going to add a target property to the DartMarquee class, so that the main HTML element that we’re referencing is handy within the class.

Just after the class declaration, and before the constructor, add a property like so:

class DartMarquee {

    Element _target;

    DartMarquee() {
    }

}

Notice the syntax here: instead of var, we use a datatype to both declare a variable and give it a datatype all at once. This syntax is reminiscent of C and Java. The name of our property is _target, and the line ends with a semi-colon. You’ll find Dart much less forgiving about missing semi-colons.

An interesting thing about Dart type system is that it’s optional. If you specify a type, Dart will do what it can to adhere to typing rules. But we could also opt to leave typing off by writing that property like this:

var _target;

Dart will then not attempt to keep your types safe; you’ll have a dynamically-typed variable just like in JavaScript. What’s even more interesting than the fact that it’s optional is that you can mix strong and dynamic typing in the same code.

Personally, strong typing is one of the things that draws me to Dart, as it’s helpful to have that kind of accountability. This will be the last time I mention dynamic typing in Dart.

We’re not done with that property yet. This is an important property, so let’s set it in the constructor.

class DartMarquee {

    Element _target;

    DartMarquee(this._target) {
    }

}

This may look a little unexpected. This is a Dart idiom; it’s so common for a constructor to receive arguments, and then simply use the constructor’s body to stash those values into properties, that Google created a shortcut.

Normally, a method parameter looks like you’d expect it to: any variable name will do, but not something that looks like a property on another object. These parameters are normal parameters like you’re used to; they’re available by name within the body of the method.

This new syntax, however, will go ahead and assign the value passed in to this parameter to the property designated by the parameter name. In other words, the code above is identical to this code:

DartMarquee(target) {
    this._target = target;
}

Only we don’t have to write that boilerplate of a line.

Note that this shortcut is only available in constructors.


Step 12: DOM Queries

Now that we have a target property set up, we need to give it a value. Back in the main function, we need to select the marquee <div> and pass it in to the constructor.

Dart provides a method to find HTML elements by CSS selection, much like jQuery or any of the popular JavaScript libraries do. This is provided by that dart:html library imported at the top of the file, which also provides a top-level document variable which gives us global access to the HTML document.

Update the main function to look like this:

void main() {
    new DartMarquee(document.query('#marquee'));
}

It’s that simple: if you’ve used jQuery (or another library), this should be rather familiar. Simply call document.query and pass in the selector. Dart does the rest.


Step 13: Console Logging

If you’ve developed with JavaScript, chances are you’ve made heavy use of console.log to test and verify your code. Dart provides a print function that, when compiled to JavaScript, turns in to a call to console.log. Let’s try it out, and test our project so far at the same time.

In the DartMarquee constructor, let’s print the _target property to make sure it’s being set.

DartMarquee(this._target) {
    print(this._target);
}

And hit Run. In your browser, open up your console and you should see something like this:

The result of a print

Note that at the time of this writing, there is a bug with the Dart Editor that generates a warning stating that “print” is not a method. This is being tracked by Google and will probably be fixed soon, if not by the time you read this. But if you’re seeing that warning, just ignore it; it still compiles fine. This is an example of the bleeding edge on which Dart stands; the print warning was not happening when I started writing this tutorial, it’s only happened with the most recent build of the Editor (build 5104).


Step 14: DOM Manipulation

We’re going to create the needed HTML elements programmatically, and place them within our target <div>. Dart provides a very clean API for this kind of task.

First, let’s create a few more properties to hold some of the elements. Add these right below the first property you added:

class DartMarquee {

    Element _target;
    DivElement _mainImage;
    DivElement _thumbContainer;

    DartMarquee(this._target) {

Notice how we’re using underscores as a prefix? Not only this a common convention when naming private properties, it’s actually idiomatic Dart. An underscore prefix makes the property (or method, or class even) private. Otherwise, it’s public.

Also notice how we’ve typed them as DivElement? Another nice feature of Dart (as least for the web) is that it provides classes for the individual HTML elements, unlike the more generic approach usually taken in JavaScript. The upshot is that individual element types have the appropriate properties so it’s easy to manipulate them with Dart. For example, ImageElements have a src property that can be safely and easily accessed directly with Dart to modify the image’s source.

Now let’s create those elements. In the constructor:

DartMarquee(this._target) {
    _mainImage = new Element.tag('div');
    _mainImage.classes = ["mainImage"];
    _thumbContainer = new Element.tag('div');
    _thumbContainer.classes = ["thumbContainer"];
    target.nodes.add(_mainImage);
    target.nodes.add(_thumbContainer);
}

There’s a lot going on here; let’s break it down.

First we create a new DivElement. But notice that we don’t write new DivElement as you might expect (and believe me, I expected that, and continued to expect that for quite a while before I discovered the proper technique). Even though DivElement is a class, it doesn’t have a constructor that you can access. Instead, you use a named constructor on the Element class to create an element of a specific type.

Named constructors are just different constructors (kind of like method overloading, but it’s not really that) that can provide a different interface to the construction. In this case, we can specify by string the type of element. You can also write new Element.html('<div>...</div>'); to write out the HTML in string format. Two rather different approaches, so we have two constructors.

Once we have our _mainImage DivElement, we set its class. Element provides a classes property which lets us access the various classes that may applied. In this case, it’s a brand new element, so that property is empty. We set it to a single class name, "mainImage".

You might expect classes to be an Array (or List, in Dart parlance), but it’s actually a Set. A Set is similar to an Array in that it’s a collection of independent values, but the key difference is that the collection is unordered; there is no guarantee that the order of the contained values will be anything in particular, or even the same each time. This has a slight ramification in how we work with the classes property, but for now it’s a simple assignment to what looks like an Array containing a single String.

The next two lines are repeated almost verbatim, except that we’re assigning the _thumbContainer property, and assigning a different class.

The final two lines add these new Elements to the DOM, specifically, to the target div. As you can see, there is a nodes property on the Element, which as you’d expect is a List of child elements. Being a List (or Array), we can simply add (similar to JavaScript’s push) an Element into it. And at this point, the elements are in the DOM.

Go ahead and run the project again; because we’ve added classes to the new <div>s, and we have our CSS file ready to go, you should see a slight change to the page:

The HTML page as it currently stands

Step 15: Loading JSON

We need some content, not just grey boxes at which to look. We’ll drive our little marquee with a JSON file, so let’s look at how we make an HTTP request in Dart.

First, let’s create the JSON file. It’ll be pretty simple, and shouldn’t need any explaining in and of itself. Create a new file in your Dart project (File > New File…) and name it marquee.json. Add the following content:

{
    "images":[
        "scottwills_machinery3.jpg",
        "scottwills_machinery4.jpg",
        "scottwills_machinery5.jpg",
        "scottwills_machinery6.jpg",
        "scottwills_machinery7.jpg",
        "scottwills_machinery8.jpg"
    ]
}

Save, and turn back to DartMarquee.dart. We’ll add the code to load this file in the constructor, after we’ve created our extra Elements.

XMLHttpRequest request = new XMLHttpRequest();
String url = 'marquee.json';
request.open("GET", url, true);
request.on.load.add(onJSONLoad);
request.send();

And that’s how you do that.

Oh, all right, a little explanation. First, we create an XMLHttpRequest object. That will handle the loading of the data (and would also handle the sending of data if we were doing that sort of thing). The next line is a bit superfluous, but I wanted to show another variable being created. Notice that String types can be created with the quote literal, just like in JavaScript (and just about every other language). In Dart, there is no difference between single- and double-quotes, unlike PHP or Ruby.

Next we start working with the XMLHttpRequest object. First we open the connection, passing in the method ("GET"), the url we just created, and finally that we’re interested in an asynchronous request (true). That means that we need to add an event listener to know when the load completes. That brings us to the most interesting line:

request.on.load.add(onJSONLoad);

This is Dart’s event model. Objects that dispatch events have an on property which acts as “event central”, where you can go to plan your next party. There will also be properties on the on object that correspond to the various events dispatched by the object in question; in this case, load is one of the events. Each of these event properties is actually a collection of listeners, to which we can add a new listener (onJSONLoad in this case; this hasn’t been written yet in case you were wondering).

This syntax took a little getting used to, but now I really like it. It’s safer and cleaner than request.addEventListener('load', onJSONLoad), wouldn’t you agree?

The last line of our previous code block simply sets the request in motion; send it off to get our data.

For this to work, we need an onJSONLoad function. Let’s start doing that next.


Step 16: Methods and Event Listeners

Now we get to write a new method. This method also happens to be an event listener (for the XMLHttpRequest we set up in the last step), but regardless the syntax is the same. Find a spot in the DartMarquee class that’s after the close of the constructor but before the close of the class – it should be between two closing braces. Add the following:

void onJSONLoad(Event e) {
    print("onJSONLoad");
}

The syntax should be fairly obvious. It follows the property/variable syntax, in that we’ve replaced JavaScript’s function keyword with a datatype. The datatype is the type of the value returned by the function. In this case, void is actually the lack of type, as the function doesn’t return anything. And similar to properties, you can optionally leave the method untyped and use the function keyword instead of a type.

Now we can try out the application. Run it again, and check the console. You should get the message that our function has run, meaning the JSON file has loaded.

Success!

Step 17: Properly Bound “this”

Let’s pause in the action for a moment to talk theory. Don’t worry, you’ll learn something important along the way.

In the code that we just wrote to add an event listener, our event listener is properly bound to the scope of the object it belongs to. In JavaScript, this be bound to the object that dispatched the event. That is, if you write this in JavaScript:

myElement.addEventListener('click', onClick);
function onClick() { console.log(this); }

Then this refers to myElement, the object doing the event dispatching. In Dart, however, this will refer to the object to which the listener belongs. Try it out; change the print to this:

void onJSONLoad(Event e) {
    print(this);
}

And run it again. You should see this:

'this' is '[object Object]'

OK, that doesn’t exactly prove things very well. [object Object] could be anything. Let’s take a quick look at a useful trick for making your classes describe themselves.

Add a method to DartMarquee called toString. This method should return a String and take no arguments.

String toString() {
    return "DartMarquee";
}

Run it one more time and now you end up with this:

Our toString method getting called implicitly

This should illustrate that “this” refers to the DartMarquee object. JavaScript does not behave this way without workarounds. This means that you don’t have to worry about binding functions to their scope when adding event listeners, such as with jQuery’s bind method and other similar solutions.


Step 18: Generics

Let’s move on and parse our JSON now that the JSON file is loaded. We’re going to parse it and stuff those URLs into a property, so first let’s trot back to the top of the class and add a _urls property:

Element _target;
DivElement _mainImage;
DivElement _thumbContainer;
List<String> _urls;

This syntax will look odd if you’re not coming from Java. The variable name is _urls, and the datatype is List<String>. We could just write List _urls, and that would work, but we can also take advantage of something that Dart provides. Back towards the beginning, I described reified generics, and the <String> part of the datatype is the generic. That is, the elements within the List are typed as Strings. The point of this step is pretty much to introduce this syntax. We’ll see it again soon.

If you’ve programmed ActionScript 3, you’ll find the syntax similar to Vectors, and in fact Dart Lists and AS3 Vectors are essentially the same thing.


Step 19: Parsing JSON

Now let’s get to parsing. Remove the print statement from onJSONLoad and add this:

void onJSONLoad(Event e) {
    XMLHttpRequest request = e.target;
    Map<String, Object> result = JSON.parse(request.responseText);
    print("JSON: " + result);
    int i = 0;
    _urls = result['images'];
    _urls.forEach((url) {
        print("url $i: $url");
        i++;
    });
}

This code really isn’t so bad. Here’s how it breaks down.

Line 2: This is just casting the source of the event (found in e.target) to an XMLHttpRequest so we can more safely work with properties on it.

Line 3: This one gets a little gnarly. Skip to the second half of the line. We’re getting responseText out of the XMLHttpRequest object, which gives us the raw text found in our file. And we pass that into the parse method of the JSON class. That’s all there is to parsing JSON; it’s essentially built-in! Now, to make sure we can work with the data, we need to store it in a variable. This variable is result. Because I’m advocating strong typing, it also has a type. This type is Map<String, Object>, which might be a little frightening.

A Map is basically what we call an Object in JavaScript; it’s a collection, and stores its values by a String key.

Because Map is a collection, it can be generified (see last step), but because there are technically two things we can specify (the key and the value), we supply two types. Somewhat oddly, you can’t use anything other than String for the key type, so I’m not sure why it needs specified. It may be possible that Dart eventually allows the use of any type as the key. But for now, it’s a String key. Because our JSON data is an Object at it’s outermost, we specify Object as the value type. We have a little flexibility, depending on the JSON structure.

Line 4: Now that we have our JSON parsed, let’s just print it out to verify the result.

Line 5: Initialize a counter. Note that Dart supports an int type.

Line 6: Get the images property out of the main JSON object, which should be an Array/List, and store that in our _urls property that we set up in the last step.

Line 7: Loop over that List, using forEach and an anonymous function. Note the syntax for anonymous functions: (url) {...}. If there is no return type, we can leave it off completely and just start with the parameter list. It feels a little odd at first, but ultimately leads to less code written, which is kind of nice.

Line 8: Now we can print out the URL along with its index. Here we can see that Dart has String interpolation, which lets you expand variables within a String, and avoid breaking out of a String in order to include the value of a variable. The use of the dollar sign indicates that what follows is actually a variable, and Dart should interpolate it. Again, this is less code written and leads to much more readable code than String concatenation.

Line 9: Hopefully this line of code doesn’t need explanation.

Run the application, and…uh oh. That console doesn’t look pretty.

Big old error

Read on for the fix.


Step 20: Importing More Libraries

The fix is, thankfully, rather simple. Dart is structured into libraries, and it turns out that JSON capability isn’t part of the HTML library. We simply need to add the following line at the very top of the file:

#import('dart:json');

Run the project again, and you should get a console full of output:

The JSON data being logged

What I find odd is that this seems like something the JavaScript compiler catches, but it’s only a warning. The compiler recognizes that you’re using a class called JSON but doesn’t know where to find that class…that seems like an important thing to catch. The lesson here, aside from where the JSON library is, is to check the Problems panel in Dart Editor. It got kind of buried amidst the false print warnings, but it was there:

The Problems panel telling us that we should have imported the JSON library

Also, when you run the project, the Console panel takes over in that space, so you may have missed the warnings altogether. Just something to be on the look out for. This kind of thing will probably improve with time.


Step 21: Writing External Classes

As we continue to explore Dart’s capabilities, we’re going to write a new class to handle a single thumbnail image. We’ll ultimately instantiate a number of these, one for each thumbnail.

While it’s possible to insert a second class definition into the same file, let’s see what happens when we decide to write an external class. In Dart Editor, create a new file for our project and name it MarqueeButton.dart. You’ll be presented with the following template:

class MarqueeButton {

}

Again, there is no requirement that we name the class after the file, or vice versa, but it does make sense, so we’ll leave well enough alone and just start filling in the details.

For now, let’s just get this functional by providing a simple constructor that prints a message so we can see it working. Add a constructor to the class:

class MarqueeButton {

    MarqueeButton(index, image) {
        print("$index: $image");
    }
}

Nothing we haven’t been over already; this is a simple constructor that uses String interpolation.

But to use it, we need to make sure the DartMarquee class is aware of the MarqueeButton class. At the top of DartMarqee, where there are two #import statement, add a third line to include our new class:

#import('dart:html');
#import('dart:json');
#source('MarqueeButton.dart');

You were expecting another #import, weren’t you? #source is a bit simpler than #import. #import is for libraries, which need to be declared as such and can link to other files. #source simply includes the targeted file. One thing to note is the #sourced files cannot, themselves, link to other files. Even #importing the built-in libraries will cause a compiler error. As such, this is a simple way to collect a few files into another script, but for more complex structures you may want to consider creating a library.

Now that we’re linking to our new class, let’s use it. Down in onJSONLoad, we’ll replace the existing print with some instantiation:

void onJSONLoad(Event e) {
    XMLHttpRequest request = e.target;
    Map<String, Object> result = JSON.parse(request.responseText);
    print("JSON: " + result);
    int i = 0;
    _urls = result['images'];
    _urls.forEach((url) {
        MarqueeButton btn = new MarqueeButton(i, "images/thumbs/" + url);
        i++;
    });
}

If you run the project again, you’ll get more or less the same thing, only now it’s logging from within the MarqueeButton class.


Step 22: Fill In the “MarqueeButton” Class

At this point, we can fill in most of the MarqueeButton class without running into much that’s new. I’ll present almost the full body of the class here, and discuss it briefly below.

class MarqueeButton {

    DivElement _target;
    String _image;
    int _index;
    Function _onClick;

    MarqueeButton(this._index, this._image) {
        _target = new Element.tag('div');
        _target.classes = ["button"];
        DivElement border = new Element.tag('div');
        border.classes = ["border"];
        _target.nodes.add(border);

        _target.style.backgroundImage = 'url("'+_image+'")';

        _target.on.click.add(onClick);
    }

    void onClick(Event e) {
        _target.classes.add('selected');
        _onClick(this);
    }

}

We start the class off with a handful of properties, all private and typed. It may be interesting to note the Function type. We’ll get to this in a moment, but this illustrates that functions are fully-fledged objects in Dart, and can be passed around by reference rather easily.

The constructor is mostly about building up the HTML elements for the button. We start from scratch; the only things passed in to the constructor are the index of the button and the image URL. We’ve seen this before, creating and adding new elements. Line 15, however, present something new, although I’d imagine you can figure out what it does. Elements have a style property which lets you set CSS styles rather easily. The properties available to the style object follow the CSS style names, only removing the hyphen and turning the name camel-case. Note that the value might be a String or in the case of numeric values, it can just be a number.

The last line of the constructor adds a click event listener to the button, following the convention we saw with the XMLHttpRequest events.

Then we have our onClick method, the listener for that click event. For style purposes we’ll add the .selected class to the element, then we call the _onClick function. This, you’ll recall, is the property we declared earlier. This is a poor man’s event dispatching, and what happens is that DartMarquee will set this property to a function of its own, so that MarqueeButton can call it. We’ll get to the setting in a moment, and we haven’t written the relevant DartMarquee code. But because functions are first-class citizens of the Dart world, it’s easy to pass that function around, and execute it somewhat arbitrarily.


Step 23: Setters and Getters

We’ll finish off the class with some getters and a setter. For the uninitiated, setters and getters are special functions that simply return a value (getters), or receive a value (setters). They’re common enough, and most object-oriented languages provide some method for creating implicit setters and getters, which are functions that are called as if they were properties.

Dart has this, as well, and throws some syntactic sugar on top of it, to boot. Add this to the end of the class (before the closing curly brace, but after the onClick method):

DivElement get target() => _target;
int get index() => _index;

Function get click() => _onClick;
void set click(Function fn) {
    _onClick = fn;
}

You can see the sugar in the three getters. Each one follows this pattern:

Type get name() => expression;

The type is nothing new; it’s the return type of the function. The get keyword signifies that this is an implicit getter function. name() is just the name of the method. Next is the => operator, which basically says “return the value that is expressed on my right.” In the case of _target, we’re simply accessing the value stored in the _target property and returning that. In other words, a basic getter method, written with a little less code than normal.

The expression can actually get a little more complicated than that, such as a boolean check or some simple one-liner math. If it’s going to require more than one line of code, it needs to be written as a regular getter, which is just like a regular method except for the get keyword:

DivElement get target() {
    return _target;
}

We’re done with the MarqueeButton class now, so we’ll turn back to the DartMarquee class and start using it.


Step 24: Displaying Thumbnails

To display the buttons, we need to go back to the DartMarquee class and revisit the onJSONLoad method. Specifically, we need to add to that loop.

_urls.forEach((url) {
    MarqueeButton btn = new MarqueeButton(i, "images/thumbs/" + url);
    _thumbContainer.nodes.add(btn.target);
    btn.click = onThumbClick;
    i++;
});

Another nodes.add(), this time on the _thumbContainer div and adding the target of the MarqueeButton object.

Then we set the click property to a method we have yet to write, but will do so now:

void onThumbClick(MarqueeButton btn) {
    print("onThumbClick");
}

We’ll work on this next, but for now we should be able to run the application, see the thumbnails, and click on them to see the log message.

The thumb click works

We’re almost there. We’ll work on getting that click to mean something in the next two steps.


Step 25: Handling the Click

The logic involved in displaying a larger image isn’t terribly complex, and at this point we’ve had a pretty extensive tour of the Dart language. I’ll start listing the method here, and then discuss what’s going on.

First we need two properties declared. At the top of the class, with the other properties, add these lines:

MarqueeButton _currentButton;
ImageElement _currentImage;

Then update onThumbClick:

void onThumbClick(MarqueeButton btn) {
    if (_currentButton != null) {
        _currentButton.target.classes.remove('selected');
    }
    _currentButton = btn;
    ImageElement image = new Element.tag('img');
    image.width = 600;
    image.height = 300;
    image.src = "images/" + _urls[btn.index];
    _mainImage.nodes.add(image);
}

The first thing to notice is that we’re checking for the existence of a value in _currentButton. If it does, then we remove the .selected class. Then we set the _currentButton property to the button that was clicked, for next time.

It’s worth nothing that Dart handles Booleans a little differently than you may be used to. Seth Ladd has a write-up on Booleans in Dart, in which we explains:

Dart has a true boolean type named bool, with only two values: true and false (and, I suppose, null). Due to Dart’s boolean conversion rules, all values except true are converted to false. Dart’s boolean expressions return the actual boolean result, not the last encountered value.

Therefore, when checking for the existence of a value within a variable, it’s wise to write if (variable != null) as opposed to the shorthand if (variable), as that could actually report false even through the variable has a valid value stored in it.

Next we create an image element, set its size, the src, and then add it as a child.

You should be able to try this out now. We won’t get a nice fade between the images, but you should now be able to use the marquee to switch images.


Step 26: Working with the Transition

Let’s work on that fade. Add the highlighted code below to the onThumbClick method. Note that Line 11 is a change from how it was before (it uses insertAdjacentElement), and the lines after that are new.

void onThumbClick(MarqueeButton e) {
    if (_currentButton != null) {
        _currentButton.target.classes.remove('selected');
        print(_currentButton.target.classes);
    }
    _currentButton = e;
    ImageElement image = new Element.tag('img');
    image.width = 600;
    image.height = 300;
    image.src = "images/" + _urls[e.index];
    _mainImage.insertAdjacentElement('afterBegin', image);

    if (_currentImage != null) _currentImage.classes.add('fade_away');
    _currentImage = image;
    image.on.transitionEnd.add((evt) {
        ImageElement img = evt.target;
        img.remove();
    });
}

The change to line 53 introduces another way to add children elements. Element.nodes.add() is fine for appending at the end, but if we want to insert in a specific place, in this case at the beginning, then nodes doesn’t give us enough options. insertAdjacentElement does provide options, although its interface isn’t as clean as it could be. In fact, it’s lifted from the Windows Internet Explorer API. I try not to get too opinionated in a tutorial, but this is an odd decision.

Regardless, it’s the API we have if we want to do more than append to the child elements. We want to add our new image to the beginning, so we pass in "afterBegin" to insertAdjacentElement, which does exactly that. This method is documented at MSDN if you’d like a description of the various valid arguments to that parameter.

The rest of the code involves itself with the CSS3 transition; by adding a .fade_away class to the old image (after checking to be sure it’s not null) we set it’s opacity to 0, invoking the transition. Then _currentImage is set to the new image, to get set for the next transition.

Finally, another event listener is added to the current image so that when the transition happens, and is finished, we can run a bit of code. All we do is get the event target and cast it as an ImageElement (not strictly necessary, but it’s something that I find useful to do in general). Then by calling remove() on the ImageElement, we remove it from the DOM. In other words, once it fade away completely, we can remove it altogether to keep our DOM tidy.

Note also that we’re using another anonymous function as the event listener in this case. Either way would work, but since this is practically a one-line function, making it anonymous is rather convenient.

Run the application, click on one thumb to load an image, then another thumb and watch it in silent awe.

A still image rendition of the fade in action

Step 27: The Final Touch

Our Dart application is rather functional now, but you’ve probably noticed that it has one minor flaw: there is not image loaded up right away. This is a simple fix.

In Marquee.dart, find the onJSONLoad method and add the highlighted line of code toward the bottom:

void onJSONLoad(Event e) {
    XMLHttpRequest request = e.target;
    Map<String, Object> result = JSON.parse(request.responseText);
    print("JSON: " + result);
    int i = 0;
    _urls = result['images'];
    _urls.forEach((url) {
        MarqueeButton btn = new MarqueeButton(i, "images/thumbs/" + url);
        _thumbContainer.nodes.add(btn.target);
        btn.click = onThumbClick;
        if (i == 0) btn.onClick(null);
        i++;
    });
}

In effect, if we’re on the first iteration, take that MarqueeButton and call its onClick method. You’ll remember that as the event listener for the click event within the MarqueeButton. We’ll just call it directly, to sort of simulate a click on the first button, so as to trigger the setting of the styles and putting content in the right place. Since the method expects an event parameter, but isn’t really used, we can supply null to the method call to satisfy the compiler.

Run it once more, and you should now have the first image selected and ready in the main area.


Step 28: Where To Go From Here

We’ve just scratched the surface of Dart, but the cool thing is that if you know JavaScript, you already know Dart in one sense. You’re already familiar with what you can do with an HTML page, and generally how to do it. Dart for the web doesn’t really add any capabilities or fancy frameworks, it’s just another language in the same problem domain. If you want to learn more, you can do worse than to simply write applications in Dart. Maybe dig out a smallish/simple bit of JavaScript you’ve done and port it over to Dart.

If you like scouring the web for more resources, Google is certainly your friend, although the name “Dart” can lead to many unrelated hits that are about the game of darts, rather than the language. Many times I’ve had to specify “dart language” in my searches or get a little more specific than just “dart events”. There is quite a bit of information floating around.

First, the official Dart website is at dartlang.org. You’ll find a small tutorial there that goes into some of the unique language features, along with the nifty Dartboard widget that lets your write and execute dart code in the browser you can even use the widget on your own site).

If you think you know what you need to do, just don’t know the right method name or class, the API documentation is good place to start, at api.dartlang.org. Sometimes the docs are a little bare or even wrong, but you should probably begin any quest for an answer here.

I’ve already mentioned the mailing list, located at groups.google.com/a/dartlang.org/group/misc/topics. It’s very active and I had a few questions answered in a matter of minutes there. The Google engineers are very involved on the list, as well.

The Dart site also has a pretty nice JavaScript-to-Dart comparison chart, located at synonym.dartlang.org, which takes common JavaScript code snippets and shows the equivalent Dart code right beside it.

Moving away from Google’s own resources, there are a few Dart-centric blogs that kept coming up in searches. One of the most prolific is Japh(r) by Chris Strom, at japhr.blogspot.com/search/label/dartlang, who is also writing a book on Dart.

The Dartosphere (dartosphere.org aggregates several different blogs about Dart, and can be a gold mine of information.

Seth Ladd works at Google, and his blog at blog.sethladd.com has been recently devoted to Dart.

DartWatch, at dartwatch.com, is another Dart-centric blog that has plenty of content to keep you busy.

One problem, however, is that Dart is a bit of a moving target currently, and some of the older posts on blogs might be out-of-date by the time you get to them. Just keep that in mind. The mailing list is the best place to go if you can’t find a solution through a web search.

One last resource: if this tutorial sparks some interest amongst Tuts+ readers, then we’ll probably find a few more tutorials to write that delve deeper into the world of Dart.


Step 29: Regarding Events

In this tutorial, we learned how to attach event listeners to object, for example:

someElement.on.click.add(myClickListener);
someHTTPRequest.on.load.add(myLoadListener);

You may have noticed that we did not leverage this model when we needed to have the MarqueeButton object communicate to the DartMarquee object. We went for a more lo-fi event listener, where we simply pass a Function in to the object, and then call that Function from within the object. You may ask yourself, why did we do that? Why didn’t we use the on property to dispatch an event? Where does that highway lead to?

The answer is that Dart doesn’t provide this event mechanism outside of its own objects. Not only that, that event system is only available to objects in the HTML libraries. This feels like an area where Google might be able to open up. It sure would be nice to have our own classes become event dispatchers by simply extending an EventDispatcher class or similar, and with a little bit of code getting that mechanism for free.

It’s possible to build your own system that mimics the built-in mechanism, but for the purposes of this tutorial, I went the lo-fi route. There may be some future Dart tutorials that go deeper.


Conclusion

Is Dart the future? Some say yes, some say no. I say, “I don’t know”. I’m certainly intrigued by the possibilities, and as long as it compiles to usable JavaScript today, then maybe it doesn’t matter if Dart isn’t interpreted natively by all of the browsers.

For now, I would say that if CoffeeScript is something that’s been catching on, then the Dart-to-JavaScript technique certainly has the same opportunity. Unlike CoffeeScript, though, you end up with some overhead JavaScript, which may not be appropriate for a vast majority of JavaScript-enabled web pages today. For instance, our DartMarquee project compiles into a JavaScript that’s over 100 KB. That’s a bit much for such a simple marquee. One should be able to write that in regular JavaScript, aided by jQuery or a similar library, for well under that weight limit. And the niceties provided by Dart, with classes, typing, and imports, aren’t enough for this small application to really justify the size.

But for larger applications, like Google Docs, 280 Slides, or Mockingbird, then you can very easily justify the overhead. You’ll have hundreds of KB of JavaScript anyway, so a little extra for the compilation process in exchange for a more structured set of classes will definitely appeal to some programmers.

That’s all for this introduction to Dart. Thanks for reading. I hope it was enlightening for you!



View full post on Activetuts+

banner ad

10 Responses to “Intro to Dart: Creating a Marquee”

  1. Dru Kepple says:
    June 29, 2012 at 9:00 am

    In this tutorial, I’ll introduce you to Dart and how to start using it. In the course of the article we’ll build a simple JavaScript-based image marquee without writing a single line of JavaScript – just Dart.

    Note: This tutorial was originally published in March 2012, as a freebie for our Facebook fans.


    Project Preview

    We will be building the following simple marquee, a screenshot of which is shown below. Click on the image to launch a working example of the project.

    Click the image to launch the project

    Step 1: Install the Dart Editor

    Let’s get started building out little marquee. From here on out, we’ll be much more hands-on, and I’ll take the time explain the new stuff along the way.

    First things first; we can write Dart in any old text editor, really, but the most convenient way to get started and to immediately run your project in a browser (via JavaScript compilation) is to install the Dart Editor.

    Head to http://www.dartlang.org/docs/getting-started/editor/, which should automatically detect your OS and present you with the appropriate download link. It’s not a small download, around 65 MB at this writing, so get it started before continuing to read.

    The Dart Editor is rather bare-bones. It’s built on Eclipse, and I hope that eventually it will be offered as an Eclipse plug-in for those with an existing Eclipse installation. But for now, it’s a self-contained Eclipse modification that does Dart and not much else.

    It offers a few of the features that Eclipse workspaces typically offer, such as language-aware completion. The big advantage it brings, though, is a fairly simple way to start and run a Dart project.

    Once the download completes, extract the ZIP file and you’ll have a dart folder. You can place this wherever you like; I’ve moved mine to my Applications folder.


    Step 2: Create a Dart Project

    Let’s open up the Dart Editor application. You’ll find it just inside that dart folder you just unzipped.

    Once it launches, you’ll be presented with a “Welcome” page, which provides a jumping-off point to some sample projects. These are certainly worth taking a look, but we’ll skip past them for now and first get a little more familiar with the language.

    The first thing you'll see when opening Dart Editor

    Go to the File menu and choose New Application… or click on the top-left icon in the toolbar:

    The 'New Application' tool bar button

    In the resulting window, enter a name for the project (I’m using DartMarquee). It will want to store the project in a folder named dart in your home directory, but you can change that by clicking on the Browse… button. Note that whichever folder you choose, Dart Editor will create a new folder in the selected folder, using the name you’ve given for the project. Inside of that there will be a few files created for you, also using the name of the project you supplied.

    Also be sure the “Web Application” is selected, not “Server Application.”

    The 'New Application' window

    Step 3: Run the Hello World Example

    The default project created for you is a simple Hello World example. You may as well see what happens before we start building our (slightly) more complicated project. Run the application by either choosing Tools > Run from the menu, pressing Command-R (Mac) or Control-R (PC), or by clicking on the green “play” button in the tool bar:

    The 'Run' Button

    You may expect this open up in your default browser, but – surprise! – Google’s Chromium browser will open (not to be confused with Chrome; Chromium has a blue-ish monochrome icon, not Chrome’s colorful icon). Chromium has built-in support the the Dart language.

    Chromium

    This is not the process I mentioned earlier where Dart files are compiled into JavaScript; this is the Dart VM running regular Dart code, which is cool, but not terribly useful for those of us currently building JavaScript applications. We’ll make the project compile to JavaScript next.


    Step 4: Add a JavaScript Launch

    If you change the run settings, then we can get Dart to compile to JavaScript. To change these settings, choose the Tools > Manage Launches… menu, press Command-Shift-M (Mac) or Control-Shift-M (PC), or click and hold the downward arrow next to the Run tool bar button, and choose Manage Launches… from the pop-up menu.

    The Manage Launches option int he tool bar

    In the window that appears, you’ll see the default launch created for you, which has the Chromium icon. To create a new launch, click on the new document icon, which will display a pop-up menu.

    New Launch targets

    Choose Dart Web Launch from the menu. In the top field at the right, give it a meaningful name, like DartMarquee JS or something to designate that we’re going for a JavaScript rendition in another browser.

    Under Launch Target, click Browse… next to HTML file:. A window will open that presents all (one) HTML files present in your project. Click on DartMarquee.html and then click OK.

    Under Browser you can choose to leave the default checked, or uncheck that option and then specify a browser with the Select… button. The browser choice shouldn’t matter too much, although I will be using some CSS3 tricks so a modern browser would be ideal.

    Click Apply and then Close.

    Now run the project again, but this time be sure to do it by clicking and holding on the Run tool bar button, and then selecting your new launch target. You should now get the same Hello World application in the browser of your choosing, which will be using JavaScript compiled from Dart. In fact, you’ll see a new file show up in your file list: DartMarquee.dart.js. This is the compiled JavaScript file.

    Now that you’ve run the new launch once, future Runs will remember this decision and launch the JavaScript version.

    But we’re not done yet. The HTML file is set up to include the Dart file, along with another JavaScript file that interprets Dart files in the browser (which is super-cool, but not the best for production applications). We need to edit the HTML file to use the compiled JavaScript file, not the Dart files.


    Step 5: The HTML

    Your new project should open with DartMaquee.dart in the main editor area. We’ll get to that soon enough, but let’s get our HTML page set up. Double-click on DartMarquee.html in the file list on the left, and it will open in a new tab in the editor.

    Dart Editor is really only aware of the Dart language, which is too bad. You’ll notice that the HTML file opens without any syntax coloring or intelligence about the language. It’s good enough for our purposes now, but feel free to open this file (and any other non-Dart file) in the text editor of your choosing. We won’t be spending too much time in non-Dart files, so I’ll just be editing them in Dart Editor for this tutorial.

    The body markup is not what we want, but first let’s update those <script> tags as mentioned in the last step. You can delete the first <script> tag altogether; that’s the once that includes the Dart file directly. Delete this line:

    
    
    <script src="http://dart.googlecode.com/svn/branches/bleeding_edge/dart/client/dart.js"></script&gt;
    

    (Hint: line numbers aren’t enabled by default, but that’s one of the few options available under Preferences).

    The script is the in-browser runtime for Dart; one pretty nifty feature is that you can write Dart without compiling it to JavaScript, and have browsers run it anyway. You just need to include dart.js. Of course, this makes for some extra overhead and impacts performance. Pretty cool trick, though.

    Now let’s change the remaining <script> tag to load our compiled JavaScript file. Change this:

    
    
    <script type="application/dart" src="DartMarquee.dart"></script>
    

    To this:

    
    
    <script src="DartMarquee.dart.js"></script>
    

    If you like, run the project again, and use the developer tool to ensure that the JavaScript file is loading, and the other two are not.

    Now, change that <h2> tag into a <div>, and give it an id of marquee.

    
    
    <div id="marquee"></div>
    

    You can leave the <h1> if you like; sometimes it’s nice to have page identification.

    Finally, we need to link to a CSS file (which we’ll create in the next step). In the <head> add a <link> tag:

    
    
    <link rel="stylesheet" href="DartMarquee.css">
    

    The application will not work, because we’ve removed the <h2> that was targeted by the Dart code, not to mention that we still need a CSS file. Let’s do that next.


    Step 6: The CSS

    We’ve linked to a non-existent CSS file, so let’s address that. In the Files area of Dart Editor, right-click, and choose New File: from the menu (you can also find New File… in the File menu).

    In the resulting window, you may need to ensure that the DartMarquee project is selected in the middle area. Then enter DartMarquee.css for the file name, and click on Finish.

    The New File window

    This file will be ready to edit in the main editor area, but as with HTML files, CSS files aren’t intelligently supported with syntax by Dart Editor. Feel free to do your CSS editing in your preferred text editor. Or, since we’re really not here to delve into the CSS, just copy and paste form below into Dart Editor:

    
    
    #marquee {
        width: 600px;
        height: 400px;
        background-color: #111;
    }
    
    .mainImage {
        height: 300px;
        background-color: #666;
        position: relative;
    }
    .mainImage img {
        display: block;
        position:absolute;
        left: 0px;
        top: 0px;
        -webkit-transition: opacity 0.6s ease-out;
           -moz-transition: opacity 0.6s ease-out;
            -ms-transition: opacity 0.6s ease-out;
             -o-transition: opacity 0.6s ease-out;
                transition: opacity 0.6s ease-out;
    }
    .mainImage img.fade_away {
        opacity: 0;
    }
    
    .thumbContainer {
        height: 100px;
        background-color: #DDD;
    }
    
    .button {
        width: 100px;
        height: 100px;
        background-color: #eee;
        position: relative;
        float: left;
    }
    
    .button .border {
        width: 90px;
        height: 90px;
        position: absolute;
        opacity: 0;
        border: 5px solid orange;
        -webkit-transition: opacity 0.3s ease-out;
           -moz-transition: opacity 0.3s ease-out;
            -ms-transition: opacity 0.3s ease-out;
             -o-transition: opacity 0.3s ease-out;
                transition: opacity 0.3s ease-out;
        cursor: pointer;
    }
    .button:hover .border {
        opacity: .5;
    }
    .button.selected .border {
        opacity: 1;
    }
    

    Again, we’re not here to discuss CSS. I’ll point out that I’m using CSS3 transitions for the button hovers and the main image changes. Otherwise, it should be fairly straightforward.

    Run the project one more time, or simply reload from the browser; at this point there won’t be any JavaScript to re-compile. If you run from Dart Editor, be sure to switch back to the HTML or Dart file; Dart Editor doesn’t know what to do when you “Run” from a CSS file.

    You should see a large dark rectangle. Doesn’t look like much yet, but you’re on the right tack.


    Step 7: Preparing the Images

    One more housekeeping task, and that’s to make our images readily accessible, so that we can see them when we’re ready to write that code.

    In the download package, you’ll find a folder named images. Copy or move this folder from the download archive to your project folder, so that’s sitting at the same level as your other files. You’ll probably need to use the Finder/Explorer for this task, as Dart Editor doesn’t (yet) support importing or drag-and-drop of existing files. They’ll show up in your file list once you get them in place, though.

    The project structure so far

    Now we can get into some Dart code. That’s next!


    Step 8: The main() Function

    Open up the DartMarquee.dart file in the editor. You’ll see three main blocks of code:

    The three main sections in the default Dart file

    The third block is the main function, and this is a required part of your Dart project. Dart will look for this function as an entry point to execution. Contrast this with JavaScript where scripts are simply executed from top to bottom. You can certainly replicate this methodology in JavaScript, but the key difference is that you don’t have to, and if you do you have to call main() yourself; in Dart, it’s expected that you have the main function, as it will be called for you once Dart in ready to begin execution of your application.

    This won’t be a foreign concept to you if you’ve programmed in C or Java, or even in ActionScript 3 and used the Document class. The nice thing about it is that there is a standardized, expected place to begin the execution of your code.


    Step 9: Classes

    Dart brings with it proper classes, which you may end up preferring to JavaScript’s class-ish-ness prototype system. Take a look at the second block of code in DartMarquee.dart. This is the meat of the program right now, and is a class with two methods declared. We’ll be ditching a large part of this code. We’ll get into the syntax as we go, but for now, hollow out this class so that it looks like this:

    
    
    class DartMarquee {
    
        DartMarquee() {
        }
    
    }
    

    What this leaves is the class declaration and the constructor. The class declaration begins with class, which is followed by the name of the class. That this class is named DartMarquee is purely a function of the template used in the application creation process in DartEditor. It’s important to know that just because this file is named “DartMarquee.dart” does not mean that there has to be a class name DartMarquee inside. We’re not going to change it, because it makes sense, but Dart is like PHP or Ruby in that you can put as many class definitions as you like in a single file, and the naming doesn’t need to match the file name (as it does in ActionScript).

    The class definition is then contained between the curly braces. Inside of that, we have a constructor. This is a function that is run when a new object is instantiated from this class. Typically one puts set-up code in a constructor. Note that the name of the constructor needs to match the name of the class, otherwise it’s not a constructor, and is a regular method instead.

    Everything else you add to a class should go in between the two curly braces denoting the class.

    You’ll notice that back in the main function, a DartMarquee object is instantiate with this line:

    
    
    new DartMarquee().run();
    

    This should look like object-oriented JavaScript. The .run() then calls the run method on the newly-created object. We just removed that method, so go ahead and change that line to this:

    
    
    new DartMarquee();
    

    Step 10: Imports

    Something I’m pretty excited about with Dart, as someone coming from JavaScript, is the ability to easily import and use other code into your project. The first block of our default code uses a single import statement:

    
    
    #import('dart:html');
    

    This imports a built-in Dart library, one that deals specifically with HTML pages and giving us access to DOM manipulation functionality. We’ll be importing other libraries as we need them, including one that we’ll write ourselves.

    When our Dart project is compiled to JavaScript, all of the disparate Dart code is converted and concatenated into a single JavaScript file. It’s smart enough to not include the same library twice, so you can import libraries from other files and not worry about them conflicting with or duplicating code in the final product.

    Our DartMarquee.dart file should look something like this now:

    
    
    #import('dart:html');
    
    class DartMarquee {
    
        DartMarquee() {
        }
    
    }
    
    function main() {
        new DartMarquee();
    }
    

    Step 11: Add a Property to the Class

    Let’s finally write code. We’re going to add a target property to the DartMarquee class, so that the main HTML element that we’re referencing is handy within the class.

    Just after the class declaration, and before the constructor, add a property like so:

    
    
    class DartMarquee {
    
        Element _target;
    
        DartMarquee() {
        }
    
    }
    

    Notice the syntax here: instead of var, we use a datatype to both declare a variable and give it a datatype all at once. This syntax is reminiscent of C and Java. The name of our property is _target, and the line ends with a semi-colon. You’ll find Dart much less forgiving about missing semi-colons.

    An interesting thing about Dart type system is that it’s optional. If you specify a type, Dart will do what it can to adhere to typing rules. But we could also opt to leave typing off by writing that property like this:

    
    
    var _target;
    

    Dart will then not attempt to keep your types safe; you’ll have a dynamically-typed variable just like in JavaScript. What’s even more interesting than the fact that it’s optional is that you can mix strong and dynamic typing in the same code.

    Personally, strong typing is one of the things that draws me to Dart, as it’s helpful to have that kind of accountability. This will be the last time I mention dynamic typing in Dart.

    We’re not done with that property yet. This is an important property, so let’s set it in the constructor.

    
    
    class DartMarquee {
    
        Element _target;
    
        DartMarquee(this._target) {
        }
    
    }
    

    This may look a little unexpected. This is a Dart idiom; it’s so common for a constructor to receive arguments, and then simply use the constructor’s body to stash those values into properties, that Google created a shortcut.

    Normally, a method parameter looks like you’d expect it to: any variable name will do, but not something that looks like a property on another object. These parameters are normal parameters like you’re used to; they’re available by name within the body of the method.

    This new syntax, however, will go ahead and assign the value passed in to this parameter to the property designated by the parameter name. In other words, the code above is identical to this code:

    
    
    DartMarquee(target) {
        this._target = target;
    }
    

    Only we don’t have to write that boilerplate of a line.

    Note that this shortcut is only available in constructors.


    Step 12: DOM Queries

    Now that we have a target property set up, we need to give it a value. Back in the main function, we need to select the marquee <div> and pass it in to the constructor.

    Dart provides a method to find HTML elements by CSS selection, much like jQuery or any of the popular JavaScript libraries do. This is provided by that dart:html library imported at the top of the file, which also provides a top-level document variable which gives us global access to the HTML document.

    Update the main function to look like this:

    
    
    void main() {
        new DartMarquee(document.query('#marquee'));
    }
    

    It’s that simple: if you’ve used jQuery (or another library), this should be rather familiar. Simply call document.query and pass in the selector. Dart does the rest.


    Step 13: Console Logging

    If you’ve developed with JavaScript, chances are you’ve made heavy use of console.log to test and verify your code. Dart provides a print function that, when compiled to JavaScript, turns in to a call to console.log. Let’s try it out, and test our project so far at the same time.

    In the DartMarquee constructor, let’s print the _target property to make sure it’s being set.

    
    
    DartMarquee(this._target) {
        print(this._target);
    }
    

    And hit Run. In your browser, open up your console and you should see something like this:

    The result of a print

    Note that at the time of this writing, there is a bug with the Dart Editor that generates a warning stating that “print” is not a method. This is being tracked by Google and will probably be fixed soon, if not by the time you read this. But if you’re seeing that warning, just ignore it; it still compiles fine. This is an example of the bleeding edge on which Dart stands; the print warning was not happening when I started writing this tutorial, it’s only happened with the most recent build of the Editor (build 5104).


    Step 14: DOM Manipulation

    We’re going to create the needed HTML elements programmatically, and place them within our target <div>. Dart provides a very clean API for this kind of task.

    First, let’s create a few more properties to hold some of the elements. Add these right below the first property you added:

    
    
    class DartMarquee {
    
        Element _target;
        DivElement _mainImage;
        DivElement _thumbContainer;
    
        DartMarquee(this._target) {
    

    Notice how we’re using underscores as a prefix? Not only this a common convention when naming private properties, it’s actually idiomatic Dart. An underscore prefix makes the property (or method, or class even) private. Otherwise, it’s public.

    Also notice how we’ve typed them as DivElement? Another nice feature of Dart (as least for the web) is that it provides classes for the individual HTML elements, unlike the more generic approach usually taken in JavaScript. The upshot is that individual element types have the appropriate properties so it’s easy to manipulate them with Dart. For example, ImageElements have a src property that can be safely and easily accessed directly with Dart to modify the image’s source.

    Now let’s create those elements. In the constructor:

    
    
    DartMarquee(this._target) {
        _mainImage = new Element.tag('div');
        _mainImage.classes = ["mainImage"];
        _thumbContainer = new Element.tag('div');
        _thumbContainer.classes = ["thumbContainer"];
        target.nodes.add(_mainImage);
        target.nodes.add(_thumbContainer);
    }
    

    There’s a lot going on here; let’s break it down.

    First we create a new DivElement. But notice that we don’t write new DivElement as you might expect (and believe me, I expected that, and continued to expect that for quite a while before I discovered the proper technique). Even though DivElement is a class, it doesn’t have a constructor that you can access. Instead, you use a named constructor on the Element class to create an element of a specific type.

    Named constructors are just different constructors (kind of like method overloading, but it’s not really that) that can provide a different interface to the construction. In this case, we can specify by string the type of element. You can also write new Element.html('<div>...</div>'); to write out the HTML in string format. Two rather different approaches, so we have two constructors.

    Once we have our _mainImage DivElement, we set its class. Element provides a classes property which lets us access the various classes that may applied. In this case, it’s a brand new element, so that property is empty. We set it to a single class name, "mainImage".

    You might expect classes to be an Array (or List, in Dart parlance), but it’s actually a Set. A Set is similar to an Array in that it’s a collection of independent values, but the key difference is that the collection is unordered; there is no guarantee that the order of the contained values will be anything in particular, or even the same each time. This has a slight ramification in how we work with the classes property, but for now it’s a simple assignment to what looks like an Array containing a single String.

    The next two lines are repeated almost verbatim, except that we’re assigning the _thumbContainer property, and assigning a different class.

    The final two lines add these new Elements to the DOM, specifically, to the target div. As you can see, there is a nodes property on the Element, which as you’d expect is a List of child elements. Being a List (or Array), we can simply add (similar to JavaScript’s push) an Element into it. And at this point, the elements are in the DOM.

    Go ahead and run the project again; because we’ve added classes to the new <div>s, and we have our CSS file ready to go, you should see a slight change to the page:

    The HTML page as it currently stands

    Step 15: Loading JSON

    We need some content, not just grey boxes at which to look. We’ll drive our little marquee with a JSON file, so let’s look at how we make an HTTP request in Dart.

    First, let’s create the JSON file. It’ll be pretty simple, and shouldn’t need any explaining in and of itself. Create a new file in your Dart project (File > New File…) and name it marquee.json. Add the following content:

    
    
    {
        "images":[
            "scottwills_machinery3.jpg",
            "scottwills_machinery4.jpg",
            "scottwills_machinery5.jpg",
            "scottwills_machinery6.jpg",
            "scottwills_machinery7.jpg",
            "scottwills_machinery8.jpg"
        ]
    }
    

    Save, and turn back to DartMarquee.dart. We’ll add the code to load this file in the constructor, after we’ve created our extra Elements.

    
    
    XMLHttpRequest request = new XMLHttpRequest();
    String url = 'marquee.json';
    request.open("GET", url, true);
    request.on.load.add(onJSONLoad);
    request.send();
    

    And that’s how you do that.

    Oh, all right, a little explanation. First, we create an XMLHttpRequest object. That will handle the loading of the data (and would also handle the sending of data if we were doing that sort of thing). The next line is a bit superfluous, but I wanted to show another variable being created. Notice that String types can be created with the quote literal, just like in JavaScript (and just about every other language). In Dart, there is no difference between single- and double-quotes, unlike PHP or Ruby.

    Next we start working with the XMLHttpRequest object. First we open the connection, passing in the method ("GET"), the url we just created, and finally that we’re interested in an asynchronous request (true). That means that we need to add an event listener to know when the load completes. That brings us to the most interesting line:

    
    
    request.on.load.add(onJSONLoad);
    

    This is Dart’s event model. Objects that dispatch events have an on property which acts as “event central”, where you can go to plan your next party. There will also be properties on the on object that correspond to the various events dispatched by the object in question; in this case, load is one of the events. Each of these event properties is actually a collection of listeners, to which we can add a new listener (onJSONLoad in this case; this hasn’t been written yet in case you were wondering).

    This syntax took a little getting used to, but now I really like it. It’s safer and cleaner than request.addEventListener('load', onJSONLoad), wouldn’t you agree?

    The last line of our previous code block simply sets the request in motion; send it off to get our data.

    For this to work, we need an onJSONLoad function. Let’s start doing that next.


    Step 16: Methods and Event Listeners

    Now we get to write a new method. This method also happens to be an event listener (for the XMLHttpRequest we set up in the last step), but regardless the syntax is the same. Find a spot in the DartMarquee class that’s after the close of the constructor but before the close of the class – it should be between two closing braces. Add the following:

    
    
    void onJSONLoad(Event e) {
        print("onJSONLoad");
    }
    

    The syntax should be fairly obvious. It follows the property/variable syntax, in that we’ve replaced JavaScript’s function keyword with a datatype. The datatype is the type of the value returned by the function. In this case, void is actually the lack of type, as the function doesn’t return anything. And similar to properties, you can optionally leave the method untyped and use the function keyword instead of a type.

    Now we can try out the application. Run it again, and check the console. You should get the message that our function has run, meaning the JSON file has loaded.

    Success!

    Step 17: Properly Bound “this”

    Let’s pause in the action for a moment to talk theory. Don’t worry, you’ll learn something important along the way.

    In the code that we just wrote to add an event listener, our event listener is properly bound to the scope of the object it belongs to. In JavaScript, this be bound to the object that dispatched the event. That is, if you write this in JavaScript:

    
    
    myElement.addEventListener('click', onClick);
    function onClick() { console.log(this); }
    

    Then this refers to myElement, the object doing the event dispatching. In Dart, however, this will refer to the object to which the listener belongs. Try it out; change the print to this:

    
    
    void onJSONLoad(Event e) {
        print(this);
    }
    

    And run it again. You should see this:

    'this' is '[object Object]'

    OK, that doesn’t exactly prove things very well. [object Object] could be anything. Let’s take a quick look at a useful trick for making your classes describe themselves.

    Add a method to DartMarquee called toString. This method should return a String and take no arguments.

    
    
    String toString() {
        return "DartMarquee";
    }
    

    Run it one more time and now you end up with this:

    Our toString method getting called implicitly

    This should illustrate that “this” refers to the DartMarquee object. JavaScript does not behave this way without workarounds. This means that you don’t have to worry about binding functions to their scope when adding event listeners, such as with jQuery’s bind method and other similar solutions.


    Step 18: Generics

    Let’s move on and parse our JSON now that the JSON file is loaded. We’re going to parse it and stuff those URLs into a property, so first let’s trot back to the top of the class and add a _urls property:

    
    
    Element _target;
    DivElement _mainImage;
    DivElement _thumbContainer;
    List<String> _urls;
    

    This syntax will look odd if you’re not coming from Java. The variable name is _urls, and the datatype is List<String>. We could just write List _urls, and that would work, but we can also take advantage of something that Dart provides. Back towards the beginning, I described reified generics, and the <String> part of the datatype is the generic. That is, the elements within the List are typed as Strings. The point of this step is pretty much to introduce this syntax. We’ll see it again soon.

    If you’ve programmed ActionScript 3, you’ll find the syntax similar to Vectors, and in fact Dart Lists and AS3 Vectors are essentially the same thing.


    Step 19: Parsing JSON

    Now let’s get to parsing. Remove the print statement from onJSONLoad and add this:

    
    
    void onJSONLoad(Event e) {
        XMLHttpRequest request = e.target;
        Map<String, Object> result = JSON.parse(request.responseText);
        print("JSON: " + result);
        int i = 0;
        _urls = result['images'];
        _urls.forEach((url) {
            print("url $i: $url");
            i++;
        });
    }
    

    This code really isn’t so bad. Here’s how it breaks down.

    Line 2: This is just casting the source of the event (found in e.target) to an XMLHttpRequest so we can more safely work with properties on it.

    Line 3: This one gets a little gnarly. Skip to the second half of the line. We’re getting responseText out of the XMLHttpRequest object, which gives us the raw text found in our file. And we pass that into the parse method of the JSON class. That’s all there is to parsing JSON; it’s essentially built-in! Now, to make sure we can work with the data, we need to store it in a variable. This variable is result. Because I’m advocating strong typing, it also has a type. This type is Map<String, Object>, which might be a little frightening.

    A Map is basically what we call an Object in JavaScript; it’s a collection, and stores its values by a String key.

    Because Map is a collection, it can be generified (see last step), but because there are technically two things we can specify (the key and the value), we supply two types. Somewhat oddly, you can’t use anything other than String for the key type, so I’m not sure why it needs specified. It may be possible that Dart eventually allows the use of any type as the key. But for now, it’s a String key. Because our JSON data is an Object at it’s outermost, we specify Object as the value type. We have a little flexibility, depending on the JSON structure.

    Line 4: Now that we have our JSON parsed, let’s just print it out to verify the result.

    Line 5: Initialize a counter. Note that Dart supports an int type.

    Line 6: Get the images property out of the main JSON object, which should be an Array/List, and store that in our _urls property that we set up in the last step.

    Line 7: Loop over that List, using forEach and an anonymous function. Note the syntax for anonymous functions: (url) {...}. If there is no return type, we can leave it off completely and just start with the parameter list. It feels a little odd at first, but ultimately leads to less code written, which is kind of nice.

    Line 8: Now we can print out the URL along with its index. Here we can see that Dart has String interpolation, which lets you expand variables within a String, and avoid breaking out of a String in order to include the value of a variable. The use of the dollar sign indicates that what follows is actually a variable, and Dart should interpolate it. Again, this is less code written and leads to much more readable code than String concatenation.

    Line 9: Hopefully this line of code doesn’t need explanation.

    Run the application, and…uh oh. That console doesn’t look pretty.

    Big old error

    Read on for the fix.


    Step 20: Importing More Libraries

    The fix is, thankfully, rather simple. Dart is structured into libraries, and it turns out that JSON capability isn’t part of the HTML library. We simply need to add the following line at the very top of the file:

    
    
    #import('dart:json');
    

    Run the project again, and you should get a console full of output:

    The JSON data being logged

    What I find odd is that this seems like something the JavaScript compiler catches, but it’s only a warning. The compiler recognizes that you’re using a class called JSON but doesn’t know where to find that class…that seems like an important thing to catch. The lesson here, aside from where the JSON library is, is to check the Problems panel in Dart Editor. It got kind of buried amidst the false print warnings, but it was there:

    The Problems panel telling us that we should have imported the JSON library

    Also, when you run the project, the Console panel takes over in that space, so you may have missed the warnings altogether. Just something to be on the look out for. This kind of thing will probably improve with time.


    Step 21: Writing External Classes

    As we continue to explore Dart’s capabilities, we’re going to write a new class to handle a single thumbnail image. We’ll ultimately instantiate a number of these, one for each thumbnail.

    While it’s possible to insert a second class definition into the same file, let’s see what happens when we decide to write an external class. In Dart Editor, create a new file for our project and name it MarqueeButton.dart. You’ll be presented with the following template:

    
    
    class MarqueeButton {
    
    }
    

    Again, there is no requirement that we name the class after the file, or vice versa, but it does make sense, so we’ll leave well enough alone and just start filling in the details.

    For now, let’s just get this functional by providing a simple constructor that prints a message so we can see it working. Add a constructor to the class:

    
    
    class MarqueeButton {
    
        MarqueeButton(index, image) {
            print("$index: $image");
        }
    }
    

    Nothing we haven’t been over already; this is a simple constructor that uses String interpolation.

    But to use it, we need to make sure the DartMarquee class is aware of the MarqueeButton class. At the top of DartMarqee, where there are two #import statement, add a third line to include our new class:

    
    
    #import('dart:html');
    #import('dart:json');
    #source('MarqueeButton.dart');
    

    You were expecting another #import, weren’t you? #source is a bit simpler than #import. #import is for libraries, which need to be declared as such and can link to other files. #source simply includes the targeted file. One thing to note is the #sourced files cannot, themselves, link to other files. Even #importing the built-in libraries will cause a compiler error. As such, this is a simple way to collect a few files into another script, but for more complex structures you may want to consider creating a library.

    Now that we’re linking to our new class, let’s use it. Down in onJSONLoad, we’ll replace the existing print with some instantiation:

    
    
    void onJSONLoad(Event e) {
        XMLHttpRequest request = e.target;
        Map<String, Object> result = JSON.parse(request.responseText);
        print("JSON: " + result);
        int i = 0;
        _urls = result['images'];
        _urls.forEach((url) {
            MarqueeButton btn = new MarqueeButton(i, "images/thumbs/" + url);
            i++;
        });
    }
    

    If you run the project again, you’ll get more or less the same thing, only now it’s logging from within the MarqueeButton class.


    Step 22: Fill In the “MarqueeButton” Class

    At this point, we can fill in most of the MarqueeButton class without running into much that’s new. I’ll present almost the full body of the class here, and discuss it briefly below.

    
    
    class MarqueeButton {
    
        DivElement _target;
        String _image;
        int _index;
        Function _onClick;
    
        MarqueeButton(this._index, this._image) {
            _target = new Element.tag('div');
            _target.classes = ["button"];
            DivElement border = new Element.tag('div');
            border.classes = ["border"];
            _target.nodes.add(border);
    
            _target.style.backgroundImage = 'url("'+_image+'")';
    
            _target.on.click.add(onClick);
        }
    
        void onClick(Event e) {
            _target.classes.add('selected');
            _onClick(this);
        }
    
    }
    

    We start the class off with a handful of properties, all private and typed. It may be interesting to note the Function type. We’ll get to this in a moment, but this illustrates that functions are fully-fledged objects in Dart, and can be passed around by reference rather easily.

    The constructor is mostly about building up the HTML elements for the button. We start from scratch; the only things passed in to the constructor are the index of the button and the image URL. We’ve seen this before, creating and adding new elements. Line 15, however, present something new, although I’d imagine you can figure out what it does. Elements have a style property which lets you set CSS styles rather easily. The properties available to the style object follow the CSS style names, only removing the hyphen and turning the name camel-case. Note that the value might be a String or in the case of numeric values, it can just be a number.

    The last line of the constructor adds a click event listener to the button, following the convention we saw with the XMLHttpRequest events.

    Then we have our onClick method, the listener for that click event. For style purposes we’ll add the .selected class to the element, then we call the _onClick function. This, you’ll recall, is the property we declared earlier. This is a poor man’s event dispatching, and what happens is that DartMarquee will set this property to a function of its own, so that MarqueeButton can call it. We’ll get to the setting in a moment, and we haven’t written the relevant DartMarquee code. But because functions are first-class citizens of the Dart world, it’s easy to pass that function around, and execute it somewhat arbitrarily.


    Step 23: Setters and Getters

    We’ll finish off the class with some getters and a setter. For the uninitiated, setters and getters are special functions that simply return a value (getters), or receive a value (setters). They’re common enough, and most object-oriented languages provide some method for creating implicit setters and getters, which are functions that are called as if they were properties.

    Dart has this, as well, and throws some syntactic sugar on top of it, to boot. Add this to the end of the class (before the closing curly brace, but after the onClick method):

    
    
    DivElement get target() => _target;
    int get index() => _index;
    
    Function get click() => _onClick;
    void set click(Function fn) {
        _onClick = fn;
    }
    

    You can see the sugar in the three getters. Each one follows this pattern:

    
    
    Type get name() => expression;
    

    The type is nothing new; it’s the return type of the function. The get keyword signifies that this is an implicit getter function. name() is just the name of the method. Next is the => operator, which basically says “return the value that is expressed on my right.” In the case of _target, we’re simply accessing the value stored in the _target property and returning that. In other words, a basic getter method, written with a little less code than normal.

    The expression can actually get a little more complicated than that, such as a boolean check or some simple one-liner math. If it’s going to require more than one line of code, it needs to be written as a regular getter, which is just like a regular method except for the get keyword:

    
    
    DivElement get target() {
        return _target;
    }
    

    We’re done with the MarqueeButton class now, so we’ll turn back to the DartMarquee class and start using it.


    Step 24: Displaying Thumbnails

    To display the buttons, we need to go back to the DartMarquee class and revisit the onJSONLoad method. Specifically, we need to add to that loop.

    
    
    _urls.forEach((url) {
        MarqueeButton btn = new MarqueeButton(i, "images/thumbs/" + url);
        _thumbContainer.nodes.add(btn.target);
        btn.click = onThumbClick;
        i++;
    });
    

    Another nodes.add(), this time on the _thumbContainer div and adding the target of the MarqueeButton object.

    Then we set the click property to a method we have yet to write, but will do so now:

    
    
    void onThumbClick(MarqueeButton btn) {
        print("onThumbClick");
    }
    

    We’ll work on this next, but for now we should be able to run the application, see the thumbnails, and click on them to see the log message.

    The thumb click works

    We’re almost there. We’ll work on getting that click to mean something in the next two steps.


    Step 25: Handling the Click

    The logic involved in displaying a larger image isn’t terribly complex, and at this point we’ve had a pretty extensive tour of the Dart language. I’ll start listing the method here, and then discuss what’s going on.

    First we need two properties declared. At the top of the class, with the other properties, add these lines:

    
    
    MarqueeButton _currentButton;
    ImageElement _currentImage;
    

    Then update onThumbClick:

    
    
    void onThumbClick(MarqueeButton btn) {
        if (_currentButton != null) {
            _currentButton.target.classes.remove('selected');
        }
        _currentButton = btn;
        ImageElement image = new Element.tag('img');
        image.width = 600;
        image.height = 300;
        image.src = "images/" + _urls[btn.index];
        _mainImage.nodes.add(image);
    }
    

    The first thing to notice is that we’re checking for the existence of a value in _currentButton. If it does, then we remove the .selected class. Then we set the _currentButton property to the button that was clicked, for next time.

    It’s worth nothing that Dart handles Booleans a little differently than you may be used to. Seth Ladd has a write-up on Booleans in Dart, in which we explains:

    Dart has a true boolean type named bool, with only two values: true and false (and, I suppose, null). Due to Dart’s boolean conversion rules, all values except true are converted to false. Dart’s boolean expressions return the actual boolean result, not the last encountered value.

    Therefore, when checking for the existence of a value within a variable, it’s wise to write if (variable != null) as opposed to the shorthand if (variable), as that could actually report false even through the variable has a valid value stored in it.

    Next we create an image element, set its size, the src, and then add it as a child.

    You should be able to try this out now. We won’t get a nice fade between the images, but you should now be able to use the marquee to switch images.


    Step 26: Working with the Transition

    Let’s work on that fade. Add the highlighted code below to the onThumbClick method. Note that Line 11 is a change from how it was before (it uses insertAdjacentElement), and the lines after that are new.

    
    
    void onThumbClick(MarqueeButton e) {
        if (_currentButton != null) {
            _currentButton.target.classes.remove('selected');
            print(_currentButton.target.classes);
        }
        _currentButton = e;
        ImageElement image = new Element.tag('img');
        image.width = 600;
        image.height = 300;
        image.src = "images/" + _urls[e.index];
        _mainImage.insertAdjacentElement('afterBegin', image);
    
        if (_currentImage != null) _currentImage.classes.add('fade_away');
        _currentImage = image;
        image.on.transitionEnd.add((evt) {
            ImageElement img = evt.target;
            img.remove();
        });
    }
    

    The change to line 53 introduces another way to add children elements. Element.nodes.add() is fine for appending at the end, but if we want to insert in a specific place, in this case at the beginning, then nodes doesn’t give us enough options. insertAdjacentElement does provide options, although its interface isn’t as clean as it could be. In fact, it’s lifted from the Windows Internet Explorer API. I try not to get too opinionated in a tutorial, but this is an odd decision.

    Regardless, it’s the API we have if we want to do more than append to the child elements. We want to add our new image to the beginning, so we pass in "afterBegin" to insertAdjacentElement, which does exactly that. This method is documented at MSDN if you’d like a description of the various valid arguments to that parameter.

    The rest of the code involves itself with the CSS3 transition; by adding a .fade_away class to the old image (after checking to be sure it’s not null) we set it’s opacity to 0, invoking the transition. Then _currentImage is set to the new image, to get set for the next transition.

    Finally, another event listener is added to the current image so that when the transition happens, and is finished, we can run a bit of code. All we do is get the event target and cast it as an ImageElement (not strictly necessary, but it’s something that I find useful to do in general). Then by calling remove() on the ImageElement, we remove it from the DOM. In other words, once it fade away completely, we can remove it altogether to keep our DOM tidy.

    Note also that we’re using another anonymous function as the event listener in this case. Either way would work, but since this is practically a one-line function, making it anonymous is rather convenient.

    Run the application, click on one thumb to load an image, then another thumb and watch it in silent awe.

    A still image rendition of the fade in action

    Step 27: The Final Touch

    Our Dart application is rather functional now, but you’ve probably noticed that it has one minor flaw: there is not image loaded up right away. This is a simple fix.

    In Marquee.dart, find the onJSONLoad method and add the highlighted line of code toward the bottom:

    
    
    void onJSONLoad(Event e) {
        XMLHttpRequest request = e.target;
        Map<String, Object> result = JSON.parse(request.responseText);
        print("JSON: " + result);
        int i = 0;
        _urls = result['images'];
        _urls.forEach((url) {
            MarqueeButton btn = new MarqueeButton(i, "images/thumbs/" + url);
            _thumbContainer.nodes.add(btn.target);
            btn.click = onThumbClick;
            if (i == 0) btn.onClick(null);
            i++;
        });
    }
    

    In effect, if we’re on the first iteration, take that MarqueeButton and call its onClick method. You’ll remember that as the event listener for the click event within the MarqueeButton. We’ll just call it directly, to sort of simulate a click on the first button, so as to trigger the setting of the styles and putting content in the right place. Since the method expects an event parameter, but isn’t really used, we can supply null to the method call to satisfy the compiler.

    Run it once more, and you should now have the first image selected and ready in the main area.


    Step 28: Where To Go From Here

    We’ve just scratched the surface of Dart, but the cool thing is that if you know JavaScript, you already know Dart in one sense. You’re already familiar with what you can do with an HTML page, and generally how to do it. Dart for the web doesn’t really add any capabilities or fancy frameworks, it’s just another language in the same problem domain. If you want to learn more, you can do worse than to simply write applications in Dart. Maybe dig out a smallish/simple bit of JavaScript you’ve done and port it over to Dart.

    If you like scouring the web for more resources, Google is certainly your friend, although the name “Dart” can lead to many unrelated hits that are about the game of darts, rather than the language. Many times I’ve had to specify “dart language” in my searches or get a little more specific than just “dart events”. There is quite a bit of information floating around.

    First, the official Dart website is at dartlang.org. You’ll find a small tutorial there that goes into some of the unique language features, along with the nifty Dartboard widget that lets your write and execute dart code in the browser you can even use the widget on your own site).

    If you think you know what you need to do, just don’t know the right method name or class, the API documentation is good place to start, at api.dartlang.org. Sometimes the docs are a little bare or even wrong, but you should probably begin any quest for an answer here.

    I’ve already mentioned the mailing list, located at groups.google.com/a/dartlang.org/group/misc/topics. It’s very active and I had a few questions answered in a matter of minutes there. The Google engineers are very involved on the list, as well.

    The Dart site also has a pretty nice JavaScript-to-Dart comparison chart, located at synonym.dartlang.org, which takes common JavaScript code snippets and shows the equivalent Dart code right beside it.

    Moving away from Google’s own resources, there are a few Dart-centric blogs that kept coming up in searches. One of the most prolific is Japh(r) by Chris Strom, at japhr.blogspot.com/search/label/dartlang, who is also writing a book on Dart.

    The Dartosphere (dartosphere.org aggregates several different blogs

  2. Dru Kepple says:
    June 29, 2012 at 9:33 am

    You’ve undoubtedly seen the “Cover Flow” view in effect. It’s all over the place on Apple’s stuff. And you’ve also probably seen a number of implementations of Cover Flow in Flash. In this tutorial, you’ll get one more. We’ll leverage the built-in 3D capabilities of Flash Player 10 (that’s pre-Stage3D) and build our own XML-driven version of Cover Flow.

    Note: This tutorial was originally published in April 2011 – before Stage3D was released – as a freebie for our newsletter subscribers.

    Final Result Preview

    Check out the demo to see what we’re working towards.



    Click to view the demo.


    Step 1: Create an ActionScript 3 Flash File

    The very first thing to do is create a Flash file in which we’ll work. Open up Flash CS4 or CS5 and choose File > New, and select Flash File (ActionScript 3.0), and press OK. Save this file into a folder that will be dedicated to this project.

    Flash version settings

    I will be setting the stage size to 600 x 400. Feel free to use whatever size you want, but I would recommend 600 x 400 as a minimum, considering that the Coverflow effect is best when it has ample room for displaying itself. Also, choose a fairly high frame rate, such as the default 24. This will make for smoother animations.

    Stage size and frame rate

    Save this file as CoverFlow.fla in a folder you can dedicate to this project.


    Step 2: Create the Test Document Class

    Our goal will be to create a reusable CoverFlow class, but to develop it we need a place for it to live. We’ll use the Flash file we just created to act as a testing ground for the CoverFlow class as we develop it, and so we’ll need a document class to go with the Flash file. This class will function to provide a place to instantiate and test the CoverFlow class. It will, as such, provide an example for how to use the CoverFlow class once it is complete.

    In the text editor of your choice, create a new file and save it as CoverFlowTest.as in the same folder as your Flash file.

    Your project folder

    Stub out a simple class:

    
    
    package {
    
        import flash.display.*;
        import flash.events.*;
        import flash.net.*;
        import flash.utils.*;
    
        public class CoverFlowTest extends Sprite {
    
            public function CoverFlowTest() {
                trace("CoverFlowTest");
            }
    
        }
    
    }
    

    This doesn’t do much, but will trace out a message if it’s hooked up correctly, which we’ll do next.


    Step 3: Wire the Document Class to the FLA

    In the Flash file, click somewhere on the empty stage, and open the Properties panel (Command/Control-F3, or Window > Properties). In the Class field, type in CoverFlowTest to assign the document class.

    Test your movie now, and you should see the aforementioned trace.

    The Output Panel when running this FLA

    Step 4: Create the CoverFlow Class

    Next we’ll create the file for the CoverFlow class. This will live in a package, so first create the folder structure. Starting in the project folder (at the same level as your FLA), create a folder called com. Inside of that, create another folder called tutsplus. Inside of this, create one more folder called coverflow.

    Now create another text file called CoverFlow.as inside of the coverflow folder.

    The project folder with the CoverFlow class

    Add the following boilerplate:

    
    
    package com.tutsplus.coverflow {
    
        import flash.display.*;
        import flash.geom.*;
        import flash.events.*;
        import flash.net.*;
        import flash.text.*;
        import flash.utils.*;
    
        public class CoverFlow extends Sprite {
    
            public function CoverFlow() {
                trace("CoverFlow");
            }
    
        }
    
    }
    

    This is very similar to the document class, only we’re anticipating the need for more classes, so there are more import statements. This class will also extend Sprite, so that we can treat CoverFlow as a display object.


    Step 5: Create a CoverFlow Instance

    Now to make sure we can create and work with CoverFlow in our document class. Back in CoverFlowTest.as, import the CoverFlow class. After the other imports:

    
    
    import com.tutsplus.coverflow.CoverFlow;
    

    Now we need a property to store the CoverFlow instance. Before the constructor:

    
    
    private var coverFlow:CoverFlow;
    

    And now to create the instance and add it to the display list. In the constructor, remove the trace and replace it with:

    
    
    coverFlow = new CoverFlow();
    addChild(coverFlow);
    

    Test it now, and you should now see “CoverFlow” trace in the Output panel. If so, all is good. We can now start building CoverFlow.

    Here is the whole document class code, for reference:

    
    
    package {
    
        import flash.display.*;
        import flash.events.*;
        import flash.net.*;
        import flash.utils.*;
    
        import com.tutsplus.coverflow.CoverFlow;
    
        public class CoverFlowTest extends Sprite {
    
            private var coverFlow:CoverFlow;
    
            public function CoverFlowTest() {
                coverFlow = new CoverFlow();
                addChild(coverFlow);
            }
    
        }
    
    }
    

    Step 6: Create a Cover Class

    A Cover class will be a single item in the entire “flow.” We’ll start by perfecting the class on a single item, then worry about loading data and building the “flow” after that is taken care of.

    Again, in your text editor, create a new class file. Save it as Cover.as in the same com/tutsplus/coverflow folder as the CoverFlow class (as opposed to the CoverFlowTest class…yes, we have some potentially confusing names. I’ll try to help you keep things straight throughout this tutorial).

    The project folder structure

    Add the following boilerplate (see a pattern yet?):

    
    
    package com.tutsplus.coverflow {
    
        import flash.display.*;
        import flash.geom.*;
        import flash.events.*;
        import flash.net.*;
        import flash.utils.*;
    
        public class Cover extends Sprite {
    
            public function Cover() {
                trace("Cover");
            }
    
        }
    
    }
    

    This is actually identical to the CoverFlow boilerplate, except for the usage of the word “Cover” instead of “CoverFlow.” These will end up being quite different, don’t worry, I’m just making sure we have files in place before going too far down the coding rabbit hole.


    Step 7: Create a Cover Instance

    So, we’ll have the CoverFlow object create and use a Cover object. In the end, CoverFlow will be responsible for creating and managing several Cover objects, but for now, as we build the Cover class, we’ll just have it create and display a single Cover object.

    In CoverFlow, instead of tracing “CoverFlow,” let’s have it do this object creation.

    
    
    public function CoverFlow() {
        var test:Cover = new Cover();
        addChild(test);
    }
    

    If you test it now, you should see “Cover” being traced (remember, that’s a single Cover object, not the previous test traces we’ve been using).

    Tracing "Cover"

    However, let’s go a step further and try to display something onscreen. In the Cover file, remove the trace and add this:

    
    
    public function Cover() {
        graphics.beginFill(0xff0000);
        graphics.drawRect(0, 0, 200, 200);
    }
    

    Now, instead of tracing to the Output panel, you should see a red square appear in the upper left corner of your movie. If that happens, we’re pretty much set to continue working. What this means is that not only is the code executing all the way down to the individual Cover object, but we’ve successfully added elements to the stage so that we can create visual objects.

    Actually seeing something in the movie

    Step 8: Put Covers in a Container

    We just added our Cover object directly to the CoverFlow’s display list. For reasons that may not be clear at the moment, we’re going to eventually need them in an extra container; that is, CoverFlow will contain a Sprite, which will contain all Cover instances. As we progress through this tutorial, we’ll add other, non-Cover display objects, and it will be very convenient to make sure all Covers are easily managed.

    First, in CoverFlow, declare a Sprite property that will reference our container.

    
    
    private var _coversContainer:Sprite;
    

    And in the constructor, create that Sprite and add it to the display list. Also, instead of adding the test Cover object to the CoverFlow’s display list, add it to the _coversContainer Sprite:

    
    
    public function CoverFlow() {
        _coversContainer = new Sprite();
        addChild(_coversContainer);
        var test:Cover = new Cover();
        _coversContainer.addChild(test);
    }
    

    If you test now, you should see exactly the same thing as before, which is good. We don’t want it to look any different, but we want a different functionality under the hood.


    Step 9: Set the CoverFlow Size

    There are a few things that we should take care of now. The size of the container that holds the CoverFlow display is one of them, as the the width and height will be used elsewhere. This will be as simple as a few properties and matching setters and getters.

    First, in CoverFlow.as, add two properties at the beginning of the class:

    
    
    private var _width:Number;
    private var _height:Number;
    

    And after the constructor, add the following setters and getters:

    
    
    override public function set width(num:Number):void {
        _width = num;
    }
    override public function get width():Number {
        return _width;
    }
    override public function set height(num:Number):void {
        _height = num;
    }
    override public function get height():Number {
        return _height;
    }
    

    Since CoverFlow is a subclass of Sprite, there already are width and height setters and getters. So we need to be sure to override them. We don’t want the default behavior of stretching, so we’ll want to control that on our own. We’ll come back to these setters in a few steps.

    However, having a size for the CoverFlow object is important enough to require these parameters in the constructor. The width and height determine much of the final layout, so we’ll add some parameters to the constructor and then immediately set our properties with them:

    
    
    public function CoverFlow(w:Number, h:Number) {
        _width = w;
        _height = h;
    
        _coversContainer = new Sprite();
        addChild(_coversContainer);
        var test:Cover = new Cover();
        _coversContainer.addChild(test);
    }
    

    And of course we need to supply some arguments to this from CoverFlowTest. In that file, update the line that creates a new CoverFlow to this:

    
    
    coverFlow = new CoverFlow(stage.stageWidth, stage.stageHeight);
    

    There isn’t much to test right now, but if you like you can publish the movie and see if any compiler errors pop up. If there are any errors, take care of them now. You’ll know that the errors somehow relate to the code you just typed, so start there.


    Step 10: Set the Background Color

    Another property that will get used later will be the background color of the entire “flow.” Apple makes theirs black, but there’s no reason to stick with that, as it will be rather simple to change it. To make it happen, though, we’ll need a Shape object that sits at the bottom of the CoverFlow object’s display stack, and we’ll need to programmatically draw a rectangle of the chosen color into that Shape.

    First, add two properties to CoverFlow, one to hold the Shape instance and one to store the background color:

    
    
    private var _backgroundColor:uint = 0;
    private var _background:Shape;
    

    Notice that we’re giving _backgroundColor a default value, so that if it’s never set by the user of this class, we’ll have a black background anyway. The number 0 is the color code for black.

    Next, write in the setter and getter for backgroundColor (we don’t need the Shape to be accessible outside of this class, just the color):

    
    
    public function set backgroundColor(val:uint):void {
        _backgroundColor = val;
        drawBackground();
    }
    public function get backgroundColor():uint {
        return _backgroundColor;
    }
    

    You’ll notice that we’re calling an as-of-yet nonexistent method called drawBackground. This will do what it says on the label. Let’s write it now:

    
    
    private function drawBackground():void {
        _background.graphics.clear();
        _background.graphics.beginFill(_backgroundColor, 1);
        _background.graphics.drawRect(0, 0, _width, _height);
    }
    

    This just clears out any previous graphics drawing in the background shape, sets the fill color to the current value of the property, and then draws a rectangle.

    Finally, we need to set up the Shape initially. In the constructor, add this at the end:

    
    
    _background = new Shape();
    addChildAt(_background, 0);
    drawBackground();
    

    And go ahead and test it! You should see a black background behind our red square.

    The published SWF, with a black background

    If you like, you can resize the player window, and you’ll see that we do indeed have a black rectangle sitting on top of the white base of the movie.

    For reference, here is the complete CoverFlow class at this point. Changes made in this step are highlighted.

    
    
    package com.tutsplus.coverflow {
    
        import flash.display.*;
        import flash.geom.*;
        import flash.events.*;
        import flash.net.*;
        import flash.text.*;
        import flash.utils.*;
    
        public class CoverFlow extends Sprite {
    
            private var _coversContainer:Sprite;
            private var _width:Number;
            private var _height:Number;
            private var _backgroundColor:uint = 0;
            private var _background:Shape;
    
            public function CoverFlow(w:Number, h:Number) {
                _width = w;
                _height = h;
    
                _coversContainer = new Sprite();
                addChild(_coversContainer);
                var test:Cover = new Cover();
                _coversContainer.addChild(test);
    
                _background = new Shape();
                addChildAt(_background, 0);
                drawBackground();
            }
    
            override public function set width(num:Number):void {
                _width = num;
            }
            override public function get width():Number {
                return _width;
            }
            override public function set height(num:Number):void {
                _height = num;
            }
            override public function get height():Number {
                return _height;
            }
    
            public function set backgroundColor(val:uint):void {
                _backgroundColor = val;
                drawBackground();
            }
            public function get backgroundColor():uint {
                return _backgroundColor;
            }
    
            private function drawBackground():void {
                _background.graphics.clear();
                _background.graphics.beginFill(_backgroundColor, 1);
                _background.graphics.drawRect(0, 0, _width, _height);
            }
    
        }
    
    }
    

    Step 11: Create the Mask

    We may have created a background shape that responds to the size of the CoverFlow, but anything else we add to the object – like individual Covers – may not respect the intended size. What we need is a mask for the entire CoverFlow display object that gets set to the same size.

    We could use a regular ol’ mask for this task, but because we are expecting a rectangular mask, we have an even easier approach. The scrollRect property of DisplayObjects provides functionality similar to that of masks, although there are differences. One advantage we have with scrollRect is a performance optimization. I don’t know specifics, but utilizing scrollRect tells Flash to render only the pixels contained within the rectangle, as opposed to regular masks, which still renders all pixels involved in the masked content.

    Setting it up is as simple as this, in the CoverFlow constructor:

    
    
    public function CoverFlow(w:Number, h:Number) {
        // ...
    
        drawBackground();
    
        scrollRect = new Rectangle(0, 0, _width, _height);
    
        // ...
    

    There’s not much to test right now, but you can compile to make sure you didn’t make any typos.


    Step 12: Adjust the Width and Height

    Now, we need to implement our own sizing logic. In the width and height setters of CoverFlow, add these lines:

    
    
    override public function set width(num:Number):void {
        _width = num;
        _background.width = _width;
        scrollRect = new Rectangle(0, 0, _width, _height);
    }
    override public function get width():Number {
        return _width;
    }
    override public function set height(num:Number):void {
        _height = num;
        _background.height = _height;
        scrollRect = new Rectangle(0, 0, _width, _height);
    }
    override public function get height():Number {
        return _height;
    }
    

    We can test this to a degree by adding a size change to the coverFlow object in CoverFlowTest:

    
    
    public function CoverFlowTest() {
        coverFlow = new CoverFlow(stage.stageWidth, stage.stageHeight);
        addChild(coverFlow);
        coverFlow.width = stage.stageWidth / 2;
        coverFlow.height = stage.stageHeight / 3;
    }
    

    You should see what you’ve been seeing, only masked.

    The size-adjusted CoverFlow. The scrollRect is in effect.

    It’s hard to tell that the scrollRect is working at the moment, but at least you have expected results for now. Remove the two lines you just added; we’ll want a full-size CoverFlow in order to continue development.


    Step 13: Add Properties to Cover

    We’ll come back to CoverFlow.as in the near future, but for now we’re going to focus on getting an individual Cover instance up to speed.
    Let’s think about what the Cover will need to do. It will need to load and display an image. It will need to display a caption. It will need to be positioned. It will also need to display a reflection beneath the image. When we get to XML data, we’ll have each Cover store the XML node related to that instance, so that we can store extra related information with the associated Cover. And it will need to dispatch a few events, for load progress, load complete, select (for when the cover comes into the center position), and click. The Cover could certainly do more, but for now, these capabilities pretty closely match what iTunes implementation of Cover Flow does, and will help keep our tutorial to a reasonable scope. For the code, this feature set means:

    Load Image We’ll need a Loader to load the image, along with specifying the URL of the image to load.

    Display Image We’ll need to add the Loader to the display list.

    Display Caption We’ll need to be able to set the caption, put it into a TextField, and display the TextField. Note that this opens up the can of worms that is text styling, and the question of how much control of the style to open up outside of the class. For our purposes, we’ll stick with a standard styling. If you’d like an implementation that allows user-definable styles, that’s an exercise for later.

    However, note that in the reference implementation of Cover Flow, the caption is not attached to the cover image, it’s a fixed area in the center bottom of the whole display area. What we’ll need is not a TextField for each Cover object, but a single TextField for the entire CoverFlow system. All the Cover object needs to do is store its caption. We’ll have CoverFlow then pull that information out of each Cover as it’s focused and handle its display. So all we really need right now is a storage mechanism for a caption.

    Display Image Reflection This will require a Bitmap object and some BitmapData fanciness, but it’s not hard. However, it does require that we know the general background color of the entire Cover Flow display, because the easiest way to handle the transparency of the reflections is to not actually be transparent (if they were, we’d have overlaying reflections show through each other). So, we’ll require that the background color be passed in to our constructor from CoverFlow.

    Also, we’ll want to hang onto the Bitmap, but the BitmapData can be a one-time object used to create the reflection in the first place.

    Positioning Since we’re subclassing Sprite, anything we display within that Sprite is automatically positioned as a unit by the positional properties of Sprite. We won’t have to do anything to gain this functionality, other than make sure that we add the appropriate display objects as children of the Cover instance itself.

    XML Data We’ll just need a property to store an arbitrary XML node and a way to get that back out of the object.

    Events Again, since we’re a subclass of Sprite, we also automatically have the capability to dispatch events. In fact, the click event is already defined by the Sprite. Load progress and complete will really just be forwarded events from the LoaderInfo of the Loader we use to load the image. And select will actually be handled by CoverFlow, since it knows how to manage a collection of Covers. So, we’re done with this one, too!

    Let’s add the properties we need, along with setters and getters where appropriate. We’ll follow the convention of making actual properties private, and providing public access through setters and getters.

    In Cover.as, add some properties to the class file. I like to keep them grouped together, at the very top of the class definition:

    
    
    private var _src:String;
    private var _caption:String;
    private var _data:XML;
    private var _loader:Loader;
    private var _reflection:Bitmap;
    private var _backgroundColor:uint;
    

    Write the setters and getters:

    
    
    public function get caption():String {
        return _caption;
    }
    
    public function get data():XML {
        return _data;
    }
    
    public function set backgroundColor(num:Number):void {
        _backgroundColor = num;
    }
    public function get backgroundColor():Number {
        return _backgroundColor;
    }
    

    Why only have these? Well, other objects won’t really need access to the Bitmap or the Loader, and for the caption and data, we’ll operate on the assumption that once those values are set, they won’t need to change. We’ll deal with that in the next step.

    Go ahead and test this out. There won’t be any changes to take note of; you should still just see a red square. But by testing the movie we run things through the compiler, which helps us find errors should any be introduced. If all went well, the movie will run and you’ll see the red square. Here is the complete Cover class as of now:

    
    
    package com.tutsplus.coverflow {
    
        import flash.display.*;
        import flash.geom.*;
        import flash.events.*;
        import flash.net.*;
        import flash.utils.*;
    
        public class Cover extends Sprite {
    
            private var _src:String;
            private var _caption:String;
            private var _data:XML;
            private var _loader:Loader;
            private var _reflection:Bitmap;
            private var _backgroundColor:uint;
    
            public function Cover() {
                graphics.beginFill(0xff0000);
                graphics.drawRect(0, 0, 200, 200);
            }
    
            public function get caption():String {
                return _caption;
            }
    
            public function get data():XML {
                return _data;
            }
    
            public function set backgroundColor(num:Number):void {
                _backgroundColor = num;
            }
            public function get backgroundColor():Number {
                return _backgroundColor;
            }
    
        }
    
    }
    

    Step 14: Set the Properties

    As mentioned, we’ll set the properties like caption, data, and background color through the constructor. Modify the constructor of Cover.as so it takes those three values, and then transfers those values to the appropriate properties. Changes to the constructor below are highlighted:

    public function Cover(caption:String, data:XML, backgroundColor:Number) {
        _caption = caption;
        _data = data;
        _backgroundColor = backgroundColor;
    
        graphics.beginFill(0xff0000);
        graphics.drawRect(0, 0, 200, 200);
    }
    

    Now, back in CoverFlow.as, we need to supply values when we create our test Cover or else we’ll get errors. In the constructor:

    
    
    public function CoverFlow(w:Number, h:Number) {
        _width = w;
        _height = h;
    
        _coversContainer = new Sprite();
        addChild(_coversContainer);
        var test:Cover = new Cover("I am a caption", <data />, _backgroundColor);
        _coversContainer.addChild(test);
    
        _background = new Shape();
        addChildAt(_background, 0);
        drawBackground();
    
        scrollRect = new Rectangle(0, 0, _width, _height);
    }
    

    We’re obviously using dummy data right now, but this should safely compile. Again, we won’t see any changes, but test the movie to make sure you haven’t introduced errors. However, we can write a quick test of what we wrote by tracing the values of the getters. Still in the CoverFlow constructor:

    
    
    public function CoverFlow(w:Number, h:Number) {
        _width = w;
        _height = h;
    
        _coversContainer = new Sprite();
        addChild(_coversContainer);
        var test:Cover = new Cover("I am a caption", <data />, _backgroundColor);
        _coversContainer.addChild(test);
    
        _background = new Shape();
        addChildAt(_background, 0);
        drawBackground();
    
        scrollRect = new Rectangle(0, 0, _width, _height);
    
        trace(test.caption);
        trace(test.data.toXMLString());
        trace(test.backgroundColor);
    }
    

    You should see the following in your Output panel:

    The results of tracing our new getters

    This verifies that we are properly setting and getting at least the caption, data XML, and backgroundColor properties.


    Step 15: Load an Image

    For this step, we’ll need an image to load. There are several in the download package for this tutorial, already cropped and sized as squares. Let’s just pick one to load. I’ll use “best.jpg.”

    First, put the images folder in the same project folder you’ve been using. It should be at the same location as your CoverFlowTest.swf. Either drop the images folder from the download here, or create your own images folder here and put the images you want to load into that folder.

    The current project folder structure

    Next, in the constructor of Cover.as, remove the lines that draw the red square.

    
    
    public function Cover(caption:String, data:XML, backgroundColor:Number) {
        _caption = caption;
        _data = data;
        _backgroundColor = backgroundColor;
    
        //graphics.beginFill(0xff0000);
        //graphics.drawRect(0, 0, 200, 200);
    }
    

    Now, create a public method called load. This will receive a string URL as a parameter, store it in the _src property, and then load the image from that URL.

    
    
    public function load(src:String):void {
        _src = src;
        _loader = new Loader();
        _loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onLoadProgress);
        _loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadComplete);
        _loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onLoadError);
        addChild(_loader);
        _loader.load(new URLRequest(_src));
    }
    

    This is standard Loader stuff. It will ultimately be up to another object (such as CoverFlow) to feed this value to the Cover.

    We’ve added three event listeners, all standard fare for loading. Let’s write out some stub listener functions so we can test. Add this code to you class. These are new methods, not code within another method:

    
    
    private function onLoadProgress(e:ProgressEvent):void {
        trace("progress: " + e.bytesLoaded + " of " + e.bytesTotal);
    }
    
    private function onLoadComplete(e:Event):void {
        trace("loaded");
    }
    
    private function onLoadError(e:IOErrorEvent):void {
        trace("error: " + e.text)
    }
    

    We’ll end up doing something more useful with these, but for now we’ll fire off a trace just to make sure the functions get called in response to events. For reference, the entire class should look something like this (additions from this step are highlighted):

    
    
    package com.tutsplus.coverflow {
    
        import flash.display.*;
        import flash.geom.*;
        import flash.events.*;
        import flash.net.*;
        import flash.utils.*;
    
        public class Cover extends Sprite {
    
            private var _src:String;
            private var _caption:String;
            private var _data:XML;
            private var _loader:Loader;
            private var _reflection:Bitmap;
            private var _backgroundColor:uint;
    
            public function Cover(caption:String, data:XML, backgroundColor:Number) {
                _caption = caption;
                _data = data;
                _backgroundColor = backgroundColor;
            }
    
            public function get caption():String {
                return _caption;
            }
    
            public function get data():XML {
                return _data;
            }
    
            public function set backgroundColor(num:Number):void {
                _backgroundColor = num;
            }
            public function get backgroundColor():Number {
                return _backgroundColor;
            }
    
            public function load(src:String):void {
                _src = src;
                _loader = new Loader();
                _loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onLoadProgress);
                _loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadComplete);
                _loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onLoadError);
                addChild(_loader);
                _loader.load(new URLRequest(_src));
            }
    
            private function onLoadProgress(e:ProgressEvent):void {
                trace("progress: " + e.bytesLoaded + " of " + e.bytesTotal);
            }
    
            private function onLoadComplete(e:Event):void {
                trace("loaded");
            }
    
            private function onLoadError(e:IOErrorEvent):void {
                trace("error: " + e.text)
            }
    
        }
    
    }
    

    Now, to test this, we need to hop back over to CoverFlow.as and at some point in the constructor, call the load method and pass in a valid path to an image:

    
    
    public function CoverFlow(w:Number, h:Number) {
        _width = w;
        _height = h;
    
        _coversContainer = new Sprite();
        addChild(_coversContainer);
        var test:Cover = new Cover("I am a caption", <data />, _backgroundColor);
        _coversContainer.addChild(test);
    
        _background = new Shape();
        addChildAt(_background, 0);
        drawBackground();
    
        scrollRect = new Rectangle(0, 0, _width, _height);
    
        trace(test.caption);
        trace(test.data.toXMLString());
        trace(test.backgroundColor);
    
        test.load("images/best.jpg");
    }
    

    If you test the movie now, not only should you see an image show up in place of the red square:

    A Cover loading an image

    …but you should also see some traces in the Output panel confirming that the progress and complete events were firing (your actual progress events may vary):

    Events tracing to the Output panel

    Obviously, the load completed because the image appeared, but it’s good to make sure we hooked up the event correctly. If you want to test the error event, just change the path value passed into the Cover constructor to something that won’t work, and you should see a different trace.


    Step 16: Center the Image

    Movement within the “flow” has two requirements. First, items need to rotate about a vertical axis that is centered horizontally on the image. Second, the bottom of the image needs to be aligned to a “ground” so that images of varying heights are all “sitting” on the same plane.

    To make the vertical rotation easy, we can center the image horizontally in relation to the containing Sprite. Similarly, to make the bottom alignment easy, we can position the image so that its bottom edge is at the x-axis of the containing Sprite. To pull this off, we need know the size of the image that we just loaded. In order to determine that, we need to make sure the image is loaded before attempting to work with its size. So, all of our centering code needs to be in the complete handler.

    Add this to the onLoadComplete method of Cover.as (and remove the trace that is currently there):

    
    
    private function onLoadComplete(e:Event):void {
        _loader.x = -Math.round(_loader.width / 2);
        _loader.y = -_loader.height;
    }
    

    If you test this now, you probably won’t see an image at all, because the Cover sprite is being positioned at (0, 0) on the stage, but all of its visible content is above the registration point of the Cover sprite. So, before testing, add a few lines of code to position the Cover object in CoverFlow.as, just after creating the test Cover object:

    
    
    test.x = _width / 2;
    test.y = _height / 2;
    

    Test it now, and you should see the image somewhere in the middle of the stage.
    If you like, you can go back and re-test the setting of the width and height of the CoverFlow (see Step 12) to see if the scrollRect works to mask out the contents of CoverFlow. You should see a partial Cover object.


    Step 17: Reflect the Image

    Now we get into some more challenging stuff. We’re going to take the image we just loaded and create a copy of it that is flipped vertically (that is, it was rotated around the bottom edge). We’ll use BitmapData to clone the appearance of the image. Like before, because we need the actual image before we can do this, we’ll initiate the drawing of the reflection in the onLoadComplete method:

    
    
    private function onLoadComplete(e:Event):void {
        _loader.x = -Math.round(_loader.width / 2);
        _loader.y = -_loader.height;
        drawReflection();
    }
    
    private function drawReflection():void {
        var clone:BitmapData = new BitmapData(_loader.width, _loader.height, false, 0x000000);
        var flip:Matrix = new Matrix();
        flip.scale(1, -1);
        flip.translate(0, _loader.height);
        clone.draw(_loader, flip);
        _reflection = new Bitmap(clone);
        addChild(_reflection);
        _reflection.x = _loader.x;
    }
    

    That’s a lot of code that may be unfamiliar to you, depending on how much you’ve worked with BitmapData.

    BitmapData, first of all, is a class that lets you work with the pixels of a bitmap. The first line creates one, specifying a width and height, transparency, and a default fill color.

    The next thing we’ll do is usually a straight forward operation, where we draw the graphics of another display object into a rendered bitmap representation. However, we don’t want a straight clone, we want to flip the image. We can do that by passing in a Matrix object into the second parameter of the draw method. A Matrix object represents a geometric, two-dimensional transformation, including scale, rotation, and translation (or position). So, before we do the draw operation, we create a new Matrix object. Then we use the scale method on the Matrix to flip it vertically (the two arguments are horizontal scale and vertical scale; 1 being no change and -1 being an inversion). Next, because the scale operation performs similarly to how display objects work, we actually scaled the image so it’s “pointing” the other direction. So we need to reposition it to get it back onto the bitmap canvas. The translate method does this, repositioning the scaled image by the image’s height.

    With the flipped image represented in a BitmapData object, we need to actually display it in a Bitmap object. BitmapData is a pure data representation and is not, itself, displayable. However, the Bitmap object is displayable, and handily enough takes a BitmapData object as the parameter to its constructor, so we create a Bitmap, add it to the display list, and finally position it horizontally to it’s aligned with the original image.

    Try this out, and you should be seeing double.

    The image showing off a reflection

    The BitmapData operations can be confusing, so if they’re not clear to you at this point I encourage you to pursue further information on it. BitmapData opens up some very interesting possibilities, so it’s worth learning more about.


    Step 18: Fade the Reflection

    Now, to make the reflection fade, we need to fade to that background color, and keep the reflection opaque. It will give the appearance of being transparent, but if we keep it opaque, one reflection can be layered on top of another without the lower one showing through. Go ahead and look at the preview again if you need to visualize this:

    Faded reflections

    We’ll add a bunch of drawing code to drawReflection (in Cover.as). Here’s the whole method, with the changes highlighted:

    
    
    private function drawReflection():void {
        var clone:BitmapData = new BitmapData(_loader.width, _loader.height, false, 0x000000);
        var flip:Matrix = new Matrix();
        flip.scale(1, -1);
        flip.translate(0, _loader.height);
        clone.draw(_loader, flip);
        _reflection = new Bitmap(clone);
        addChild(_reflection);
        _reflection.x = _loader.x;
    
        var gradient:Shape = new Shape();
        var gradientMatrix:Matrix = new Matrix();
        gradientMatrix.createGradientBox(_reflection.width, _reflection.height, Math.PI / 2);
        var gradientFill:GraphicsGradientFill = new GraphicsGradientFill(GradientType.LINEAR, [_backgroundColor, _backgroundColor], [.5, 1], [0, 255], gradientMatrix);
        var gradientRect:GraphicsPath = new GraphicsPath();
        gradientRect.moveTo(0, 0);
        gradientRect.lineTo(_reflection.width, 0);
        gradientRect.lineTo(_reflection.width, _reflection.height);
        gradientRect.lineTo(0, _reflection.height);
        gradientRect.lineTo(0, 0);
        var graphicsData:Vector.<IGraphicsData> = new Vector.<IGraphicsData>();
        graphicsData.push(gradientFill, gradientRect);
        gradient.graphics.drawGraphicsData(graphicsData);
    
        _reflection.bitmapData.draw(gradient);
    }
    

    Yup, that’s quite a lot of code to chew on. In summary, it creates another Shape object, in which we draw a linear gradient. The gradient is set to be same color as the main background, with alpha changes going from half transparent to fully opaque, top to bottom. This gradient then gets merged into the BitmapData already containing the flipped reflection of the image, so that the final effect is a reflection that fades out to the background color.

    Go ahead and try this out, you should feel good about obtaining these results:

    A nicely faded reflection

    However, if you test this further and try setting up the coverFlow instance in CoverFlowTest with a background color other than black, you’ll see some unpredictable results:

    A not-so-nicely faded reflection

    We’ll address this next.


    Step 19: Keep Track of the Cover Instances

    We are currently using the CoverFlow instance as a place to test a single Cover instance. And even though we’ll eventually get rid of that test instance, we now need to store it in an official list of all instances. We’ll create an Array of Cover instances, and every one that gets creates will get stashed in the Array. Actually, since we’re targeting Flash 10, we can make it a Vector, which will offer a small performance increase.

    First, in CoverFlow.as, declare the Vector, alongside the rest of the properties:

    
    
    private var _covers:Vector.<Cover>;
    

    Then, instantiate that Vector almost immediately. In the constructor, put this line right after you set the _width and _height:

    
    
    _covers = new Vector.<Cover>();
    

    And after the “test” Cover object has been created (still in the constructor), add it to the Vector:

    
    
    _covers.push(test);
    

    The top part of your CoverFlow class should look like this (additions highlighted):

    
    
    public class CoverFlow extends Sprite {
    
        private var _coversContainer:Sprite;
        private var _width:Number;
        private var _height:Number;
        private var _backgroundColor:uint = 0;
        private var _background:Shape;
        private var _covers:Vector.<Cover>;
    
        public function CoverFlow(w:Number, h:Number) {
            _width = w;
            _height = h;
            _covers = new Vector.<Cover>();
    
            _coversContainer = new Sprite();
            addChild(_coversContainer);
            var test:Cover = new Cover("I am a caption", <data />, _backgroundColor);
            _coversContainer.addChild(test);
            test.x = _width / 2;
            test.y = _height / 2;
            _covers.push(test);
    
            trace(test.caption);
            trace(test.data.toXMLString());
            trace(test.backgroundColor);
    
            test.load("images/best.jpg");
    
            _background = new Shape();
            addChildAt(_background, 0);
            drawBackground();
        }
    // ...
    

    Step 20: Set the Background Color of the Covers

    Now, in the backgroundColor setter, we not only need to draw the main background, but we need to inform all of our Cover instances that the background color has changed. The entire method will look like this (new code is highlighted):

    
    
    public function set backgroundColor(val:uint):void {
        _backgroundColor = val;
        drawBackground();
        for each (var cover:Cover in _covers) {
            cover.backgroundColor = val;
        }
    }
    

    Then, in the Cover class, update its backgroundColor setter so that it redraws the reflection:

    
    
    public function set backgroundColor(num:Number):void {
        _backgroundColor = num;
        drawReflection();
    }
    

    Lastly, we need to do some error checking. In the test case that we have set up right now, the backgroundColor gets set before the image loads (and this is a reasonable action; typically you’ll set up the CoverFlow and give it a backgroundColor right away, as the images load). Because of this, the Loader has a width and height of 0, which makes the first line of drawReflection produce an Error. If you set the backgroundColor of the CoverFlow object right now and test the movie, you’ll see this:

    Runtime error from trying to set the background color too soon

    This is easy enough to handle. If the Loader has a width and/or height of 0, we can safely assume that the loader hasn’t finished loading yet. So, the very first lines of drawReflection can check for this:

    
    
    private function drawReflection():void {
        if (_loader.width == 0 || _loader.height == 0) {
            return;
        }
        var clone:BitmapData = new BitmapData(_loader.width, _loader.height, false, 0x000000);
        var flip:Matrix = new Matrix();
        // ...
    

    Simply exit the method, and everything will be fine. Don’t worry, we also call drawReflection from onLoadComplete, so at that point, the _backgroundColor property will be set with the correct value, and the Loader will be loaded, so we can draw. In the event that we want to change the background color after the images have loaded, this still works, because the Loader will have non-zero dimensions, and drawReflection will run from the backgroundColor setter.

    Try it out: go back to CoverFlowTest and set the CoverFlow instance’s background color:

    
    
    public function CoverFlowTest() {
        coverFlow = new CoverFlow(stage.stageWidth, stage.stageHeight);
        addChild(coverFlow);
        coverFlow.backgroundColor = 0xC14216;
    }
    

    And you’ll have a glorious orange thing going on:

    Orange background and orange reflections

    Feel free to remove that line after you’re satisfied that the background color and the reflection works (what, you don’t like orange?).


    Step 21: Write an XML Data Source

    We’ll move on to providing a real set of data to drive this piece. Our test image can go away, and we’ll start displaying a set of images.

    We’ll assume that in order to provide data to the CoverFlow object, it will most likely be provided as an external XML file. This makes for easier changes to live content, but also allows us to load more than one XML file to reuse the same CoverFlow module with different content in the same movie.

    Before we write the ActionScript to handle the XML, let’s write our XML file. Create a new text file called coverFlowImages.xml in the same folder as your CoverFlow.fla file. There will be a root node, of course, and inside of that will simply be a list of image nodes, one for each item to appear in the flow. The general format for an image node will look like this:

    
    
    <image src="path/to/image.jpg" title="A Titillating Title">
        whatever data we want to associate with the image
    </image>
    

    It’s assumed that the image will have an image path, and probably a title. However, we may want to associate more data with each image, which might just be simple text, or we could even provide a nested XML structure with complex data within, for example:

    
    
    <image src="people/DruKepple.jpg" title="Dru Kepple, ActionScript Implementor">
        <name>
            <first>Dru</first>
            <last>Kepple</last>
        </name>
        <employment>
            <company name="Summit Projects" url="http://www.summitprojects.com&quot; />
            <company name="Art Institute of Portland" url="http://www.aidepartments.com&quot; />
        </employment>
        <websites>
            <site url="summitprojectsflashblog.wordpress.com" />
            <site url="www.thekeppleeffect.com" />
            <site url="active.tutsplus.com/author/dru-kepple" />
            <site url="www.linkedin.com/drukepple" />
        </websites>
    </image>
    

    The point here is that inside of the image node, we can put whatever we want (from lengthy and complex XML data to nothing at all). This data will be available through the CoverFlow class, as the XML node that it is.

    Here’s our final full document (I used other images and links during the build), a list of images and data culled from active.tutsplus.com:

    
    
    <coverflow>
    	<image src="images/megaphone.jpg" title="HTML5, Flash and RIAs: 18 Industry Experts Have Their Say">
    		<link>http://active.tutsplus.com/articles/roundups/html5-and-flash-17-industry-experts-have-their-say/</link&gt;
    	</image>
    	<image src="images/magnifyer.jpg" title="Create an Impressive Magnifying Effect with ActionScript 3.0">
    		<link>http://active.tutsplus.com/tutorials/effects/create-an-impressive-magnifying-effect-with-actionscript-30/</link&gt;
    	</image>
    	<image src="images/as3101.jpg" title="AS3 101: Five Reasons to use Setters and Getters">
    		<link>http://active.tutsplus.com/tutorials/actionscript/as3-101-five-reasons-to-use-setters-and-getters/</link&gt;
    	</image>
    	<image src="images/montypython.jpg" title="10 Flash Things You Can’t Do With HTML5">
    		<link>http://active.tutsplus.com/articles/roundups/10-flash-things-you-can’t-do-with-html5/</link&gt;
    	</image>
    	<image src="images/bad.jpg" title="Blog Action Day: Clean up With a Beautiful Watery Game">
    		<link>http://active.tutsplus.com/tutorials/games/blog-action-day-clean-up-with-a-beautiful-watery-game/</link&gt;
    	</image>
    	<image src="images/hype.jpg" title="Create a Mesmeric Music Visualizer with HYPE">
    		<link>http://active.tutsplus.com/tutorials/effects/create-a-mesmeric-music-visualizer-with-hype/</link&gt;
    	</image>
    	<image src="images/max.jpg" title="Smart AS3 Video Loading with GreenSock LoaderMax – Free Active Premium!">
    		<link>http://active.tutsplus.com/tutorials/actionscript/smart-as3-video-loading-with-greensock-loadermax-free-active-premium/</link&gt;
    	</image>
    	<image src="images/50twitterers.jpg" title="50 More Flash Twitterers Worth Following">
    		<link>http://active.tutsplus.com/articles/roundups/50-more-flash-twitterers-worth-following/</link&gt;
    	</image>
    	<image src="images/open_mic_prefixes.jpg" title="Open Mike: Prefixes">
    		<link>http://active.tutsplus.com/articles/open-mike/open-mike-prefixes/</link&gt;
    	</image>
    	<image src="images/fullscreen_website.jpg" title="Create a Full Screen, Scalable Flash Website: Part 1">
    		<link>http://active.tutsplus.com/tutorials/web-design/create-a-full-screen-scalable-flash-website-part-1/</link&gt;
    	</image>
    </coverflow>
    

    It looks like a lot, but it’s really just a list of image nodes with two attributes each, the src and title, and a <link> node nested inside of the <image> node, which houses the URL of the article associated with the image.


    Step 22: Load an XML File

    To load XML, we’ll need a property to store the XML, and a property for a URLLoader to load the XML. We’ll need a public method to initiate a load with a String URL, some internal event handlers for the URLLoader to handle the XML load events. The elements of this step are pretty standard fare for loading XML, so I’ll just pile it all in to one step and not spend too much time explaining things.

    Start by adding two properties, one for the urlLoader and one for the xml, at the top of the CoverFlow class, with the rest of the properties.

    
    
    private var _urlLoader:URLLoader;
    private var _xml:XML;
    

    In CoverFlow’s constructor, create and set up the URLLoader (it doesn’t really matter where in the constructor, but I’m opting for at the end):

    
    
    _urlLoader = new URLLoader();
    _urlLoader.addEventListener(Event.COMPLETE, onXMLLoad);
    _urlLoader.addEventListener(IOErrorEvent.IO_ERROR, onXMLLoadError);
    

    Write the URLLoader event handling functions, somewhere in the main body of your class:

    
    
    private function onXMLLoad(e:Event):void {
        _xml = new XML(_urlLoader.data);
        trace("XML Loaded:\n" + _xml);
    }
    
    private function onXMLLoadError(e:IOErrorEvent):void {
        trace("There was an error loading the XML document: " + e.text);
    }
    

    Right now we’re just tracing things; we’re making sure we convert the URLLoader’s data to XML, then spitting it out as-is. We’re also handling an error in case we get a bad URL to load. We could do something fancier here, but for now we’re really just preventing the error from stopping everything else, while still tracing a message.

    We need a public load method, to initiate the XML load. We can assume that if there is already something loaded, we should clear it out first, then start the new load. To that end, we’ll not only start the load on the URLLoader, but also call a method called clearContents to remove anything previously created in the CoverFlow. We’ll fill that in later, but we’ll plan for it and call it, and create an empty method to house it.

    
    
    public function load(url:String):void {
        clearContents();
        _urlLoader.load(new URLRequest(url));
    }
    
    private function clearContents():void {
    
    }
    

    Lastly, we need to upgrade our tests. We need to remove the lines that create a test Cover from CoverFlow’s constructor (I’ve commented them out here so you can identify them, but go ahead and remove them. The next code snippet of this function will have them removed):

    
    
    public function CoverFlow(w:Number, h:Number) {
        _width = w;
        _height = h;
        _covers = new Vector.<Cover>();
    
        _coversContainer = new Sprite();
        addChild(_coversContainer);
    
        //var test:Cover = new Cover("I am a caption", <data />, _backgroundColor);
        //_coversContainer.addChild(test);
        //test.x = _width / 2;
        //test.y = _height / 2;
        //_covers.push(test);
    
        //trace(test.caption);
        //trace(test.data.toXMLString());
        //trace(test.backgroundColor);
    
        //test.load("images/best.jpg");
    
        _background = new Shape();
        addChildAt(_background, 0);
        drawBackground();
    
        scrollRect = new Rectangle(0, 0, _width, _height);
    
        _urlLoader = new URLLoader();
        _urlLoader.addEventListener(Event.COMPLETE, onXMLLoad);
        _urlLoader.addEventListener(IOErrorEvent.IO_ERROR, onXMLLoadError);
    }
    

    And then we need to go back to CoverFlowTest.as and add a call to load. Pass in the coverFlowImages.xml file we created in the last step.

    
    
    public function CoverFlowTest() {
        coverFlow = new CoverFlow(stage.stageWidth, stage.stageHeight);
        addChild(coverFlow);
        coverFlow.backgroundColor = 0x000000;
        coverFlow.load("coverFlowImages.xml");
    }
    

    You should see our XML document traced to the Output panel.


    Step 23: Parse the XML

    Next we need to parse the XML and eventually do something with the data. We’ll parse it in this step, and start doing something with it in the next step.

    In the onXMLLoad method of CoverFlow, remove the trace and replace it with some basic XML looping. For now, we’ll trace out values to make sure we’re parsing them correctly.

    
    
    private function onXMLLoad(e:Event):void {
        _xml = new XML(_urlLoader.data);
    
        var imageList:XMLList = _xml.image;
        var iLen:uint = imageList.length();
        var imageNode:XML;
        for (var i:uint = 0; i < iLen; i++) {
            imageNode = imageList[i];
            var src:String = imageNode.@src;
            var title:String = imageNode.@title;
            trace(src);
            trace(title);
            trace("");
        }
    }
    

    There isn’t anything too special going on. We’re just selecting all image nodes, loop over them, and then extracting the attributes from them. Now, we’ll do something with them.


    Step 24: Creating Cover Objects

    We will have the potential to load quite a few images. It will be better to control the load by loading one at a time. This will maximize bandwidth for each image, letting the first image show up as soon as possible, so that there is

  3. James Tyner says:
    June 29, 2012 at 9:40 am

    In this tutorial, we’ll take a basic browser game (which we built in a Tuts+ Premium tutorial), and add progress bars, a preloader, a splash screen, and a lot more polish.


    Introduction

    In this Tuts+ Premium tutorial, we built a basic card matching game with JavaScript, whose images came from Flickr. Check out the demo:



    Click to try the game as it is now.

    In this tutorial, we’ll add a lot of polish to the game, by implementing a preloader and progress bar, a splash screen, and a keyword search. Take a look at how the game will turn out:



    Click to try the game with the improvements we’ll be adding.

    In this tutorial, you’ll learn the JavaScript and HTML necessary to code all these improvements. Download the source files and extract the folder called StartHere; this contains all the code from the end of the Premium tutorial.

    In flickrgame.js there is a function called preloadImage(), which contains this line:

    
    
    tempImage.src = flickrGame.tempImages[i].imageUrl;
    

    For the purposes of testing, change it to:

    
    
    tempImage.src = "cardFront.jpg";
    

    This will show the images on the cards all the time, which makes testing a lot easier. You can change this back at any time.

    Now, read on!


    Step 1: addKeyPress()

    Right now we have the tag “dog” hard coded, but the game will get boring quickly if we force the user to use dog photos all the time!

    The search input has been sitting there looking pretty, but being totally non-functional all this time. Let’s fix that. We will listen for the user to hit the Enter key and then call the doSearch() method using whatever they typed in to call the Flickr API.

    Add the following beneath the resetImages() function, in flickrgame.js.

    
    
    function addKeyPress() {
    	$(document).on("keypress", function (e) {
    		if (e.keyCode == 13) {
    		  doSearch();
    		}
    	});
    }
    

    Here we listen for a keypress and if the keyCode is equal to 13, we know they pressed the Enter key so we call the doSearch() function.

    We need to modify the doSearch function to use the text in the input, so make the following changes:

    
    
    function doSearch() {
    	if ($("#searchterm").val() != "") {
    		$(document).off("keypress");
    		var searchURL = "http://api.flickr.com/services/rest/?method=flickr.photos.search&quot;;
    		searchURL += "&api_key=" + flickrGame.APIKEY;
    		searchURL += "&tags=" + $("#searchterm").val();
    		searchURL += "&per_page=36"
    		searchURL += "&license=5,7";
    		searchURL += "&format=json";
    		searchURL += "&jsoncallback=?";
    		$.getJSON(searchURL, setImages);
    	}
    }
    

    Here, we first check that the input is not empty (we don’t want to search for nothing), then we remove the keypress listener. Finally, we alter the tags to use the input’s value.

    The last thing we need to do is remove the call to doSearch() in the JS file. Find where we are manually calling doSearch() and remove it. (It’s right after the addKeyPress() function.)

    Dont forget to actually call the addKeyPress() function. I called it right beneath where I declared it.

    
    
    function addKeyPress() {
    	$(document).on("keypress", function (e) {
    		if (e.keyCode == 13) {
    		  doSearch();
    		}
    	});
    }
    addKeyPress();
    

    Now if you test the game you wont see any images until you do a search.


    Step 2: Contacting Server

    When we make our first call to Flickr’s API there is a slight delay. We will show an animated GIF (a “throbber”) while we contact the server, and remove it once the call comes back.

    Add the following to the doSearch() function.

    
    
    function doSearch() {
        if ($("#searchterm").val() != "") {
            $(document).off("keypress");
            $("#infoprogress").css({
                'visibility': 'visible'
            });
            var searchURL = "http://api.flickr.com/services/rest/?method=flickr.photos.search&quot;;
            searchURL += "&api_key=" + flickrGame.APIKEY;
            searchURL += "&tags=" + $("#searchterm").val();
            searchURL += "&per_page=36"
            searchURL += "&license=5,7";
            searchURL += "&format=json";
            searchURL += "&jsoncallback=?";
            $.getJSON(searchURL, setImages);
        }
    }
    

    This sets the #infoprogress div to be visible. Once the information comes back from Flickr, we will hide it. To do so, add the following code to the setImages() function:

    
    
    function setImages(data) {
    	$("#infoprogress").css({
    		'visibility': 'hidden'
    	});
    	$.each(data.photos.photo, function (i, item) {
    		var imageURL = 'http://farm' + item.farm + '.static.flickr.com/' + item.server + '/' + item.id + '_' + item.secret + '_' + 'q.jpg';
    		flickrGame.imageArray.push({
    				imageUrl: imageURL,
    				photoid: item.id
    		});
    	});
    
    	infoLoaded();
    }
    

    If you test the game now, you should see the loader image show while contacting the Flickr API.


    Step 3: Get Photo Info

    We need to get the information for each photo we use. We will call the method=flickr.photos.getInfo on each photo, and then call the infoLoaded() function every time the information is loaded. Once the information for every photo has loaded, the game continues as before.

    There is a lot of new information to take in here, so we will break it down step by step. First, add the following to the setImages() function:

    
    
    function setImages(data) {
        $("#infoprogress").css({
            'visibility': 'hidden'
        });
        if (data.photos.photo.length >= 12) {
            $("#searchdiv").css({
                'visibility': 'hidden'
            });
            $.each(data.photos.photo, function (i, item) {
                var imageURL = 'http://farm' + item.farm + '.static.flickr.com/' + item.server + '/' + item.id + '_' + item.secret + '_' + 'q.jpg';
                flickrGame.imageArray.push({
                    imageUrl: imageURL,
                    photoid: item.id
                });
                var getPhotoInfoURL = "http://api.flickr.com/services/rest/?method=flickr.photos.getInfo&quot;;
                getPhotoInfoURL += "&api_key=" + flickrGame.APIKEY;
                getPhotoInfoURL += "&photo_id=" + item.id;
                getPhotoInfoURL += "&format=json";
                getPhotoInfoURL += "&jsoncallback=?";
                $.getJSON(getPhotoInfoURL, infoLoaded);
            });
        } else {
            alert("NOT ENOUGH IMAGES WERE RETURNED");
            addKeyPress();
        }
        flickrGame.numberPhotosReturned = flickrGame.imageArray.length;
    }
    

    Now that we are getting the tags from the user we should make sure enough images were returned to make up a single game (12). If so, we hide the input so the player can’t do another search mid-game. We set a variable getPhotoInfoURL and use the method=flickr.photos.getInfo – notice that we are using the item.id for the photo_id. We then use the jQuery’s getJSON method, and call infoLoaded.

    If not enough images were returned, we throw up an alert and call addKeyPress() so the user can do another search.

    So we need to know how many images were returned from the call to the Flickr API, and we store this in the variable numberPhotosReturned, which we add to our flickrGame object:

    
    
    var flickrGame = {
    	APIKEY: "76656089429ab3a6b97d7c899ece839d",
    	imageArray: [],
    	tempImages:[],
    	theImages: [],
    	chosenCards: [],
    	numberPhotosReturned: 0
    }
    

    (Make sure you add a comma after chosenCards: [].)

    We cannot test just yet; if we did we would be calling preloadImages() 36 times in a row since that is all our infoLoaded() function does at the moment. Definitely not what we want. In the next step we will flesh out the infoLoaded() function.


    Step 4: infoLoaded()

    The infoLoaded() function receives information about a single photo. It adds the information to the imageArray for the proper photo, and keeps track of how many photos’ info have been loaded; if this number is equal to numberPhotosReturned, it calls preloadImages().

    Delete the call to preloadImages() and put the following inside the infoLoaded() function:

    
    
    	flickrGame.imageNum += 1;
    	var index = 0;
    	for (var i = 0; i < flickrGame.imageArray.length; i++) {
    		if (flickrGame.imageArray[i].photoid == data.photo.id) {
    			index = i;
    			flickrGame.imageArray[index].username = data.photo.owner.username;
    			flickrGame.imageArray[index].photoURL = data.photo.urls.url[0]._content;
    		}
    	}
    	if (flickrGame.imageNum == flickrGame.numberPhotosReturned) {
    		preloadImages();
    	}
    }
    

    Here we increment the imageNum variable and set a variable index equal to 0. Inside the for loop we check to see if the photoid in the imageArray is equal to the data.photo.id (remember the data is a JSON representation of the current image being processed). If they do match we set index equal to i and update the appropriate index in the imageArray with a username and photoURL variable. We’ll need this information when we show the image attributions later.

    This might seem a bit confusing, but all we are doing is matching up the photos. Since we don’t know the order in which they will be returned from the server we make sure their id’s match, and then we can add the username and photoURL variables to the photo.

    Lastly, we check if imageNum is equal to the numberPhotosReturned, and if it is then all images have been processed so we call preloadImages().

    Don’t forget to add the imageNum to the flickrGame object.

    
    
    var flickrGame = {
    	APIKEY: "76656089429ab3a6b97d7c899ece839d",
    	imageArray: [],
    	tempImages:[],
    	theImages: [],
    	chosenCards: [],
    	numberPhotosReturned: 0,
    	imageNum: 0
    }
    

    (Make sure you add a comma after the numberPhotosReturned: 0.)

    If you test now it will take a little longer for you to see the photos. On top of calling the Flickr API to retrieve the photos, we are now getting information about each one of them.


    Step 5: Progress Bar for Photo Info

    In this step we will get the progress bar showing when we load the photo information.

    Add the following code to the setImages() function:

    
    
    function setImages(data) {
        $("#infoprogress").css({
            'visibility': 'hidden'
        });
        $("#progressdiv").css({
            'visibility': 'visible'
        });
        $("#progressdiv p").text("Loading Photo Information");
        if (data.photos.photo.length >= 12) {
            $("#searchdiv").css({
                'visibility': 'hidden'
            });
            $.each(data.photos.photo, function (i, item) {
                var imageURL = 'http://farm' + item.farm + '.static.flickr.com/' + item.server + '/' + item.id + '_' + item.secret + '_' + 'q.jpg';
                flickrGame.imageArray.push({
                    imageUrl: imageURL,
                    photoid: item.id
                });
                var getPhotoInfoURL = "http://api.flickr.com/services/rest/?method=flickr.photos.getInfo&quot;;
                getPhotoInfoURL += "&api_key=" + flickrGame.APIKEY;
                getPhotoInfoURL += "&photo_id=" + item.id;
                getPhotoInfoURL += "&format=json";
                getPhotoInfoURL += "&jsoncallback=?";
                $.getJSON(getPhotoInfoURL, infoLoaded);
            });
        } else {
            $("#progressdiv").css({
                'visibility': 'hidden'
            });
            alert("NOT ENOUGH IMAGES WERE RETURNED");
            addKeyPress();
        }
        flickrGame.numberPhotosReturned = flickrGame.imageArray.length;
    }
    

    This shows the #progressdiv and changes the paragraph’s text within the #progressdiv to read “Loading Photo Information”. If not enough images were returned we hide the #progressdiv.

    Next add the following to the infoLoaded() function:

    
    
     function infoLoaded(data) {
    	flickrGame.imageNum += 1;
    	var percentage = Math.floor(flickrGame.imageNum / flickrGame.numberPhotosReturned * 100);
    	$("#progressbar").progressbar({
    		value: percentage
    	});
    	var index = 0;
    	for (var i = 0; i < flickrGame.imageArray.length; i++) {
    		if (flickrGame.imageArray[i].photoid == data.photo.id) {
    			index = i
    			flickrGame.imageArray[index].username = data.photo.owner.username;
    			flickrGame.imageArray[index].photoURL = data.photo.urls.url[0]._content;
    		}
    	}
    	if (flickrGame.imageNum == flickrGame.numberPhotosReturned) {
    		preloadImages();
    	}
    }
    

    Here we set a variable percentage equal to Math.floor(flickrGame.imageNum / flickrGame.numberPhotosReturned * 100); this makes sure we get a number between 0 and 100. Then we call $("#progressbar").progressbar() and set the value property equal to percentage.

    Now if you test the game it should work just as before, but with a progress bar. Well, there is one problem: the progress bar sticks around after the images get drawn. In the game we first load the photo information, then we preload the images and both use the progress bar. We will fix this in the next step.


    Step 6: Preloading the Images

    In this step we will utlilize the jQuery.imgpreload plugin (it’s already in the source download). As soon as all the file information from the above steps has been loaded, the progress bar resets itself and monitors the loading of the images.

    Add the following to the preloadImages() function:

    
    
    function preloadImages() {
        flickrGame.tempImages = flickrGame.imageArray.splice(0, 12);
        for (var i = 0; i < flickrGame.tempImages.length; i++) {
            for (var j = 0; j < 2; j++) {
                var tempImage = new Image();
                tempImage.src = "cardFront.png";
                tempImage.imageSource = flickrGame.tempImages[i].imageUrl;
                flickrGame.theImages.push(tempImage);
    
            }
        }
        $("#progressdiv").css({
            'visibility': 'visible'
        });
        $("#progressdiv p").text("Loading Images");
        var tempImageArray = [];
        for (var i = 0; i < flickrGame.tempImages.length; i++) {
            tempImageArray.push(flickrGame.tempImages[i].imageUrl);
        }
    
        $.imgpreload(tempImageArray, {
            each: function () {
                if ($(this).data('loaded')) {
                    flickrGame.numImagesLoaded++;
                    var percentage = Math.floor(flickrGame.numImagesLoaded / flickrGame.totalImages * 100);
                    $("#progressbar").progressbar({
                        value: percentage
                    });
                }
            },
            all: function () {
                $("#progressdiv").css({
                    'visibility': 'hidden'
                });
                drawImages();
            }
        });
    }
    

    Here we set the #progressdiv to be visible and change the paragraph to read “Loading Images”. We set up a temporary array and add the temporary images’ URLs to it, then pass the entire array to $.imgpreload to kick off the preload.

    The each function gets run each time a photo is preloaded, and the all function gets run when all the images have been preloaded. Inside each() we check to make sure the image actually was loaded, increment the numImagesLoaded variable, and use the same method for the percentage and progress bar as before. (The totalImages is 12 since that how many we are using per game.)

    Once all the images have been preloaded (that is, when all() is run) we set the #progessdiv to hidden and call the drawImages() function.

    We need to add the numImagesLoaded and totalImages variables to our flickrGame object:

    
    
    var flickrGame = {
    	APIKEY: "76656089429ab3a6b97d7c899ece839d",
    	imageArray: [],
    	tempImages:[],
    	theImages: [],
    	chosenCards: [],
    	numberPhotosReturned: 0,
    	imageNum: 0,
    	numImagesLoaded: 0,
    	totalImages: 12
    }
    

    (Make sure you add the comma after imageNum.)

    If you test the game now, you should see the progress bar for both the photo information and for the preloading of the images.


    Step 7: Showing the Attributions

    To conform to the Flickr API terms of service, we have to show attributions for the images we use. (It’s also polite to do so.)

    Add the following code within the hideCards() function:

    
    
    function hideCards() {
    	$(flickrGame.chosenCards[0]).animate({
    		'opacity': '0'
    	});
    	$(flickrGame.chosenCards[1]).animate({
    		'opacity': '0'
    	});
    	flickrGame.theImages.splice(flickrGame.theImages.indexOf(flickrGame.chosenCards[0]), 1);
    	flickrGame.theImages.splice(flickrGame.theImages.indexOf(flickrGame.chosenCards[1]), 1);
    	$("#image1").css('background-image', 'none');
    	$("#image2").css('background-image', 'none');
    
    	if (flickrGame.theImages.length == 0) {
    		$("#gamediv img.card").remove();
    		$("#gamediv").css({
    			'visibility': 'hidden'
    		});
    		showAttributions();
    	}
    	addListeners();
    	flickrGame.chosenCards = new Array();
    }
    

    Here, we check if the number of images left is zero, and if so we know the user has matched all of the cards. We therefore remove all the cards from the DOM and set the #gamediv to be hidden. Then, we call the showAttributions() function which we will code next.


    Step 8: Show Attributions

    In this step we will code the showAttributions() function.

    Add the following beneath the checkForMatch() function you coded in the steps above:

    
    
    function showAttributions() {
    	$("#attributionsdiv").css({
    		'visibility': 'visible'
    	});
    	$("#attributionsdiv div").each(function (index) {
    		$(this).find('img').attr('src', flickrGame.tempImages[index].imageUrl).
    		next().html('<span>Username: </span> ' + flickrGame.tempImages[index].username + '<br/>' + '<a href="' + flickrGame.tempImages[index].photoURL + '"target="_blank">View Photo</a>');
    	});
    }
    

    Here we set the #attributionsdiv to be visible, and then loop through each div within it. There are 12 divs, each with an image and a paragraph; we use jQuery’s find() method to find the img within the div, set the src of the image to the correct imageUrl, and use jQuery’s next() method to set the username and photoURL to the info from Flickr.

    Here are links to jQuery’s find() and next() methods so you can learn more about them.

    If you test the game now and play through a level, you’ll see the attributions with a link to the image on Flickr. You will also see two buttons: one for the next level and one for a new game. We will get these buttons working in the next steps.


    Step 9: Next Level

    In our call to the Flickr API we set per_page to 36, to request that many images at once. Since we are using 12 images per game, this means that there can be up to three levels. In this step we will get the Next Level button working.

    Add the following code within the setImages() function:

    
    
    function setImages(data) {
    
    	// ... snip ...
    
    	flickrGame.numberPhotosReturned = flickrGame.imageArray.length;
    	flickrGame.numberLevels = Math.floor(flickrGame.numberPhotosReturned / 12);
    }
    

    We need to know how many levels the game will have. This depends on how many images were returned from our search. It will not always be 36. For example, I searched for “hmmmm” and it returned about 21 photos at the time. We’ll use Math.floor() to round the number down – we don’t want 2.456787 levels, after all, and it would throw the game logic way off.

    Make sure you add the numberLevels variable to the flickrGame object:

    
    
    var flickrGame = {
    	APIKEY: "76656089429ab3a6b97d7c899ece839d",
    	imageArray: [],
    	tempImages:[],
    	theImages: [],
    	chosenCards: [],
    	numberPhotosReturned: 0,
    	imageNum: 0,
    	numImagesLoaded: 0,
    	totalImages: 12,
    	numberLevels: 0
    }
    

    (Don’t forget to add the comma after totalImages: 12.)

    Now modify the drawImages() function as follows:

    
    
    function drawImages() {
    	flickrGame.currentLevel += 1;
    	$("#leveldiv").css({
    		'visibility': 'visible'
    	}).html("Level " + flickrGame.currentLevel + " of " + flickrGame.numberLevels);
    	flickrGame.theImages.sort(randOrd);
    	for (var i = 0; i < flickrGame.theImages.length; i++) {
    		$(flickrGame.theImages[i]).attr("class", "card").appendTo("#gamediv");
    	}
    	addListeners();
    }
    

    Here we increment the currentLevel variable, set the #leveldiv to be visible and set the HTML of the div to read what level we are on and how many levels there are.

    Once again, we need to add the currentLevel variable to our flickrGame object.

    
    
    var flickrGame = {
    	APIKEY: "76656089429ab3a6b97d7c899ece839d",
    	imageArray: [],
    	tempImages:[],
    	theImages: [],
    	chosenCards: [],
    	numberPhotosReturned: 0,
    	imageNum: 0,
    	numImagesLoaded: 0,
    	totalImages: 12,
    	numberLevels: 0,
    	currentLevel: 0
    }
    

    (I’m sure you don’t need reminding by now, but make sure you add the comma after numberLevels: 0.)

    Now modify the showAttributions() function to the following:

    
    
    function showAttributions() {
    	$("#leveldiv").css({
    		'visibility': 'hidden'
    	});
    	$("#attributionsdiv").css({
    		'visibility': 'visible'
    	});
    	if (flickrGame.currentLevel == flickrGame.numberLevels) {
    		$("#nextlevel_btn").css({
    			'visibility': 'hidden'
    		});
    	} else {
    		$("#nextlevel_btn").css({
    			'visibility': 'visible'
    		});
    	}
    
    	$("#attributionsdiv div").each(function (index) {
    		$(this).find('img').attr('src', flickrGame.tempImages[index].imageUrl);
    		$(this).find('p').html('<span>Username: </span> ' + flickrGame.tempImages[index].username + '<br/>' + '<a href="' + flickrGame.tempImages[index].photoURL + '"target="_blank">View Photo</a>');
    	});
    }
    

    We hide the #leveldiv by setting its visibility to hidden.

    Next we check whether the currentLevel is equal to the numberLevels. If they are equal, there are no more levels available so we hide the #nextlevel_btn; otherwise, we show it.

    Finally we need to wire up the #nextlevel_btn. Add the following code beneath the addKeyPress() function you created in the step above:

    
    
    $("#nextlevel_btn").on("click", function (e) {
    	$(this).css({
    		'visibility': 'hidden'
    	});
    	$("#gamediv").css({
    		'visibility': 'visible'
    	});
    	$("#attributionsdiv").css({
    		'visibility': 'hidden'
    	});
    
    	flickrGame.numImagesLoaded = 0;
    	preloadImages();
    
    });
    

    Here we hide the button, reveal the #gamediv, hide the #attributionsdiv, reset the numImagesLoaded variable, and call preloadImages() which grabs the next 12 images.

    You can test the game now and should be able to play through all the levels. We will wire up the #newgame_btn in the coming steps.


    Step 10: Starting a New Game

    You can begin a new game at any time, but after all the levels have been played that is the only option. In this step we will wire up the #newgame_btn.

    Add the following beneath the code for the #nextlevel_btn you added in the step above:

    
    
    $("#newgame_btn").on("click", function (e) {
    	$("#gamediv").css({
    		'visibility': 'visible'
    	});
    	$("#leveldiv").css({
    		'visibility': 'hidden'
    	});
    	$("#attributionsdiv").css({
    		'visibility': 'hidden'
    	});
    	$("#searchdiv").css({
    		'visibility': 'visible'
    	});
    	$("#nextlevel_btn").css({
    		'visibility': 'hidden'
    	});
    	flickrGame.imageNum = 0;
    	flickrGame.numImagesLoaded = 0;
    	flickrGame.imageArray = new Array();
    	flickrGame.currentLevel = 0;
    	flickrGame.numberLevels = 0;
    	addKeyPress();
    });
    

    Here we reveal the #gamediv, hide the #leveldiv and #attributionsdiv, reveal the #searchdiv, and hide the #nextlevel_btn. We then reset some variables, and call addKeyPress() so the user can search again.

    If you test now you should be able to start a new game at any time, as well as when all levels have been played.

    The game is complete as far as gameplay is concerned, but we need to show a splash screen. We’ll do this in the next step.


    Step 11: Splash Screen

    We need to make some changes to our CSS file. Specifically, we need to set the #gamediv visibility to hidden, and set the #introscreen to visible. Open styles/game.css and make those changes now:

    
    
    #gamediv {
    position:absolute;
    left:150px;
    width:600px;
    height:375px;
    border: 1px solid black;
    padding:10px;
    color:#FF0080;
    visibility:hidden;
    background: #FFFFFF url('../pattern.png');
    }
    
    #introscreen{
    position:absolute;
    left:150px;
    width:600px;
    height:375px;
    border: 1px solid black;
    padding-top:10px;
    color:#FF0080;
    visibility:visible;
    background: #FFFFFF url('../pattern.png');
    padding-left:80px;
    }
    

    Next we need to change the addKeyPress() function. Remove everything from addKeyPress() and replace it with the following:

    
    
    function addKeyPress() {
        $(document).on("keypress", function (e) {
            if (e.keyCode == 13) {
                if (!flickrGame.gameStarted) {
                    hideIntroScreen();
                } else {
                    doSearch();
                }
                flickrGame.gameStarted = true;
            }
        });
    }
    

    Here we check if the user has pressed the Enter key, then we check whether the game has started. If it hasn’t we call hideIntroScreen(); otherwise, we call doSearch(); either way, we mark the game as having started. This means that the first time the user presses Enter it will call hideIntroScreen(), and the next time the user presses the Enter key it will call doSearch().

    Now we need to code the hideIntroScreen() function. Add the following beneath the addKeyPress() function:

    
    
    function hideIntroScreen() {
    	$("#gamediv").css({
    		'visibility': 'visible'
    	});
    	$("#introscreen").css({
    		'visibility': 'hidden'
    	});
    }
    

    If you test the game now you should see the splash screen; press Enter and you can play the game as before.


    Step 12: A Better Alert

    Right now if enough images are not returned for a game, we pop up an alert. Although this works, we can make it look a little nicer by using jQuery UI’s dialog.

    We need to edit index.html, so open it and add the following right inside the #gamediv:

    
    
    <div id="gamediv">
    <div id="dialog" title="Sorry">
    <p>Not enough images were returned, please try a different keyword.</p>
    
    </div>
    

    Now we need tie it in. Add the following beneath the hideIntroScreen() function in the JS file:

    
    
    $("#dialog").dialog({
         autoOpen: false
    });
    

    This code converts the #dialog div into a dialog; we disable the auto-open feature.

    We want to trigger this dialog to open instead of the alert we had before, so remove the alert from the setImages() function and replace it with the following:

    
    
    } else {
            $("#progressdiv").css({
                'visibility': 'hidden'
            });
            $("#dialog").dialog('open');
            addKeyPress();
        }
        flickrGame.numberPhotosReturned = flickrGame.imageArray.length;
        flickrGame.numberLevels = Math.floor(flickrGame.numberPhotosReturned / 12);
    }
    

    Now, if not enough images are returned we get a nice looking dialog, instead of using an alert reminiscent of webpages from the ’90s.

    Don’t forget to change this line, from preloadImages():

    
    
    tempImage.src = "cardFront.jpg";
    

    …back to this:

    
    
    tempImage.src = flickrGame.tempImages[i].imageUrl;
    

    …otherwise, the game will be a bit too easy!

    Now test the final game. If anything’s not quite right, you can always compare your source to mine, or ask a question in the comments.

    Conclusion

    We have coded a fun little game using images from the Flickr API, and given it a decent layer or two of polish. I hope you enjoyed this tutorial and learned something worthwhile. Thanks for reading and have fun!


  4. Patrick Jaoko says:
    June 29, 2012 at 9:46 am

    If you’ve been doing JavaScript development long enough, you’ve most likely crashed your browser a few times. The problem usually turns out to be some JavaScript bug, like an endless while loop; if not, the next suspect is page transformations or animations – the kind that involve adding and removing elements from the webpage or animating CSS style properties. This tutorial focuses on optimising animations produced using JS and the HTML5 <canvas> element.

    This tutorial starts and ends with what the HTML5 animation widget you see below:

    We will take it with us on a journey, exploring the different emerging canvas optimization tips and techniques and applying them to the widget’s JavaScript source code. The goal is to improve on the widget’s execution speed and end up with a smoother, more fluid animation widget, powered by leaner, more efficient JavaScript.

    The source download contains the HTML and JavaScript from each step in the tutorial, so you can follow along from any point.

    Let’s take the first step.


    Step 1: Play the Movie Trailer

    The widget above is based on the movie trailer for Sintel, a 3D animated movie by the Blender Foundation. It’s built using two of HTML5′s most popular additions: the <canvas> and <video> elements.

    The <video> loads and plays the Sintel video file, while the <canvas> generates its own animation sequence by taking snapshots of the playing video and blending it with text and other graphics. When you click to play the video, the canvas springs to life with a dark background that’s a larger black and white copy of the playing video. Smaller, colored screen-shots of the video are copied to the scene, and glide across it as part of a film roll illustration.

    In the top left corner, we have the title and a few lines of descriptive text that fade in and out as the animation plays. The script’s performance speed and related metrics are included as part of the animation, in the small black box at the bottom left corner with a graph and vivid text. We’ll be looking at this particular item in more detail later.

    Finally, there’s a large rotating blade that flies across the scene at the beginning of the animation, whose graphic is loaded from an external PNG image file.


    Step 2: View the Source

    The source code contains the usual mix of HTML, CSS and Javascript. The HTML is sparse: just the <canvas> and <video> tags, enclosed in a container <div>:

    
    
    <div id="animationWidget" >
    	<canvas width="368" height="208" id="mainCanvas" ></canvas>
    	<video width="184" height="104" id="video" autobuffer="autobuffer" controls="controls" poster="poster.jpg" >
    		<source src="sintel.mp4" type="video/mp4" ></source>
    		<source src="sintel.webm" type="video/webm" ></source>
    	</video>
    </div>
    

    The container <div> is given an ID (animationWidget), which acts as a hook for all the CSS rules applied to it and its contents (below).

    
    
    #animationWidget{
    	border:1px #222 solid;
    	position:relative;
    	width: 570px;
    	height: 220px;
    }
    #animationWidget canvas{
    	border:1px #222 solid;
    	position:absolute;
    	top:5px;
    	left:5px;
    }
    #animationWidget video{
    	position:absolute;
    	top:110px;
    	left:380px;
    }
    

    While HTML and CSS are the marinated spices and seasoning, its the JavaScript that’s the meat of the widget.

    • At the top, we have the main objects that will be used often through the script, including references to the canvas element and its 2D context.
    • The init() function is called whenever the video starts playing, and sets up all the objects used in the script.
    • The sampleVideo() function captures the current frame of the playing video, while setBlade() loads an external image required by the animation.
    • The pace and contents of the canvas animation are controlled by the main() function, which is like the script’s heartbeat. Run at regular intervals once the video starts playing, it paints each frame of the animation by first clearing the canvas, then calling each one of the script’s five drawing functions:
      • drawBackground()
      • drawFilm()
      • drawTitle()
      • drawDescription()
      • drawStats()

    As the the names suggest, each drawing function is responsible for drawing an item in the animation scene. Structuring the code this way improves flexibility and makes future maintenance easier.

    The full script is shown below. Take a moment to assess it, and see if you can spot any changes you would make to speed it up.

    
    
    (function(){
    	if( !document.createElement("canvas").getContext ){ return; } //the canvas tag isn't supported
    
    	var mainCanvas = document.getElementById("mainCanvas"); // points to the HTML canvas element above
    	var mainContext = mainCanvas.getContext('2d'); //the drawing context of the canvas element
    	var video = document.getElementById("video"); // points to the HTML video element
    	var frameDuration = 33; // the animation's speed in milliseconds
    	video.addEventListener( 'play', init ); // The init() function is called whenever the user presses play & the video starts/continues playing
    	video.addEventListener( 'ended', function(){ drawStats(true); } ); //drawStats() is called one last time when the video end, to sum up all the statistics 		
    
    	var videoSamples; // this is an array of images, used to store all the snapshots of the playing video taken over time. These images are used to create the 'film reel'
    	var backgrounds; // this is an array of images, used to store all the snapshots of the playing video taken over time. These images are used as the canvas background
    	var blade; //An canvas element to store the image copied from blade.png
    	var bladeSrc = 'blade.png'; //path to the blade's image source file
    
    	var lastPaintCount = 0; // stores the last value of mozPaintCount sampled
    	var paintCountLog = []; // an array containing all measured values of mozPaintCount over time
    	var speedLog = []; // an array containing all the execution speeds of main(), measured in milliseconds
    	var fpsLog = []; // an array containing the calculated frames per secong (fps) of the script, measured by counting the calls made to main() per second
    	var frameCount = 0; // counts the number of times main() is executed per second.
    	var frameStartTime = 0; // the last time main() was called
    
    	// Called when the video starts playing. Sets up all the javascript objects required to generate the canvas animation and measure perfomance
    	function init(){
    		if( video.currentTime > 1 ){ return; }		
    
    		bladeSrc = new Image();
    		bladeSrc.src = "blade.png";
    		bladeSrc.onload = setBlade;
    
    		backgrounds = [];
    		videoSamples = [];
    		fpsLog = [];
    		paintCountLog = [];
    		if( window.mozPaintCount ){ lastPaintCount = window.mozPaintCount; }
    		speedLog = [];
    		frameCount = 0;
    		frameStartTime = 0;
    		main();
    		setTimeout( getStats, 1000 );
    	}
    
    	// As the scripts main function, it controls the pace of the animation
    	function main(){
    		setTimeout( main, frameDuration );
    		if( video.paused || video.ended ){ return; }
    
    		var now = new Date().getTime();
    		if( frameStartTime ){
    			speedLog.push( now - frameStartTime );
    		}
    		frameStartTime = now;
    		if( video.readyState < 2 ){ return; }
    
    		frameCount++;
    		mainCanvas.width = mainCanvas.width; //clear the canvas
    		drawBackground();
    		drawFilm();
    		drawDescription();
    		drawStats();
    		drawBlade();
    		drawTitle();
    	}
    
    	// This function is called every second, and it calculates and stores the current frame rate
    	function getStats(){
    		if( video.readyState >= 2 ){
    			if( window.mozPaintCount ){ //this property is specific to firefox, and tracks how many times the browser has rendered the window since the document was loaded
    				paintCountLog.push( window.mozPaintCount - lastPaintCount );
    				lastPaintCount = window.mozPaintCount;
    			}			
    
    			fpsLog.push(frameCount);
    			frameCount = 0;
    		}
    		setTimeout( getStats, 1000 );
    	}
    
    	// create blade, the ofscreen canavs that will contain the spining animation of the image copied from blade.png
    	function setBlade(){
    		blade = document.createElement("canvas");
    		blade.width = 400;
    		blade.height = 400;
    		blade.angle = 0;
    		blade.x = -blade.height * 0.5;
    		blade.y = mainCanvas.height/2 - blade.height/2;
    	}
    
    	// Creates and returns a new image that contains a snapshot of the currently playing video.
    	function sampleVideo(){
    		var newCanvas = document.createElement("canvas");
    		newCanvas.width = video.width;
    		newCanvas.height = video.height;
    		newCanvas.getContext("2d").drawImage( video, 0, 0, video.width, video.height );
    		return newCanvas;
    	}
    
    	// renders the dark background for the whole canvas element. The background features a greyscale sample of the video and a gradient overlay
    	function drawBackground(){
    		var newCanvas = document.createElement("canvas");
    		var newContext = newCanvas.getContext("2d");
    		newCanvas.width = mainCanvas.width;
    		newCanvas.height = mainCanvas.height;
    		newContext.drawImage(  video, 0, video.height * 0.1, video.width, video.height * 0.5, 0, 0, mainCanvas.width, mainCanvas.height  );
    
    		var imageData, data;
    		try{
    			imageData = newContext.getImageData( 0, 0, mainCanvas.width, mainCanvas.height );
    			data = imageData.data;
    		} catch(error){ // CORS error (eg when viewed from a local file). Create a solid fill background instead
    			newContext.fillStyle = "yellow";
    			newContext.fillRect( 0, 0, mainCanvas.width, mainCanvas.height );
    			imageData = mainContext.createImageData( mainCanvas.width, mainCanvas.height );
    			data = imageData.data;
    		}
    
    		//loop through each pixel, turning its color into a shade of grey
    		for( var i = 0; i < data.length; i += 4 ){
    			var red = data[i];
    			var green = data[i + 1];
    			var blue = data[i + 2];
    			var grey = Math.max( red, green, blue );
    
    			data[i] =  grey;
    			data[i+1] = grey;
    			data[i+2] = grey;
    		}
    		newContext.putImageData( imageData, 0, 0 );
    
    		//add the gradient overlay
    		var gradient = newContext.createLinearGradient( mainCanvas.width/2, 0, mainCanvas.width/2, mainCanvas.height );
    		gradient.addColorStop( 0, '#000' );
    		gradient.addColorStop( 0.2, '#000' );
    		gradient.addColorStop( 1, "rgba(0,0,0,0.5)" );
    		newContext.fillStyle = gradient;
    		newContext.fillRect( 0, 0, mainCanvas.width, mainCanvas.height );
    
    		mainContext.save();
    		mainContext.drawImage( newCanvas, 0, 0, mainCanvas.width, mainCanvas.height );
    
    		mainContext.restore();
    	}
    
    	// renders the 'film reel' animation that scrolls across the canvas
    	function drawFilm(){
    		var sampleWidth = 116; // the width of a sampled video frame, when painted on the canvas as part of a 'film reel'
    		var sampleHeight = 80; // the height of a sampled video frame, when painted on the canvas as part of a 'film reel'
    		var filmSpeed = 20; // determines how fast the 'film reel' scrolls across the generated canvas animation.
    		var filmTop = 120; //the y co-ordinate of the 'film reel' animation
    		var filmAngle = -10 * Math.PI / 180; //the slant of the 'film reel'
    		var filmRight = ( videoSamples.length > 0 )? videoSamples[0].x + videoSamples.length * sampleWidth : mainCanvas.width; //the right edge of the 'film reel' in pixels, relative to the canvas		
    
    		//here, we check if the first frame of the 'film reel' has scrolled out of view
    		if( videoSamples.length > 0 ){
    			var bottomLeftX = videoSamples[0].x + sampleWidth;
    			var bottomLeftY = filmTop + sampleHeight;
    			bottomLeftX = Math.floor( Math.cos(filmAngle) * bottomLeftX - Math.sin(filmAngle) * bottomLeftY ); // the final display position after rotation
    
    			if( bottomLeftX < 0 ){ //the frame is offscreen, remove it's refference from the film array
    				videoSamples.shift();
    			}
    		}			
    
    		// add new frames to the reel as required
    		while( filmRight <= mainCanvas.width ){
    			var newFrame = {};
    			newFrame.x = filmRight;
    			newFrame.canvas = sampleVideo();
    			videoSamples.push(newFrame);
    			filmRight += sampleWidth;
    		}
    
    		// create the gradient fill for the reel
    		var gradient = mainContext.createLinearGradient( 0, 0, mainCanvas.width, mainCanvas.height );
    		gradient.addColorStop( 0, '#0D0D0D' );
    		gradient.addColorStop( 0.25, '#300A02' );
    		gradient.addColorStop( 0.5, '#AF5A00' );
    		gradient.addColorStop( 0.75, '#300A02' );
    		gradient.addColorStop( 1, '#0D0D0D' );			
    
    		mainContext.save();
    		mainContext.globalAlpha = 0.9;
    		mainContext.fillStyle = gradient;
    		mainContext.rotate(filmAngle);
    
    		// loops through all items of film array, using the stored co-ordinate values of each to draw part of the 'film reel'
    		for( var i in videoSamples ){
    			var sample = videoSamples[i];
    			var punchX, punchY, punchWidth = 4, punchHeight = 6, punchInterval = 11.5;
    
    			//draws the main rectangular box of the sample
    			mainContext.beginPath();
    			mainContext.moveTo( sample.x, filmTop );
    			mainContext.lineTo( sample.x + sampleWidth, filmTop );
    			mainContext.lineTo( sample.x + sampleWidth, filmTop + sampleHeight );
    			mainContext.lineTo( sample.x, filmTop + sampleHeight );
    			mainContext.closePath();				
    
    			//adds the small holes lining the top and bottom edges of the 'fim reel'
    			for( var j = 0; j < 10; j++ ){
    				punchX = sample.x + ( j * punchInterval ) + 5;
    				punchY = filmTop + 4;
    				mainContext.moveTo( punchX, punchY + punchHeight );
    				mainContext.lineTo( punchX + punchWidth, punchY + punchHeight );
    				mainContext.lineTo( punchX + punchWidth, punchY );
    				mainContext.lineTo( punchX, punchY );
    				mainContext.closePath();
    				punchX = sample.x + ( j * punchInterval ) + 5;
    				punchY = filmTop + 70;
    				mainContext.moveTo( punchX, punchY + punchHeight );
    				mainContext.lineTo( punchX + punchWidth, punchY + punchHeight );
    				mainContext.lineTo( punchX + punchWidth, punchY );
    				mainContext.lineTo( punchX, punchY );
    				mainContext.closePath();
    			}
    			mainContext.fill();
    		}		
    
    		//loop through all items of videoSamples array, update the x co-ordinate values of each item, and draw its stored image onto the canvas
    		mainContext.globalCompositeOperation = 'lighter';
    		for( var i in videoSamples ){
    			var sample = videoSamples[i];
    			sample.x -= filmSpeed;
    			mainContext.drawImage( sample.canvas, sample.x + 5, filmTop + 10, 110, 62 );
    		}
    
    		mainContext.restore();
    	}
    
    	// renders the canvas title
    	function drawTitle(){
    		mainContext.save();
    		mainContext.fillStyle = 'black';
    		mainContext.fillRect( 0, 0, 368, 25 );
    		mainContext.fillStyle = 'white';
    		mainContext.font = "bold 21px Georgia";
    		mainContext.fillText( "SINTEL", 10, 20 );
    		mainContext.restore();
    	}
    
    	// renders all the text appearing at the top left corner of the canvas
    	function drawDescription(){
    		var text = []; //stores all text items, to be displayed over time. the video is 60 seconds, and each will be visible for 10 seconds.
    		text[0] = "Sintel is an independently produced short film, initiated by the Blender Foundation.";
    		text[1] = "For over a year an international team of 3D animators and artists worked in the studio of the Amsterdam Blender Institute on the computer-animated short 'Sintel'.";
    		text[2] = "It is an epic short film that takes place in a fantasy world, where a girl befriends a baby dragon.";
    		text[3] = "After the little dragon is taken from her violently, she undertakes a long journey that leads her to a dramatic confrontation.";
    		text[4] = "The script was inspired by a number of story suggestions by Martin Lodewijk around a Cinderella character (Cinder in Dutch is 'Sintel'). ";
    		text[5] = "Screenwriter Esther Wouda then worked with director Colin Levy to create a script with multiple layers, with strong characterization and dramatic impact as central goals.";
    		text = text[Math.floor( video.currentTime / 10 )]; //use the videos current time to determine which text item to display.  
    
    		mainContext.save();
    		var alpha = 1 - ( video.currentTime % 10 ) / 10;
    		mainContext.globalAlpha = ( alpha < 5 )? alpha : 1;
    		mainContext.fillStyle = '#fff';
    		mainContext.font = "normal 12px Georgia";
    
    		//break the text up into several lines as required, and write each line on the canvas
    		text = text.split(' ');
    		var colWidth = mainCanvas.width * .75;
    		var line = '';
    		var y = 40;
    		for(var i in text ){
    			line += text[i] + ' ';
    			if( mainContext.measureText(line).width > colWidth ){
    				mainContext.fillText( line, 10, y );
    				line = '';
    				y += 12;
    			}
    		}
    		mainContext.fillText( line, 10, y ); 
    
    		mainContext.restore();
    	}
    
    	//updates the bottom-right potion of the canvas with the latest perfomance statistics
    	function drawStats( average ){
    		var x = 245.5, y = 130.5, graphScale = 0.25;
    
    		mainContext.save();
    		mainContext.font = "normal 10px monospace";
    		mainContext.textAlign = 'left';
    		mainContext.textBaseLine = 'top';
    		mainContext.fillStyle = 'black';
    		mainContext.fillRect( x, y, 120, 75 );			
    
    		//draw the x and y axis lines of the graph
    		y += 30;
    		x += 10;
    		mainContext.beginPath();
    		mainContext.strokeStyle = '#888';
    		mainContext.lineWidth = 1.5;
    		mainContext.moveTo( x, y );
    		mainContext.lineTo( x + 100, y );
    		mainContext.stroke();
    		mainContext.moveTo( x, y );
    		mainContext.lineTo( x, y - 25 );
    		mainContext.stroke();			
    
    		// draw the last 50 speedLog entries on the graph
    		mainContext.strokeStyle = '#00ffff';
    		mainContext.fillStyle = '#00ffff';
    		mainContext.lineWidth = 0.3;
    		var imax = speedLog.length;
    		var i = ( speedLog.length > 50 )? speedLog.length - 50 : 0
    		mainContext.beginPath();
    		for( var j = 0; i < imax; i++, j += 2 ){
    			mainContext.moveTo( x + j, y );
    			mainContext.lineTo( x + j, y - speedLog[i] * graphScale );
    			mainContext.stroke();
    		}
    
    		// the red line, marking the desired maximum rendering time
    		mainContext.beginPath();
    		mainContext.strokeStyle = '#FF0000';
    		mainContext.lineWidth = 1;
    		var target = y - frameDuration * graphScale;
    		mainContext.moveTo( x, target );
    		mainContext.lineTo( x + 100, target );
    		mainContext.stroke();
    
    		// current/average speedLog items
    		y += 12;
    		if( average ){
    			var speed = 0;
    			for( i in speedLog ){ speed += speedLog[i]; }
    			speed = Math.floor( speed / speedLog.length * 10) / 10;
    		}else {
    			speed = speedLog[speedLog.length-1];
    		}
    		mainContext.fillText( 'Render Time: ' + speed, x, y );
    
    		// canvas fps
    		mainContext.fillStyle = '#00ff00';
    		y += 12;
    		if( average ){
    			fps = 0;
    			for( i in fpsLog ){ fps += fpsLog[i]; }
    			fps = Math.floor( fps / fpsLog.length * 10) / 10;
    		}else {
    			fps = fpsLog[fpsLog.length-1];
    		}
    		mainContext.fillText( ' Canvas FPS: ' + fps, x, y );
    
    		// browser frames per second (fps), using window.mozPaintCount (firefox only)
    		if( window.mozPaintCount ){
    			y += 12;
    			if( average ){
    				fps = 0;
    				for( i in paintCountLog ){ fps += paintCountLog[i]; }
    				fps = Math.floor( fps / paintCountLog.length * 10) / 10;
    			}else {
    				fps = paintCountLog[paintCountLog.length-1];
    			}
    			mainContext.fillText( 'Browser FPS: ' + fps, x, y );
    		}
    
    		mainContext.restore();
    	}
    
    	//draw the spining blade that appears in the begining of the animation
    	function drawBlade(){
    		if( !blade || blade.x > mainCanvas.width ){ return; }
    		blade.x += 2.5;
    		blade.angle = ( blade.angle - 45 ) % 360;
    
    		//update blade, an ofscreen canvas containing the blade's image
    		var angle = blade.angle * Math.PI / 180;
    		var bladeContext = blade.getContext('2d');
    		blade.width = blade.width; //clear the canvas
    		bladeContext.save();
    		bladeContext.translate( 200, 200 );
    		bladeContext.rotate(angle);
    		bladeContext.drawImage( bladeSrc, -bladeSrc.width/2, -bladeSrc.height/2 );
    		bladeContext.restore();
    
    		mainContext.save();
    		mainContext.globalAlpha = 0.95;
    		mainContext.drawImage( blade, blade.x, blade.y + Math.sin(angle) * 50 );
    		mainContext.restore();
    	}
    })();

    Step 3: Code Optimization: Know the Rules

    The first rule of code performance optimization is: Don’t.

    The point of this rule is to discourage optimization for optimization’s sake, since the process comes at a price.

    A highly optimized script will be easier for the browser to parse and process, but usually with a burden for humans who will find it harder to follow and maintain. Whenever you do decide that some optimization is necessary, set some goals beforehand so that you don’t get carried away by the process and overdo it.

    The goal in optimizing this widget will be to have the main() function run in less than 33 milliseconds as it’s supposed to, which will match the frame rate of the playing video files (sintel.mp4 and sintel.webm). These files were encoded at a playback speed of 30fps (thirty frames per second), which translates to about 0.33 seconds or 33 milliseconds per frame ( 1 second ÷ 30 frames ).

    Since JavaScript draws a new animation frame to the canvas every time the main() function is called, the goal of our optimization process will be to make this function take 33 milliseconds or less each time it runs. This function repeatedly calls itself using a setTimeout() Javascript timer as shown below.

    
    
    var frameDuration = 33; // set the animation's target speed in milliseconds
    function main(){
    	if( video.paused || video.ended ){ return false; }
    	setTimeout( main, frameDuration );
    

    The second rule: Don’t yet.

    This rule stresses the point that optimization should always be done at the end of the development process when you’ve already fleshed out some complete, working code. The optimization police will let us go on this one, since the widget’s script is a perfect example of complete, working program that’s ready for the process.

    The third rule: Don’t yet, and profile first.

    This rule is about understanding your program in terms of runtime performance. Profiling helps you know rather than guess which functions or areas of the script take up the most time or are used most often, so that you can focus on those in the optimization process. It is critical enough to make leading browsers ship with inbuilt JavaScript profilers, or have extensions that provide this service.

    I ran the widget under the profiler in Firebug, and below is a screenshot of the results.


    Step 4: Set Some Performance Metrics

    As you ran the widget, I’m sure you found all the Sintel stuff okay, and were absolutely blown away by the item on the lower right corner of the canvas, the one with a beautiful graph and shiny text.

    It’s not just a pretty face; that box also delivers some real-time performance statistics on the running program. Its actually a simple, bare-bones Javascript profiler. That’s right! Yo, I heard you like profiling, so I put a profiler in your movie, so that you can profile it while you watch.

    The graph tracks the Render Time, calculated by measuring how long each run of main() takes in milliseconds. Since this is the function that draws each frame of the animation, it’s effectively the animation’s frame rate. Each vertical blue line on the graph illustrates the time taken by one frame. The red horizontal line is the target speed, which we set at 33ms to match the video file frame rates. Just below the graph, the speed of the last call to main() is given in milliseconds.

    The profiler is also a handy browser rendering speed test. At the moment, the average render time in Firefox is 55ms, 90ms in IE 9, 41ms in Chrome, 148ms in Opera and 63ms in Safari. All the browsers were running on Windows XP, except for IE 9 which was profiled on Windows Vista.

    The next metric below that is Canvas FPS (canvas frames per second), obtained by counting how many times main() is called per second. The profiler displays the latest Canvas FPS rate when the video is still playing, and when it ends it shows the average speed of all calls to main().

    The last metric is Browser FPS, which measures how many the browser repaints the current window every second. This one is only available if you view the widget in Firefox, as it depends on a feature currently only available in that browser called window.mozPaintCount., a JavaScript property that keeps track of how many times the browser window has been repainted since the webpage first loaded.

    The repaints usually occur when an event or action that changes the look of a page occurs, like when you scroll down the page or mouse-over a link. It’s effectively the browser’s real frame rate, which is determined by how busy the current webpage is.

    To gauge what effect the un-optimized canvas animation had on mozPaintCount, I removed the canvas tag and all the JavaScript, so as to track the browser frame rate when playing just the video. My tests were done in Firebug’s console, using the function below:

    
    
    	var lastPaintCount = window.mozPaintCount;
    	setInterval( function(){
    		console.log( window.mozPaintCount - lastPaintCount );
    		lastPaintCount = window.mozPaintCount;
    	}, 1000);
    

    The results: The browser frame rate was between 30 and 32 FPS when the video was playing, and dropped to 0-1 FPS when the video ended. This means that Firefox was adjusting its window repaint frequency to match that of the playing video, encoded at 30fps. When the test was run with the un-optimized canvas animation and video playing together, it slowed down to 16fps, as the browser was now struggling to run all the JavaScript and still repaint its window on time, making both the video playback and canvas animations sluggish.

    We’ll now start tweaking our program, and as we do so, we’ll keep track of the Render Time, Canvas FPS and Browser FPS to measure the effects of our changes.


    Step 5: Use requestAnimationFrame()

    The last two JavaScript snippets above make use of the setTimeout() and setInterval() timer functions. To use these functions, you specify a time interval in milliseconds and the callback function you want executed after the time elapses. The difference between the two is that setTimeout() will call your function just once, while setInterval() calls it repeatedly.

    While these functions have always been indispensable tools in the JavaScript animator’s kit, they do have a few flaws:

    First, the time interval set is not always reliable. If the program is still in the middle of executing something else when the interval elapses, the callback function will be executed later than originally set, once the browser is no longer busy. In the main() function, we set the interval to 33 milliseconds – but as the profiler reveals, the function is actually called every 148 milliseconds in Opera.

    Second, there’s an issue with browser repaints. If we had a callback function that generated 20 animation frames per second while the browser repainted its window only 12 times a second, 8 calls to that function will be wasted as the user will never get to see the results.

    Finally, the browser has no way of knowing that the function being called is animating elements in the document. This means that if those elements scroll out of view, or the user clicks on another tab, the callback will still get executed repeatedly, wasting CPU cycles.

    Using requestAnimationFrame() solves most of these problems, and it can be used instead of the timer functions in HTML5 animations. Instead of specifying a time interval, requestAnimationFrame() synchronizes the function calls with browser window repaints. This results in more fluid, consistent animation as no frames are dropped, and the browser can make further internal optimizations knowing an animation is in progress.

    To replace setTimeout() with requestAnimationFrame in our widget, we first add the following line at the top of our script:

    
    
    requestAnimationFrame = window.requestAnimationFrame ||
    						window.mozRequestAnimationFrame ||
    						window.webkitRequestAnimationFrame ||
    						window.msRequestAnimationFrame ||
    						setTimeout;
    

    As the specification is still quite new, some browsers or browser versions have their own experimental implementations, this line makes sure that the function name points to the right method if it is available, and falls back to setTimeout() if not. Then in the main() function, we change this line:

    
    
    	setTimeout( main, frameDuration );
    

    …to:

    
    
    	requestAnimationFrame( main, canvas );
    

    The first parameter takes the callback function, which in this case is the main() function. The second parameter is optional, and specifies the DOM element that contains the animation. It is supposed to be used by to compute additional optimizations.

    Note that the getStats() function also uses a setTimeout(), but we leave that one in place since this particular function has nothing to do with animating the scene. requestAnimationFrame() was created specifically for animations, so if your callback function is not doing animation, you can still use setTimeout() or setInterval().


    Step 6: Use the Page Visibility API

    In the last step we made requestAnimationFrame power the canvas animation, and now we have a new problem. If we start running the widget, then minimize the browser window or switch to a new tab, the widget’s window repaint rate throttles down to save power. This also slows down the canvas animation since it is now synchronized with the repaint rate – which would be perfect if the video did not keep playing on to the end.

    We need a way to detect when the page is not being viewed so that we can pause the playing video; this is where the Page Visibility API comes to the rescue.

    The API contains a set of properties, functions and events we can use to detect if a webpage is in view or hidden. We can then add code that adjusts our program’s behavior accordingly. We will make use of this API to pause the widget’s playing video whenever the page is inactive.

    We start by adding a new event listener to our script:

    
    
    	document.addEventListener( 'visibilitychange', onVisibilityChange, false);
    

    Next comes the event handler function:

    
    
    // Adjusts the program behavior, based on whether the webpage is active or hidden
    function onVisibilityChange() {
    	if( document.hidden && !video.paused ){
    		video.pause();
    	}else  if( video.paused ){
    		video.play();
    	}
    }
    

    Step 7: For Custom Shapes, Draw the Whole Path At Once

    Paths are used to create and draw custom shapes and outlines on the <canvas> element, which will at all times have one active path.

    A path holds a list of sub-paths, and each sub-path is made up of canvas co-ordinate points linked together by either a line or a curve. All the path making and drawing functions are properties of the canvas’s context object, and can be classified into two groups.

    There are the subpath-making functions, used to define a subpath and include lineTo(), quadraticCurveTo(), bezierCurveTo(), and arc(). Then we have stroke() and fill(), the path/subpath drawing functions. Using stroke() will produce an outline, while fill() generates a shape filled by either a color, gradient or pattern.

    When drawing shapes and outline on the canvas, it is more efficient to create the whole path first, then just stroke() or fill() it once, rather than defining and drawing each supbath at a time. Taking the profiler’s graph described in Step 4 as an example, each single vertical blue line is a subpath, while all of them together make up the whole current path.

    The stroke() method is currently being called within a loop that defines each subpath:

    
    
    	mainContext.beginPath();
    	for( var j = 0; i < imax; i++, j += 2 ){
    		mainContext.moveTo( x + j, y ); // define the subpaths starting point
    		mainContext.lineTo( x + j, y - speedLog[i] * graphScale );	// set the subpath as a line, and define its endpoint
    		mainContext.stroke(); // draw the subpath to the canvas
    	}
    

    This graph can be drawn much more efficiently by first defining all the subpaths, then just drawing the whole current path at once, as shown below.

    
    
    	mainContext.beginPath();
    	for( var j = 0; i < imax; i++, j += 2 ){
    		mainContext.moveTo( x + j, y ); // define the subpaths starting point
    		mainContext.lineTo( x + j, y - speedLog[i] * graphScale );	// set the subpath as a line, and define its endpoint
    	}
    	mainContext.stroke(); // draw the whole current path to the mainCanvas.
    

    Step 8: Use an Off-Screen Canvas To Build the Scene

    This optimization technique is related to the one in the previous step, in that they are both based on the same principle of minimizing webpage repaints.

    Whenever something happens that changes a document’s look or content, the browser has to schedule a repaint operation soon after that to update the interface. Repaints can be an expensive operation in terms of CPU cycles and power, especially for dense pages with a lot of elements and animation going on. If you are building up a complex animation scene by adding up many items one at a time to the <canvas>, every new addition may just trigger a whole repaint.

    It is better and much faster to build the scene on an off screen (in memory) <canvas>, and once done, paint the whole scene just once to the onscreen, visible <canvas>.

    Just below the code that gets reference to the widget’s <canvas> and its context, we’ll add five new lines that create an off-screen canvas DOM object and match its dimensions with that of the original, visible <canvas>.

    
    
    	var mainCanvas = document.getElementById("mainCanvas"); // points to the on-screen, original HTML canvas element
    	var mainContext = mainCanvas.getContext('2d'); // the drawing context of the on-screen canvas element
    	var osCanvas = document.createElement("canvas"); // creates a new off-screen canvas element
    	var osContext = osCanvas.getContext('2d'); //the drawing context of the off-screen canvas element
    	osCanvas.width = mainCanvas.width; // match the off-screen canvas dimensions with that of #mainCanvas
    	osCanvas.height = mainCanvas.height;
    

    We’ll then do as search and replace in all the drawing functions for all references to “mainCanvas” and change that to “osCanvas”. References to “mainContext” will be replaced with “osContext”. Everything will now be drawn to the new off-screen canvas, instead of the original <canvas>.

    Finally, we add one more line to main() that paints what’s currently on the off-screen <canvas> into our original <canvas>.

    
    
    // As the scripts main function, it controls the pace of the animation
    function main(){
    	requestAnimationFrame( main, mainCanvas );
    	if( video.paused || video.currentTime > 59  ){ return; }
    
    	var now = new Date().getTime();
    	if( frameStartTime ){
    		speedLog.push( now - frameStartTime );
    	}
    	frameStartTime = now;
    	if( video.readyState < 2 ){ return; }
    
    	frameCount++;
    	osCanvas.width = osCanvas.width; //clear the offscreen canvas
    	drawBackground();
    	drawFilm();
    	drawDescription();
    	drawStats();
    	drawBlade();
    	drawTitle();
    	mainContext.drawImage( osCanvas, 0, 0 ); // copy the off-screen canvas graphics to the on-screen canvas
    }
    

    Step 9: Cache Paths As Bitmap Images Whenever Possible

    For many kinds of graphics, using drawImage() will be much faster than constructing the same image on canvas using paths. If you find that a large potion of your script is spent repeatedly drawing the same shapes and outlines over and over again, you may save the browser some work by caching the resulting graphic as a bitmap image, then painting it just once to the canvas whenever required using drawImage().

    There are two ways of doing this.

    The first is by creating an external image file as a JPG, GIF or PNG image, then loading it dynamically using JavaScript and copying it to your canvas. The one drawback of this method is the extra files your program will have to download from the network, but depending on the type of graphic or what your application does, this could actually be a good solution. The animation widget uses this method to load the spinning blade graphic, which would have been impossible to recreate using just the canvas path drawing functions.

    The second method involves just drawing the graphic once to an off-screen canvas rather than loading an external image. We will use this method to cache the title of the animation widget. We first create a variable to reference the new off-screen canvas element to be created. Its default value is set to false, so that we can tell whether or not an image cache has been created, and saved once the script starts running:

    
    
    	var titleCache = false; // points to an off-screen canvas used to cache the animation scene's title
    

    We then edit the drawTitle() function to first check whether the titleCache canvas image has been created. If it hasn’t, it creates an off-screen image and stores a reference to it in titleCache:

    
    
    // renders the canvas title
    function drawTitle(){
    	if( titleCache == false ){ // create and save the title image
    		titleCache = document.createElement('canvas');
    		titleCache.width = osCanvas.width;
    		titleCache.height = 25;
    
    		var context = titleCache.getContext('2d');
    		context.fillStyle = 'black';
    		context.fillRect( 0, 0, 368, 25 );
    		context.fillStyle = 'white';
    		context.font = "bold 21px Georgia";
    		context.fillText( "SINTEL", 10, 20 );
    	}
    
    	osContext.drawImage( titleCache, 0, 0 );
    }
    

    Step 10: Clear the Canvas With clearRect()

    The first step in drawing a new animation frame is to clear the canvas of the current one. This can be done by either resetting the width of the canvas element, or using the clearRect() function.

    Resetting the width has a side effect of also clearing the current canvas context back to its default state, which can slow things down. Using clearRect() is always the faster and better way to clear the canvas.

    In the main() function, we’ll change this:

    
    
    	osCanvas.width = osCanvas.width; //clear the off-screen canvas
    

    …to this:

    
    
    	osContext.clearRect( 0, 0, osCanvas.width, osCanvas.height ); //clear the offscreen canvas
    

    Step 11: Implement Layers

    If you’ve worked with image or video editing software like Gimp or Photoshop before, then you’re already familiar with the concept of layers, where an image is composed by stacking many images on top of one another, and each can be selected and edited separately.

    Applied to a canvas animation scene, each layer will be a separate canvas element, placed on top of each other using CSS to create the illusion of a single element. As an optimization technique, it works best when there is a clear distinction between foreground and background elements of a scene, with most of the action taking place in the foreground. The background can then be drawn on a canvas element that does not change much between animation frames, and the foreground on another more dynamic canvas element above it. This way, the whole scene doesn’t have to be redrawn again for each animation frame.

    Unfortunately, the animation widget is a good example of a scene where we cannot usefully apply this technique, since both the foreground and background elements are highly animated.


    Step 12: Update Only The Changing Areas of an Animation Scene

    This is another optimization technique that depends heavily on the animation’s scene composition. It can be used when the scene animation is concentrated around a particular rectangular region on the canvas. We could then clear and redraw just redraw that region.

    For example, the Sintel title remains unchanged throughout most of the animation, so we could leave that area intact when clearing the canvas for the next animation frame.

    To implement this technique, we replace the line that calls the title drawing function in main() with the following block:

    
    
    	if( titleCache == false ){ // If titleCache is false, the animation's title hasn't been drawn yet
    		drawTitle(); // we draw the title. This function will now be called just once, when the program starts
    		osContext.rect( 0, 25, osCanvas.width, osCanvas.height ); // this creates a path covering the area outside by the title
    		osContext.clip(); // we use the path to create a clipping region, that ignores the title's region
    	}
    

    Step 13: Minimize Sub-Pixel Rendering

    Sub-pixel rendering or anti-aliasing happens when the browser automatically applies graphic effects to remove jagged edges. It results in smoother looking images and animations, and is automatically activated whenever you specify fractional co-ordinates rather than whole number when drawing to the canvas.

    Right now there is no standard on exactly how it should be done, so subpixel rendering is a bit inconsistent across browsers in terms of the rendered output. It also slows down rendering speeds as the browser has to do some calculations to generate the effect. As canvas anti-aliasing cannot be directly turned off, the only way to get around it is by always using whole numbers in your drawing co-ordinates.

    We will use Math.floor() to ensure whole numbers in our script whenever applicable. For example, the following line in drawFilm():

    
    
    	punchX = sample.x + ( j * punchInterval ) + 5; // the x co-ordinate
    

    …is rewritten as:

    
    
    	punchX = sample.x + ( j * punchInterval ) + 5; // the x co-ordinate
    

    Step 14: Measure the Results

    We’ve looked at quite a few canvas animation optimization techniques, and it now time to review the results.

    This table shows the before and after average Render Times and Canvas FPS. We can see some significant improvements across all the browsers, though it’s only Chrome that really comes close to achieving our original goal of a maximum 33ms Render Time. This means there is still much work to be done to get that target.

    We could proceed by applying more general JavaScript optimization techniques, and if that still fails, maybe consider toning down the animation by removing some bells and whistles. But we won’t be looking at any of those other techniques today, as the focus here was on optimizations for <canvas> animation.

    The Canvas API is still quite new and growing every day, so keep experimenting, testing, exploring and sharing. Thanks for reading the tutorial.


  5. Daniel Albu says:
    June 29, 2012 at 10:12 am

    The web moves fast – so fast that our original EaselJS tutorial is already out of date! In this tutorial, you’ll learn how to use the newest CreateJS suite by creating a simple Pong clone.


    Final Result Preview

    Let’s take a look at the final result we will be working towards:

    The PONG game

    Click to play

    This tutorial is based on Carlos Yanez’s Create a Pong Game in HTML5 With EaselJS, which in turn built on his Getting Started With EaselJS guide. The graphics and sound effects are all taken from the former tutorial.


    Step 1: Create index.html

    This will be our main index.html file:

    
    
    <!DOCTYPE html>
    <html>
    	<head>
    		<title>Pong</title>
    
    		<style>/* Removes Mobile Highlight */ *{-webkit-tap-highlight-color: rgba(0, 0, 0, 0);}</style>
    
    		<script src="http://code.createjs.com/easeljs-0.4.2.min.js"></script&gt;
    		<script src="http://code.createjs.com/tweenjs-0.2.0.min.js"></script&gt;
    		<script src="http://code.createjs.com/soundjs-0.2.0.min.js"></script&gt;
    		<script src="http://code.createjs.com/preloadjs-0.1.0.min.js"></script&gt;
    		<script src="http://code.createjs.com/movieclip-0.4.1.min.js"></script&gt;
    		<script src="assets/soundjs.flashplugin-0.2.0.min.js"></script>
    		<script src="Main.js"></script>
    
    	</head>
    	<body onload="Main();">
    		<canvas id="PongStage" width="480" height="320"></canvas>
    	</body>
    </html>
    

    As you can see, it’s pretty short and consists mainly of loading the CreateJS libraries.

    Since the release of CreateJS (which basically bundles all the separate EaselJS libraries) we no longer have to download the JS files and host them on our website; the files are now placed in a CDN (Content Delivery Network) which allows us to load these files remotely as quickly as possible.

    Let’s review the code:

    
    
    <style>/* Removes Mobile Highlight */ *{-webkit-tap-highlight-color: rgba(0, 0, 0, 0);}</style>

    This line removes the mobile highlight which may appear when you trying to play the game on mobile. (The mobile highlight causes the canvas object to get highlighted and thus ignore your finger movements.)

    Next up, we have the loading of the CreateJS libraries:

    
    
    <script src="http://code.createjs.com/easeljs-0.4.2.min.js"></script&gt;
    		<script src="http://code.createjs.com/tweenjs-0.2.0.min.js"></script&gt;
    		<script src="http://code.createjs.com/soundjs-0.2.0.min.js"></script&gt;
    		<script src="http://code.createjs.com/preloadjs-0.1.0.min.js"></script&gt;
    		<script src="http://code.createjs.com/movieclip-0.4.1.min.js"></script&gt;
    

    This code loads the JS files from the CreateJS CDN and it basically allows us to use any of the CreateJS functions in our code

    Next, we will load the SoundJS Flash plugin, which provides sound support for browsers that don’t support HTML5 Audio. This is done by using a SWF (a Flash object) to load the sounds.

    
    
    <script src="assets/soundjs.flashplugin-0.2.0.min.js"></script>
    

    In this case we will not use the CDN; instead, we’ll download the SoundJS library from http://createjs.com/#!/SoundJS/download and place the soundjs.flashplugin-0.2.0.min.js and FlashAudioPlugin.swf files in a local folder named assets.

    Last among the JS files, we’ll load the Main.js file which will contain all the code to our game:

    
    
    <script src="Main.js"></script>
    

    Finally, let’s place a Canvas object on our stage.

    
    
    <body onload="Main();">
    		<canvas id="PongStage" width="480" height="320"></canvas>
    	</body>
    

    Now we can start working on the game code.


    Step 2: The Variables

    Our game code will be inside a file named Main.js, so create and save this now.

    First of all, let’s define variables for all the graphic objects in the game:

    
    
    var canvas; //Will be linked to the canvas in our index.html page
    var stage; //Is the equivalent of stage in AS3; we'll add "children" to it
    
    // Graphics
    //[Background]
    
    var bg; //The background graphic
    
    //[Title View]
    
    var main; //The Main Background
    var startB; //The Start button in the main menu
    var creditsB; //The credits button in the main menu
    
    //[Credits]
    
    var credits; //The Credits screen
    
    //[Game View]
    
    var player; //The player paddle graphic
    var ball; //The ball graphic
    var cpu; //The CPU paddle
    var win; //The winning popup
    var lose; //The losing popup
    

    I’ve added a comment for each variable so that you’ll know what we’ll be loading in that variable

    Next up, the scores:

    
    
    //[Score]
    
    var playerScore; //The main player score
    var cpuScore; //The CPU score
    var cpuSpeed=6; //The speed of the CPU paddle; the faster it is the harder the game is
    

    We’ll, need variables for the speed of the ball:

    
    
    // Variables
    
    var xSpeed = 5;
    var ySpeed = 5;
    

    You can change these values to whatever you want, if you’d like to make the game easier or harder.

    If you’re a Flash developer, you know that Flash’s onEnterFrame is very useful when creating games, as there are things that need to happen in every given frame. (If you’re not familiar with this idea, check out this article on the Game Loop.)

    We have an equivalent for onEnterFrame in CreateJS, and that is the ticker object, which can run code every fraction of a second. Let’s create the variable that will link to it:

    
    
    var tkr = new Object;
    

    Next we have the preloader, which will use the new PreloadJS methods.

    
    
    //preloader
    var preloader;
    var manifest;
    var totalLoaded = 0;
    
    • preloader – will contain the PreloadJS object.
    • manifest – will hold the list of files we need to load.
    • totalLoaded – this variable will hold the number of files already loaded.

    Last but not least in our list of variables, we have TitleView, which will hold several graphics within in order to display them together (like a Flash DisplayObjectContainer).

    
    
    var TitleView = new Container();
    

    Let’s move on to the Main function…


    Step 3: The Main() Function

    This function is the first function that runs after all the JS files from the index.html are loaded. But what’s calling this function?

    Well, remember this line from the index.html file?

    
    
    <body onload="Main();">
    

    This code snippet states that once the HTML (and JS libraries) are loaded, the Main function should run.

    Let’s review it:

    
    
    function Main()
    {
    	/* Link Canvas */
    
    	canvas = document.getElementById('PongStage');
      	stage = new Stage(canvas);
    
      	stage.mouseEventsEnabled = true;
    
    	/* Set The Flash Plugin for browsers that don't support SoundJS */
      	SoundJS.FlashPlugin.BASE_PATH = "assets/";
        if (!SoundJS.checkPlugin(true)) {
          alert("Error!");
          return;
        }
    
      	manifest = [
    				{src:"bg.png", id:"bg"},
    				{src:"main.png", id:"main"},
    				{src:"startB.png", id:"startB"},
    				{src:"creditsB.png", id:"creditsB"},
    				{src:"credits.png", id:"credits"},
    				{src:"paddle.png", id:"cpu"},
    				{src:"paddle.png", id:"player"},
    				{src:"ball.png", id:"ball"},
    				{src:"win.png", id:"win"},
    				{src:"lose.png", id:"lose"},
    				{src:"playerScore.mp3|playerScore.ogg", id:"playerScore"},
    				{src:"enemyScore.mp3|enemyScore.ogg", id:"enemyScore"},
    				{src:"hit.mp3|hit.ogg", id:"hit"},
    				{src:"wall.mp3|wall.ogg", id:"wall"}
    			];
    
      	preloader = new PreloadJS();
      	preloader.installPlugin(SoundJS);
        preloader.onProgress = handleProgress;
        preloader.onComplete = handleComplete;
        preloader.onFileLoad = handleFileLoad;
        preloader.loadManifest(manifest);
    
    	/* Ticker */
    
    	Ticker.setFPS(30);
    	Ticker.addListener(stage);
    }
    

    Let’s break down each part:

    
    
      	canvas = document.getElementById('PongStage');
      	stage = new Stage(canvas);
    
      	stage.mouseEventsEnabled = true;
    

    Here we link the PongStage Canvas object from the index.html file to the canvas variable, and then create a Stage object from that canvas. (The stage will allow us to place objects on it.)

    mouseEventsEnabled enables us to use mouse events, so we can detect mouse movements and clicks.

    
    
    /* Set The Flash Plugin for browsers that don't support SoundJS */
      	SoundJS.FlashPlugin.BASE_PATH = "assets/";
        if (!SoundJS.checkPlugin(true)) {
          alert("Error!");
          return;
        }
    

    Here we configure where the Flash sound plugin resides for those browsers in which HTML5 Audio is not supported

    
    
    	manifest = [
    				{src:"bg.png", id:"bg"},
    				{src:"main.png", id:"main"},
    				{src:"startB.png", id:"startB"},
    				{src:"creditsB.png", id:"creditsB"},
    				{src:"credits.png", id:"credits"},
    				{src:"paddle.png", id:"cpu"},
    				{src:"paddle.png", id:"player"},
    				{src:"ball.png", id:"ball"},
    				{src:"win.png", id:"win"},
    				{src:"lose.png", id:"lose"},
    				{src:"playerScore.mp3|playerScore.ogg", id:"playerScore"},
    				{src:"enemyScore.mp3|enemyScore.ogg", id:"enemyScore"},
    				{src:"hit.mp3|hit.ogg", id:"hit"},
    				{src:"wall.mp3|wall.ogg", id:"wall"}
    			];
    

    In the manifest variable we place an array of files we want to load (and provide a unique ID for each one). Each sound has two formats – MP3 and OGG – because different browsers are (in)compatible with different formats.

    
    
      	preloader = new PreloadJS();
      	preloader.installPlugin(SoundJS);
        preloader.onProgress = handleProgress;
        preloader.onComplete = handleComplete;
        preloader.onFileLoad = handleFileLoad;
        preloader.loadManifest(manifest);
    

    Here we configure the preloader object using PreloadJS. PreloadJS is a new addition to the CreateJS libraries and quite a useful one.

    We create a new PreloadJS object and place it in the preloader variable, then assign a method to each event (onProgress, onComplete, onFileLoad). Finally we use the preloader to load the manifest we created earlier.

    
    
    Ticker.setFPS(30);
    	Ticker.addListener(stage);
    

    Here we add the Ticker object to the stage and set the frame rate to 30 FPS; we’ll use it later in the game for the enterFrame functionality.


    Step 4: Creating the Preloader Functions

    
    
    function handleProgress(event)
    {
    	//use event.loaded to get the percentage of the loading
    }
    
    function handleComplete(event) {
             //triggered when all loading is complete
    }
    
    function handleFileLoad(event) {
             //triggered when an individual file completes loading
    
             switch(event.type)
             {
             	case PreloadJS.IMAGE:
             	//image loaded
             	 var img = new Image();
                  img.src = event.src;
                  img.onload = handleLoadComplete;
                  window[event.id] = new Bitmap(img);
             	break;
    
             	case PreloadJS.SOUND:
             	//sound loaded
             	handleLoadComplete();
             	break;
             }
    }
    

    Let’s review the functions:

    • handleProgress – In this function you’ll be able to follow the percentage of the loading progress using this parameter: event.loaded. You could use this to create for example a progress bar.
    • handleComplete – This function is called once all the files have been loaded (in case you want to place something there).
    • handleFileLoad – Since we load two types of files – images and sounds – we have this function that will handle each one separately. If it’s an image, we create a bitmap image and place it in a variable (whose name is the same as the ID of the loaded image) and then call the handleLoadComplete function (which we’ll write next); if it’s a sound then we just call the handleLoadComplete immediately.

    Now let’s discuss the handleLoadComplete function I just mentioned:

    
    
     function handleLoadComplete(event)
     {
    
    	totalLoaded++;
    
    	if(manifest.length==totalLoaded)
    	{
    		addTitleView();
    	}
     }
    

    It’s a pretty straightforward function; we increase the totalLoaded variable (that holds the number of assets loaded so far) and then we check if the number of items in our manifest is the same as the number of loaded assets, and if so, go to the Main Menu screen.


    Step 5: Creating the Main Menu

    The Main Menu
    
    
    function addTitleView()
    {
    	//console.log("Add Title View");
    	startB.x = 240 - 31.5;
    	startB.y = 160;
    	startB.name = 'startB';
    
    	creditsB.x = 241 - 42;
    	creditsB.y = 200;
    
    	TitleView.addChild(main, startB, creditsB);
    	stage.addChild(bg, TitleView);
    	stage.update();
    
    	// Button Listeners
    
    	startB.onPress = tweenTitleView;
    	creditsB.onPress = showCredits;
    

    Nothing special here. We place the images of the Background, Start Button and Credits Button on the stage and link onPress event handlers to the Start and Credits buttons.

    Here are the functions that display and remove the credits screen and the tweenTitleView which starts the game:

    
    
    function showCredits()
    {
    	// Show Credits
    
    	credits.x = 480;
    
    	stage.addChild(credits);
    	stage.update();
    	Tween.get(credits).to({x:0}, 300);
    	credits.onPress = hideCredits;
    }
    
    // Hide Credits
    
    function hideCredits(e)
    {
    	Tween.get(credits).to({x:480}, 300).call(rmvCredits);
    }
    
    // Remove Credits
    
    function rmvCredits()
    {
    	stage.removeChild(credits);
    }
    
    // Tween Title View
    
    function tweenTitleView()
    {
    	// Start Game
    
    	Tween.get(TitleView).to({y:-320}, 300).call(addGameView);
    }
    

    Step 6: The Game Code

    The PONG game

    We’ve reached the main part of this tutorial which is the code of the game itself.

    First of all, we need to add all the required assets to the stage, so we do that in the addGameView function:

    
    
    function addGameView()
    {
    	// Destroy Menu & Credits screen
    
    	stage.removeChild(TitleView);
    	TitleView = null;
    	credits = null;
    
    	// Add Game View
    
    	player.x = 2;
    	player.y = 160 - 37.5;
    	cpu.x = 480 - 25;
    	cpu.y = 160 - 37.5;
    	ball.x = 240 - 15;
    	ball.y = 160 - 15;
    
    	// Score
    
    	playerScore = new Text('0', 'bold 20px Arial', '#A3FF24');
    	playerScore.x = 211;
    	playerScore.y = 20;
    
    	cpuScore = new Text('0', 'bold 20px Arial', '#A3FF24');
    	cpuScore.x = 262;
    	cpuScore.y = 20;
    
    	stage.addChild(playerScore, cpuScore, player, cpu, ball);
    	stage.update();
    
    	// Start Listener 
    
    	bg.onPress = startGame;
    }
    

    Again, a pretty straightforward function that places the objects on the screen and adds a mouseEvent to the background image, so that when the user clicks it the game will start (we will call the startGame function).

    Let’s review the startGame function:

    
    
    function startGame(e)
    {
    	bg.onPress = null;
    	stage.onMouseMove = movePaddle;
    
    	Ticker.addListener(tkr, false);
    	tkr.tick = update;
    }
    

    Here, as you can see, in addition to adding an onMouseMove event that will move our paddle. We add the tick event, which will call the update function in each frame.

    Let’s review the movePaddle and reset functions:

    
    
    function movePaddle(e)
    {
    	// Mouse Movement
    	player.y = e.stageY;
    }
    
    /* Reset */
    
    function reset()
    {
    	ball.x = 240 - 15;
    	ball.y = 160 - 15;
    	player.y = 160 - 37.5;
    	cpu.y = 160 - 37.5;
    
    	stage.onMouseMove = null;
    	Ticker.removeListener(tkr);
    	bg.onPress = startGame;
    }
    

    In movePaddle, we basically place the user’s paddle at the mouse’s y-coordinate.

    In reset, we do something similar to addGameView, except here we don’t add any graphic elements since they are already on the screen.

    Using the alert function we’ll display the winning and losing popup:

    
    
    function alert(e)
    {
    	Ticker.removeListener(tkr);
    	stage.onMouseMove = null;
    	bg.onPress = null
    
    	if(e == 'win')
    	{
    		win.x = 140;
    		win.y = -90;
    
    		stage.addChild(win);
    		Tween.get(win).to({y: 115}, 300);
    	}
    	else
    	{
    		lose.x = 140;
    		lose.y = -90;
    
    		stage.addChild(lose);
    		Tween.get(lose).to({y: 115}, 300);
    	}
    }
    

    Step 7: The Game Loop

    Now, for the last part of our tutorial we’ll work on the update function (which occurs in every frame of the game – similar to Flash’s onEnterFrame):

    
    
    function update()
    {
    	// Ball Movement 
    
    	ball.x = ball.x + xSpeed;
    	ball.y = ball.y + ySpeed;
    
    	// Cpu Movement
    
    	if(cpu.y < ball.y) {
    		cpu.y = cpu.y + 4;
    	}
    	else if(cpu.y > ball.y) {
    		cpu.y = cpu.y - 4;
    	}
    
    	// Wall Collision 
    
    	if((ball.y) < 0) { ySpeed = -ySpeed; SoundJS.play('wall'); };//Up
    	if((ball.y + (30)) > 320) { ySpeed = -ySpeed; SoundJS.play('wall');};//down
    
    	/* CPU Score */
    
    	if((ball.x) < 0)
    	{
    		xSpeed = -xSpeed;
    		cpuScore.text = parseInt(cpuScore.text + 1);
    		reset();
    		SoundJS.play('enemyScore');
    	}
    
    	/* Player Score */
    
    	if((ball.x + (30)) > 480)
    	{
    		xSpeed = -xSpeed;
    		playerScore.text = parseInt(playerScore.text + 1);
    		reset();
    		SoundJS.play('playerScore');
    	}
    
    	/* Cpu collision */
    
    	if(ball.x + 30 > cpu.x && ball.x + 30 < cpu.x + 22 && ball.y >= cpu.y && ball.y < cpu.y + 75)
    	{
    		xSpeed *= -1;
    		SoundJS.play('hit');
    	}
    
    	/* Player collision */
    
    	if(ball.x <= player.x + 22 && ball.x > player.x && ball.y >= player.y && ball.y < player.y + 75)
    	{
    		xSpeed *= -1;
    		SoundJS.play('hit');
    	}
    
    	/* Stop Paddle from going out of canvas */
    
    	if(player.y >= 249)
    	{
    		player.y = 249;
    	}
    
    	/* Check for Win */
    
    	if(playerScore.text == '10')
    	{
    		alert('win');
    	}
    
    	/* Check for Game Over */
    
    	if(cpuScore.text == '10')
    	{
    		alert('lose');
    	}
    }
    

    Looks scary, doesn’t it? Don’t worry, we’ll review each part and discuss it.

    
    
    	// Ball Movement 
    
    	ball.x = ball.x + xSpeed;
    	ball.y = ball.y + ySpeed;
    

    In each frame, the ball will move according to its x and y speed values

    
    
    // Cpu Movement
    
    	if((cpu.y+32) < (ball.y-14)) {
    		cpu.y = cpu.y + cpuSpeed;
    	}
    	else if((cpu.y+32) > (ball.y+14)) {
    		cpu.y = cpu.y - cpuSpeed;
    	}
    

    Here we have the basic AI of the computer, in which the computer’s paddle simply follows the ball without any special logic. We just compare the location of the center of the paddle (which is why we add 32 pixels to the cpu Y value) to the location of the ball, with a small offset, and move the paddle up or down as necessary.

    
    
    if((ball.y) < 0) { //top
    	ySpeed = -ySpeed;
    	SoundJS.play('wall');
    };
    if((ball.y + (30)) > 320) { //bottom
    	ySpeed = -ySpeed;
    	SoundJS.play('wall');
    };
    

    If the ball hits the top border or the bottom border of the screen, the ball changes direction and we play the Wall Hit sound.

    
    
     	/* CPU Score */
     	if((ball.x) < 0)
     	{
     		xSpeed = -xSpeed;
     		cpuScore.text = parseInt(cpuScore.text + 1);
     		reset();
     		SoundJS.play('enemyScore');
     	}
     	/* Player Score */
      	if((ball.x + (30)) > 480)
     	{
     		xSpeed = -xSpeed;
     		playerScore.text = parseInt(playerScore.text + 1);
     		reset();
     		SoundJS.play('playerScore');
     	}
    

    The score login is simple: if the ball passes the left or right borders it increases the score of the player or CPU respectively, plays a sound, and resets the location of the objects using the reset function we’ve discussed earlier.

    
    
    /* CPU collision */
    if(ball.x + 30 > cpu.x && ball.x + 30 < cpu.x + 22 && ball.y >= cpu.y && ball.y < cpu.y + 75)
    {
    	xSpeed *= -1;
    	SoundJS.play('hit');
    }
    /* Player collision */
    if(ball.x <= player.x + 22 && ball.x > player.x && ball.y >= player.y && ball.y < player.y + 75)
    {
     	xSpeed *= -1;
     	SoundJS.play('hit');
     }
    

    Here we deal with collisions of the ball with the paddles; every time the ball hits one of the paddles, the ball changes direction and a sound is played

    
    
     	if(player.y >= 249)
     	{
     		player.y = 249;
     	}
    

    If the player’s paddle goes out of bounds, we place it back within the bounds.

    
    
     /* Check for Win */
     if(playerScore.text == '10')
     {
     	alert('win');
    }
    /* Check for Game Over */
    if(cpuScore.text == '10')
    {
     	alert('lose');
    }
    

    In this snippet, we check whether either of the players’ score has reached 10 points, and if so we display the winning or losing popup to the player (according to his winning status).


    Conclusion

    That’s it, you’ve created an entire pong game using CreateJS. Thank you for taking the time to read this tutorial.


  6. Sebastian Bratu says:
    June 29, 2012 at 10:46 am

    In this mini-series, exclusive to Tuts+ Premium members, you’ll learn how to use Flash to build a Facebook Graph API application that can create slideshows for your public pages. The final part shows you how to actually retrieve and display the information from Facebook.


    Premium Preview

    Click to try the app on Facebook.

    This application allows you to select a Facebook album or event list from one of your public pages and turn it into a slideshow for your page tab. When the users enter your page, they will see photos from your chosen album, with your photo title and description, or event name, date and invites (for the event tab).

    In the previous part of this series, we created the event slider generator. In this part we’ll make the actual slider for the images (and later, for the events).

    You’ll need to be logged in to Facebook in order to see this demo: https://apps.facebook.com/activetuts_tabmaker/


    Read the Full Tutorial

    Premium members can access the full tutorial right away!

    If you’re not yet a Premium member, you can still read the first few steps for free.


    Tuts+ Premium Membership

    We run a Premium membership system which periodically gives members access to extra tutorials, like this one, from across the whole Tuts+ network. If you’re a Premium member, you can log in and read the tutorial. If you’re not a member, you can of course join today!

    Also, don’t forget to follow @envatoactive on twitter, circle us on Google+, like us on Facebook, and grab the Activetuts+ RSS Feed to stay up to date with the latest tutorials and articles.


  7. Porter says:
    June 29, 2012 at 11:35 am

    Earlier today, Wilson Lim showed you how to create a gravity-based game called Flux. In this Workshop, Matt Porter critiques Flux, explaining what it would take to turn that simple demo into a real game.


    Play the Game

    Use the left and right arrow keys to manoeuvre your ship, the up and down arrow keys to increase or reduce the size of the magnetic field it produces, and the space bar to reverse the polarity. Collect the white crystals to increase your fuel supply – but avoid the red ones, because they use it up. Don’t hit a rock, or it’s game over.

    Please bear in mind that this demo was created specifically for a tutorial, rather than for release on a Flash portal, so it’s naturally less polished than games we’ve featured in past critiques.


    Introduction

    Flux is a barebones game. It has one core mechanic, and very basic controls. That being said, even the most basic aspects of a game can require careful balance. With a few small tweaks, we can make something that’s simple and frustrating into something that might not necessarily be a blast, but will be a much smoother and more enjoyable experience.

    The core aim of Flux is to sustain energy for your ship by collecting white crystals, while at the same time avoiding red crystals. In addition, you must also avoid rocks, which end your game immediately upon contact. To mix things up a bit, the ship is equipped with a magnet of sorts, that can attract or deflect the negative crystals, but has no effect on the rocks of instant doom.

    You can move your ship horizontally, but not vertically, using the left and right arrow keys. The last bit of spice in this otherwise currently bland game is that you can increase or decrease your magnet’s area of effect, by pressing the up and down arrow keys respectively.

    So there you have it, that’s Flux. While there’s very little to this game, we’re about to break it down into more than the average eyes see, and come up with some simple, yet game changing, alterations.


    Getting Started

    The first and most immediate flaw in Flux is that there isn’t really a title screen.

    Flux’s starting screen

    There’s no instructions, no place to check high score, no title, no music… you’re just tossed onto a bland screen with a Start Game button. Pretty bad start, but okay, let’s move on.

    Upon pressing the button, we now see our ship, and some objects in our face. Let’s just assume that we know what to do right off, and that there is a rock (instant death if it hits us) coming right at us (that’ll happen when positions are 100% random). We quickly get our hands onto the keyboard (we started using the mouse, and there were no instructions, so we’re not actually prepared for this), and attempt to dodge the rock.

    Oh no, our ship isn’t moving! Does WASD not work? Well, actually, they don’t work (which is a horrible decision, as WASD and arrow keys should always both be supported where possible) – but believe it or not, that’s not our issue either.

    The real issue is that the game area doesn’t have focus. We actually need to click the player area to gain control, even though we just pressed the Start Game button. Looks like we just blew up from an oncoming rock. So here we are, literally five seconds into the game, and all we’ve done is see a bland title screen and die from absolute unfairness. Congratulations, you’ve just lost the majority of all your players right off, and most of them have down-voted your game if it’s being played on a major portal such as Newgrounds or Kongregate.

    A likely response from a Newgrounds gamer

    While the above is an absolute mess, it’s actually quite easily fixed.

    Pixel Purge‘s title screen, for comparison

    First off, we add a simple title screen. The quality can range greatly, but at the very least, we need a title, a play button, and something related to scores – whether it’s a list already on screen, or a button to let us view them all.

    Next, we make sure that the play area has keyboard focus after the Start Game button is pressed. If this were my game, I would then choose to display the controls of the game to the player through pictures and text, and not just a wall of text. For good measure, I’d save a variable to a shared object that says the player has seen the controls, and I would never display them at the start of a game again (unless a “delete all data” button was pressed).

    Now that the player has a good initial first impression, with a decent menu, and controls shown to them, we’d start the game. Here I would make sure that the game didn’t actually start until the player moved the ship. This would accomplish two things: first, we’d know that they have their hands on the keyboard and are ready to play; and second, they wouldn’t die from a randomly generated flying space rock within the first two seconds of the game.

    Nothing that I just listed above is hard, but it’s just changed that poor initial first impression of this game to “this has potential, let’s see what happens”.


    Gameplay

    Now that we’ve taken care of analyzing the first impression, let’s focus a bit on the actual gameplay.

    Flux’s play screen

    The first thing I noticed when playing Flux, is that the movement was extremely stiff, and felt very amateur. It’s obvious that the movement is locked to a set speed, and that there’s no acceleration or easing. If we were to add some of that then not only would the game feel better and look more smooth, but our control would be far more precise, making for a much more enjoyable experience.

    The magnet mechanic is actually pretty neat, but it’s a bit rough around the edges. The first thing I noticed, is that there are no restrictions on how big or small the attract radius can be. This allows us to go negative, and eventually appear to be positive again, but the magnet won’t actually do anything. This could leave various impressions on the player, from them being confused to them thinking the game looks unprofessional, so it’s important that we put restrictions in place.


    One More Time

    Assuming that players actually have fun with the game the way it is (admittedly doubtful beyond the first play or two), we still have some fixing up to do. When the player dies, they aren’t really left with any incentive to play again. The game over screen should be used as an opportunity to tempt the player to play again – and simply having a button to let them do so is not what I mean.

    Flux’s game over screen

    In this case, the game over screen should still show the player’s score, but also their all-time best score. If their previous play was their best, this should be related to the player both visually and audibly.

    Pixel Purge’s game over screen, for comparison

    If we wanted to take things even further, we’d toss in Facebook / Twitter buttons, and allow the player to brag about their accomplishment with friends.


    What Else?

    As I’ve mentioned, even with the critical flaws fixed, and the controls a bit polished, the game is still a bit boring. While there are hundreds if not thousands of directions in which to take a game this basic, I’ll just focus on some of the simpler yet still effective changes.

    The first addition I would add is powerups. We’ve already got collision code we use for collecting crystals, so adding powerups is not that hard from a technical standpoint. For example, we could add a powerup that turns every red crystal into a white one. With a cool visual effect, and an awesome sound effect, grabbing one of these would be quite rewarding.

    The next thing I would do, is add crystals of different sizes, where the bigger the crystal, the harder it is to attract or repel. Give the larger crystals a higher score value, and a more rewarding sound, and you’ve now got some substance to your game. You’ll find players act extra risky around instant-kill death rocks, just so they can attempt to pull in a giant white crystal.

    Speaking of instant-kill death rocks, why not add a way to get rid of them? With the simple press of a button (say, the X key), let the player shoot directly ahead – for a cost. To make the game more interesting, firing your weapon would require some of your energy, so it would have to be used sparingly. We could also add a powerup that explodes all rocks on the screen, or that makes the player invincible so that they can hit them without worry for a limited time.

    If I really wanted to add a level of complexity to the game, I’d make it so that all crystals gained would be stored as currency, and after each game (or level), the player could spend those points on upgrading stats. These stats could range from maximum magnet radius, to increased energy regeneration from white crystals; the possibilities are nearly endless.

    All of the biggest remaining issues are related to polish, and as many developers will tell you, this can take a long time to get right.

    Some of the more major aspects of polish that are needed are as follows:

    • The Times New Roman font needs to be replaced.
    • The game needs consistent audio toggle buttons (to be found on all screens).
    • More visual effects are needed to increase the graphical quality.
    • The game needs to be 100% audio complete, with both sounds and music.

    Conclusion

    As you can see, it didn’t take too much to really rip this game apart, and then point out some simple but effective ways to fix it up.

    There are enormous benefits to being able to fix up such a basic game. In reality, everything that Flux has is no larger or more complex than one individual portion of any other larger game. If we look at game development like this, we then see the benefit of being able to fix up such a simple game. We’re essentially able to view our bigger projects as small pieces, and we can then polish each piece up individually until it’s a smooth and enjoyable experience on its own. In the end, we’ll be left with a full-fledged game, comprised of many small, extremely well built pieces.

    What do you think should be added to Flux? Post your suggestions in the comments – or you could even follow the tutorial and make the changes yourself…


  8. Wilson Lim says:
    June 29, 2012 at 12:33 pm

    In this tutorial, I’ll explain the major steps and workflow for creating a simple space survival game, based on the gravity mechanic explained in a previous tutorial. This game is written in AS3 using FlashDevelop.


    Play the Game

    Use the left and right arrow keys to manoeuvre your ship, the up and down arrow keys to increase or reduce the size of the magnetic field it produces, and the space bar to reverse the polarity. Collect the white crystals to increase your fuel supply – but avoid the red ones, because they use it up. Don’t hit a rock, or it’s game over!

    In this tutorial, we won’t actually create the full game displayed above; we’ll just get started on it, by making a very simple version with primitive graphics and just one type of object. However, by the end, you should have learned enough to be able to add the other features yourself!

    The game itself is very simple in its current state – take a look at this critique for tips on how you can take it from a simple demo to a full game!


    Let’s Get Started!

    Set up a new AS3 project in FlashDevelop, and set its dimensions to 550x600px.

    
    
     package
    {
    	[SWF(width = "550", height = "600")]
    
    	public class Main extends Sprite
    	{
    
    	}
    }
    

    Step 1: Identifying the Game Objects

    There are six objects in particle that you can identify from playing the game above:

    • Energy supply – represented by an white oval shape object
    • Asteroid – represented by a rock-like object
    • Energy consumer – represented by a red star bounded with green light.
    • Stars – the background
    • Range indicator – represented by a white circle
    • Ship – player object

    Of course you can add in any other object to make the game more interactive or add a new feature. For this tutorial we’ll just make


    Step 2: The Energy Class

    From the objects we identified, four of them actually work in exactly the same way: by falling from top to bottom.

    They are:

    • Stars
    • Energy supply
    • Energy consumer
    • Asteroid

    In this tutorial, we’re only going to make the “energy supply” objects, out of the four above. So let’s begin by creating these objects and making them fall down, with a random spawning position and speed.

    Start by creating an Energy class:

    
    
    	package
    	{
    		import flash.display.MovieClip;
    		import flash.events.Event;
    
    		public class Energy extends MovieClip
    		{
    			private var rSpeed:Number = 0;
    
    			public function Energy(speed:Number)
    			{
    				graphics.beginFill(0x321312);
    				graphics.drawCircle(0, 0 , 8);
    
    				rSpeed = speed;
    			}
    
    			// we will call this every frame
    			public function move():void
    			{
    				this.y += rSpeed;
    				//rotation speed is linked to moving speed
    				this.rotation += rSpeed / 8;
    			}
    		}
    	}
    

    Step 3: The GameScreen Class

    This class will eventually control most of the aspects of our game, including the player movement and the game loop.

    Create the class:

    
    
    package
    {
    
    	public class GameScreen extends MovieClip
    	{
    
    		public function GameScreen()
    		{
    
    		}
    	}
    }
    

    That’s all we need for now.


    Step 4: Update The Main Class

    We’ll now create an instance of GameScreen within Main:

    
    
    package
    {
    	import flash.display.Sprite;
    	import flash.events.Event;
    
    	[SWF(width = "550", height = "600")]
    
    	public class Main extends Sprite
    	{
    		private var game:GameScreen;
    
    		public function Main():void
    		{
    			// don't display a yellow rectangle on the screen at startup
    			stage.stageFocusRect = false;
    
    			game = new GameScreen();
    			addChild(game);
    
    			// give keyboard focus to the game screen immediately
    			stage.focus = game;
    		}
    	}
    }
    

    Why bother? Well, this way, it’ll be easier to add extra screens later if we want to (like a preloader, a title screen, a game over screen…).


    Step 5: Introducing a Manager Class

    To avoid the GameScreen class becoming too much of a mess, we’ll use separate classes to manage each object.

    Each manager class will contain all the functions that relate to, and interact with, a particular object. Here’s the EnergyManager class:

    
    
    package
    {
    	import flash.display.MovieClip;
    
    	public class EnergyManager
    	{
    		// this Vector will store all instances of the Energy class
    		private var energyList:Vector.<Energy>
    		private var gameScreen:GameScreen;
    
    		public function EnergyManager(gs:GameScreen)
    		{
    			gameScreen = gs;
    			energyList = new Vector.<Energy>;
    		}
    	}
    }
    

    Note that we require a reference to the GameScreen to be passed to the constructor, and we store this reference in a private variable. We also set up a Vector to store references to all the energy objects.

    So far the class contain no other functions; we will add them in later.


    Step 6: Creating Energy

    Add the below function for creating energy, this is just a function; we will call the function later from GameScreen Class:

    
    
    	public function createEnergy(number:int):void
    	{
    		var energy:Energy;
    		for (var i:int = 0; i < number; i++) {		
    
    			energy = new Energy(4);				
    
    			gameScreen.addEnergyToScreen(energy);
    
    			energyList.push(energy);				
    
    			energy.x = Calculation.generateRandomValue(30, 520);
    			energy.y = Calculation.generateRandomValue( -150, -20);
    		}
    	}
    

    We create a new energy supply with a speed of 4, add it to the display list (via the GameScreen), add it to the Vector of all energy objects that we just created, and set its position to a random point within certain bounds.

    The Calculation.generateRandomValue(#, #) is a static function we haven’t written yet, so let’s do that now. Create a new class called Calculation and add this function:

    
    
    	public static function generateRandomValue(min:Number, max:Number):Number
    	{
    		var randomValue:Number = min + (Math.random() * (max - min));
    
    		return randomValue;
    	}
    

    This function will generate a random number between the two values passed to it. For more information on how it works, see this Quick Tip. Since this is a static function, we don’t need to create an instance of Calculation in order to call it.

    Now, what’s that addEnergyToScreen() function? We haven’t defined that yet, so let’s do it now. Add this to GameScreen:

    
    
    		public function addEnergyToScreen(energy:Energy):void
    		{
    			addChild(energy);
    		}
    

    It just adds the passed instance of energy to the display list. Let’s also make a corresponding function to remove a given energy object from the screen:

    
    
    		public function removeEnergyFromScreen(energy:Energy):void
    		{
    			if (energy.parent == this)
    			{
    				removeChild(energy);
    			}
    		}
    

    Step 7: Spawning Energy

    Let’s set a timer that defines the interval for each spawning. This code goes in GameScreen‘s constructor function:

    
    
    energyM = new EnergyManager(this);	//remember to pass a reference to the game screen
    
    var spawnTimer:Timer = new Timer(3000, 0);
    spawnTimer.addEventListener(TimerEvent.TIMER, spawnEnergy);
    spawnTimer.start();
    

    So, every three seconds, the timer will call spawnEnergy(). Let’s write that function now:

    
    
    	private function spawnEnergy(e:TimerEvent):void
    	{
    		energyM.createEnergy(4);    // create 4 energies
    	}
    

    Step 8: Creating Player

    Let’s use another, bigger circle to represent the player. Feel free to import an image to use instead:

    
    
    public function Player()
    		{
    			graphics.beginFill(0x7ebff1);
    			graphics.drawCircle(0, 0, 20);
    

    Add this code to GameScreen to add the player to the screen:

    
    
    // in the variable definitions
    public var player:Player;
    
    
    
    // in the constructor function
    player = new Player;
    addChild(player);
    player.x = 275;
    player.y = 450;
    

    So far we should have a few energy supplies falling few seconds, and the player appearing in the middle of the screen:

    playerandenergy.

    Step 9: Moving the Player

    There are basically two ways to apply movement:

    1. Using Boolean (true/false) values – true = moving, false = not moving. When the right arrow key is pressed, the value for “moving right” will change to true. In each frame update, “moving right” is true, we increase the object’s x-value.
    2. Using direct update each frame – when the right arrow key is pressed, an object is told to move right immediately, by increasing its x-value.

    The second method does not lead to smooth movement when the key is continuously pressed, but the first method does – so we shall use the first method.

    There are three simple steps to doing this:

    1. Create two Boolean variables, one for moving right and one for moving left.
      
      
      	private var moveRight:Boolean = false;
      	private var moveLeft:Boolean = false;
      	
    2. Toggle the Boolean when keys are pressed or released:
      
      
      		addEventListener(Event.ENTER_FRAME, update);
      		addEventListener(KeyboardEvent.KEY_DOWN, KeyDownHandler);
      		addEventListener(KeyboardEvent.KEY_UP, KeyUpHandler);
      	}
      
      	private function KeyDownHandler(e:KeyboardEvent):void
      	{
      		if (e.keyCode == Keyboard.RIGHT) {
      			moveRight = true;
      		}
      		if (e.keyCode == Keyboard.LEFT) {
      			moveLeft = true;
      		}
      		if (e.keyCode == Keyboard.SPACE) {
      			if (isGravityPushing == true) {
      				isGravityPushing = false;
      			} else  {
      				isGravityPushing = true;
      			}
      		}
      	}
      
      	private function KeyUpHandler(e:KeyboardEvent):void
      	{
      		if (e.keyCode == Keyboard.RIGHT) {
      			moveRight = false;
      		}
      		if (e.keyCode == Keyboard.LEFT) {
      			moveLeft = false;
      		}
      	}
      	
    3. Based on these Booleans, actually move the player every frame:

      Don’t forget to first create a function listen from the enter frame event, “updating” :

      
      
      //call this function every frame
      private function update(e:Event):void
      	if (moveRight == true) {
      		player.x += 6;
      	}
      	if (moveLeft == true) {
      		player.x -= 6;
      	}
      	

      Keep the player within the bounds of the screen:

      
      
      	if (player.x >= 525) {
      		moveRight = false;
      	}
      	if (player.x <= 20) {
      		moveLeft = false;
      	}
      	

    Here’s how all that looks, in place:

    
    
    package
    {
        import flash.display.MovieClip;
        import flash.events.Event;
        import flash.events.TimerEvent;
        import flash.ui.Keyboard;
        import flash.utils.Timer;
        import flash.events.KeyboardEvent;
    
        public class GameScreen
        {
            public var player:Player;
    
            private var energyM:EnergyManager;
    
            private var moveRight:Boolean = false;
            private var moveLeft:Boolean = false;
            private var isGravityPushing:Boolean = true;
    
            private var returnedPower:int = 0;
    
            private var scoreText:Text;
            private var totalScore:int=0;
            private var score:Text;
    
            public function GameScreen()
            {
                scoreText = new Text("Score :");
                addChild(scoreText);
    
                energyM = new EnergyManager;
    
                var spawnTimer:Timer = new Timer(3000, 0);
                spawnTimer.addEventListener(TimerEvent.TIMER, spawnEnergy);
                spawnTimer.start();
    
                player = new Player;
                addChild(player);
                player.x = 275;
                player.y = 450;
    
                addEventListener(Event.ENTER_FRAME, update);
                addEventListener(KeyboardEvent.KEY_DOWN, KeyDownHandler);
                addEventListener(KeyboardEvent.KEY_UP, KeyUpHandler);
            }
    
    	private function KeyDownHandler(e:KeyboardEvent):void
    	{
    		if (e.keyCode == Keyboard.RIGHT) {
    			moveRight = true;
    		}
    		if (e.keyCode == Keyboard.LEFT) {
    			moveLeft = true;
    		}
    		if (e.keyCode == Keyboard.SPACE) {
    			if (isGravityPushing == true) {
    				isGravityPushing = false;
    			}else if (isGravityPushing == false) {
    				isGravityPushing = true;
    			}
    		}
    	}
    
    	private function KeyUpHandler(e:KeyboardEvent):void
    	{
    		if (e.keyCode == Keyboard.RIGHT) {
    			moveRight = false;
    		}
    		if (e.keyCode == Keyboard.LEFT) {
    			moveLeft = false;
    		}
    	}
    
    	private function update(e:Event):void
    	{
    		if (player.x >= 525) {
    			moveRight = false;
    		}
    		if (player.x <= 20) {
    			moveLeft = false;
    		}
    		if (moveRight == true) {
    			player.x += 6;
    		}
    		if (moveLeft == true) {
    			player.x -= 6;
    		}
    	}
        }
    }
    

    Step 10: Move the Energy Supplies

    At the moment, the energy supplies are spawning but not moving. We’ll use the GameScreen.update() function to make them move, since it runs every frame.

    Add this code to GameScreen.update():

    
    
    			energyM.moveAll();  // will make every energy object move
    

    Now of course we need to make the EnergyManager.moveAll() function, so add this to EnergyManager.as:

    
    
    		public function moveAll():void
    		{
    			for (var i:int = 0; i < energyList.length; i++) {
    				var energyS:Energy = energyList[i];
    				energyS.move();
    			}
    		}
    

    Step 10: Collision Detection

    We will need to check for collisions between each energy object and the player. (If you develop the game further, you’ll need to check this for asteroids and energy consumers, but not for stars.)

    The best place to handle these checks is inside the EnergyManager, triggered every frame by the GameScreen.

    One thing to consider: the collision checks will be between two circles, so hitTestObject() is not ideal. Instead, we’ll be using the method explained in this tutorial.

    We can write the function as below:

    
    
    	public function checkCollision(p:Player):int
    	{
    		// energy transferred due to collision
    		var energyTransfer:int = 0;
    
    		for (var i:int = 0; i < energyList.length; i++) {
    			var energyS:Energy = energyList[i];
    
    			var newX:Number = p.x - energyS.x;
    			var newY:Number = p.y - energyS.y;
    
    			var distance:Number = Math.sqrt(newX * newX + newY * newY);
    
    			if (distance <= 28) {
    				gameScreen.removeEnergyFromScreen(energyS);
    				energyList.splice(i, 1);
    				// for this simple game, we'll always transfer 1 unit
    				// but you could alter this based on speed of collision
    				// or any other factor
    				energyTransfer = 1;
    			}
    		}
    		return energyTransfer;
    	}
    
    • Line 32: note that we pass in a reference to the player, so that we can access its position.
    • Line 38: EnergyS is short for Energy Supply.
    • Line 40 & 41: finding the difference in x- and y-coordinates between the player and the energy supply we are currently checking.
    • Line 43: calculate the distance between the objects via Pythagoras.
    • Line 45: check for collision; 28 is the sum of the two objects’ radii (player radius is 20, energy radius is 8).
    • Line 46 & 47: remove energy supply from screen and from Vector.
    • Line 51: add a maximum of one unit of energy per frame.

    You could alter Line 51 to energyTransfer += 1, to allow the player to absorb more than one energy object at once. It’s up to you – try it out and see how it affects the game.


    Step 11: Call Collision Detection Routine

    We need to check for collisions every frame, so we should call the function we just wrote from GameScreen.update().

    First, we need to create an integer variable to store the energy transfer value from the collision detection function. We’ll use this value for increasing the ship’s energy and adding to the player’s score.

    
    
    private var returnedPower:int = 0;
    
    
    
    returnedPower = energyM.checkCollision(player);
    

    Step 12: Newton’s Law of Gravitation

    Before we go into creating the game mechanic for the ‘Push’ and ‘Pull’ function of the ship, I would like to introduce the physics concept on which the mechanic is based.

    The idea is to attract the object towards the player by means of a force. Newton’s Law of Universal Gravitation gives us a great (and simple) mathematical formula we can use for this, where the force is of course the gravitational force:

    G is just a number, and we can set it to whatever we like. Similarly, we can set the masses of each object in the game to any values that we like. Gravity occurs across infinite distances, but in our game, we’ll have a cut-off point (denoted by the white circle in the demo from the start of the tutorial).

    The two most important things to note about this formula are:

    • The strength of the force depends on the square of the distance between the two objects (so if the objects are twice as far away, the force is one-quarter as strong).
    • The direction of the force is along the direct line connecting the two objects through space.

    Step 13: Revising Math Concepts

    Before we start coding the game mechanics for the ‘Push’ and ‘Pull’ function, let’s be clear on what we want it to do:

    frameWork

    Essentially, we want A (the player) to exert a certain force on B (a crystal), and move B towards A based on that force.

    We should revise a few concepts:

    • Flash works in radians rather than degrees.
    • Flash’s coordinate system has its y-axis reversed: going down means an increase in y.
    • We can get the angle of the line connecting A to B using Math.atan2(B.y - A.y, B.x - A.x).
    • We can use trigonometry to figure out how much we need to move B along each axis, based on this angle and the force:
      • B.x += (Force*Math.cos(angle));
      • B.y += (Force*Math.sin(angle));
    • We can use Pythagoras’s theorem to figure out the distance between the two objects:

    For more information, see the tutorials Gravity in Action and Trigonometry for Flash Game Developers.


    Step 14: Implementing Push and Pull

    Based on the previous explanation, we can come up with an outline for our code that attracts each crystal to the ship:

    1. Find the difference in x and y between the ship and a given crystal.
    2. Find the angle between them, in radians.
    3. Find the distance between them, using Pythagoras.
    4. Check whether object is within the ship’s gravitational field.
    5. If so, calculate the gravitational force, and…
    6. …apply the force, changing the x and y values of the crystal.

    Sample Code:

    
    
    	public function gravityPull(p:Player): void
    	{
    		for (var i:int = 0; i < energyList.length; i++) {
    			var energyS:Energy = energyList[i];
    
    			var nX:Number = (p.x - energyS.x);
    			var nY:Number = (p.y - energyS.y);
    
    			var angle:Number = Math.atan2(nY, nX);
    
    			var r:Number =  Math.sqrt(nX * nX + nY * nY);
    
    			if (r <= 250) {
    				var f:Number = (4 * 50 * 10) / (r * r);
    				energyS.x += f * Math.cos(angle);
    				energyS.y += f * Math.sin(angle);
    			}
    		}
    	}
    
    • Line 53: get a reference to the player.
    • Line 55: we loop through each energy object.
    • Line 61: find the angle between the ship and the energy.
    • Line 63: find the distance between them, too.
    • Line 65: check whether the energy is within the ship’s force field.
    • Line 67: use the formula:
      • 4 = G, the “gravitational constant” I’ve chosen.
      • 50 = m1, the mass of the ship player.
      • 10 = m2, the mass of the energy object.
    • Line 69: apply movement.

    Here’s a timelapse showing how this looks:

    Note that the energy moves faster the closer it gets to the ship, thanks to the r-squared term.

    We can implement the pushing function just by making the force negative:

    
    
    	public function gravityPull(p:Player): void
    	{
    		for (var i:int = 0; i < energyList.length; i++) {
    			var energyS:Energy = energyList[i];
    
    			var nX:Number = (p.x - energyS.x);
    			var nY:Number = (p.y - energyS.y);
    
    			var angle:Number = Math.atan2(nY, nX);
    
    			var r:Number =  Math.sqrt(nX * nX + nY * nY);
    
    			if (r <= 250) {
    				var f:Number = (4 * 50 * 10) / (r * r);
    				energyS.x -= f * Math.cos(angle);
    				energyS.y -= f * Math.sin(angle);
    			}
    		}
    	}
    

    Here the object moves more slowly as it gets further away from the player, since the force gets weaker.


    Step 15: Apply the Mechanic

    Of course that you will need this function to be run each frame by GameScreen – but before that, we will need to use a Boolean function to toggle between the two functions:

    
    
    private var isGravityPushing:Boolean = true;  // hitting space toggles it
    

    We are going to use true for ‘Push’ and false for ‘Pull’.

    Inside KeyDownHandler():

    
    
    	if (e.keyCode == Keyboard.SPACE) {
    		if (isGravityPushing == true) {
    			isGravityPushing = false;
    		} else if (isGravityPushing == false) {
    			isGravityPushing = true;
    		}
    	}
    

    Afterwards, you will have to check the Boolean each frame. Add this to update():

    
    
    	if (isGravityPushing == true) {
    		energyM.gravityPull(player);
    	}
    	if (isGravityPushing == false) {
    		energyM.gravityPush(player);
    	}
    

    Step 16: Modification

    You might find that the movement doesn’t look so nice. This could be because the force is not quite ideal, or because of the r-squared term.

    I’d like to alter the formula like so:

    
    
    var f:Number = (0.8 * 50 * 10) / r;
    

    As you can see, I’ve reduced the value of “G” to 0.8, and changed the force to depend simply on the distance between the objects, rather than the distance squared.

    Try it out and see if you enjoy the change. You can always alter it however you like.


    Step 17: The Text Class

    We will need to show some text on the screen, for showing the score and the ship’s remaining power.

    For this purpose, we’ll build a new class, Text:

    
    
    package
    {
    	import flash.display.MovieClip;
    	import flash.text.TextField;
    	import flash.events.Event;
    	import flash.text.TextFormat;
    
    	import flash.text.TextFormatAlign;
    
    	public class Text extends MovieClip
    	{
    		public var _scoreText:TextField= new TextField();
    
    		public function Text(string:String)
    		{
    			var myScoreFormat:TextFormat = new TextFormat(); //Format changeable
    			myScoreFormat.size = 24;		
    
    			myScoreFormat.align = TextFormatAlign.LEFT;
    			myScoreFormat.color = (0x131313);
    
    			_scoreText.defaultTextFormat = myScoreFormat;
    
    			_scoreText.text = string;
    
    			addChild(_scoreText);
    		}
    
    		public function updateText(string:String)
    		{
    			_scoreText.text = string;
    		}
    	}
    }
    

    It’s very simple; it’s basically a MovieClip with a text field inside.


    Step 18: Adding Power for Player

    To give the game some challenge, we’ll make the ship’s power get used up slowly, so that the player has to collect energy objects in order to recharge.

    To make the ship’s power appear on the ship itself, we can simply add an instance of Text to the ship object’s display list.

    Declare these variables within the Ship class:

    
    
    public var totalPower:Number = 100;  // ship starts with this much power
    private var powerText:Text;
    

    We’ll need to keep the amount of power (both stored and displayed) updated every frame, so add this new function to Player:

    First, in the constructor:

    
    
    			// add a new text object if it doesn't already exist
    			if (!powerText) {
    				powerText = new Text(String(int(totalPower)));
    				addChild(powerText);
    				powerText.x -= 20;			//Adjust position
    				powerText.y -= 16;
    			}
    

    And then…

    
    
    	public function updatePower():void
    		{
    			// fps = 24, so this makes power decrease by 1/sec
    			totalPower -= 1 / 24;
    			powerText.updateText(String(int(totalPower)));
    		}
    

    The power will decrease every frame by 1/24th of a unit, meaning it’ll decrease by one full unit every second.

    We need to make this run every frame, so add this line to GameScreen.update():

    
    
    player.updatePower();
    

    Step 19: Make Energy Increase Power

    When the ship collides with an energy object, we want it to increase its power.

    In GameScreen.update(), add the highlighted line:

    
    
    returnedPower = energyM.checkCollision(player);
    player.totalPower += returnedPower;
    

    Remember you can alter how much power is returned in the EnergyManager.checkCollision() function.


    Step 20: Setting Up the Score

    Again, we will need the text class. This time, we’ll display “Score” and then the value.

    Here, we will need three more variables:

    • The “Score” text.
    • The score value text.
    • A variable to store the actual score.

    Declare these in GameScreen class:

    
    
    private var scoreText:Text;
    private var totalScore:int = 0;
    private var score:Text;
    

    In the constructor, add this code:

    
    
    scoreText = new Text("Score :");
    addChild(scoreText);
    
    score = new Text(String(totalScore));
    addChild(score);
    score.x = scoreText.x + 100;   //Positioning it beside the "Score : " Text.
    score.y += 2;
    

    Now, in the update() function, add this:

    
    
    score.updateText(String(totalScore));
    

    That’s it – we’ve created a basic version of the above game!

    Take a look (you may need to reload the page):


    Extra Features and Polishing

    Space Background

    Maybe you would also like a background with an embedded image and stars. Add this to your Main class:

    
    
    [Embed(source = "/../lib/SpaceBackground.jpg")]	//embed
    		private var backgroundImage:Class; //This line must come immediately after the embed
    
    		private var bgImage:Bitmap = new backgroundImage();
    		private var numOfStars:int = 70;
    

    Now create the Star class:

    
    
    package assets
    {
    	import flash.display.MovieClip;
    	import flash.events.Event;
    
    	public class Star extends MovieClip
    	{
    		private var speed:Number;
    
    		public function Star(alpha:Number, size:Number, speed1:Number)
    		{
    			graphics.beginFill(0xCCCCCC);
    			graphics.drawCircle(0, 0, size);
    
    			speed = speed1;
    		}
    
    		// make sure you call this every frame
    		private function moveDown():void
    		{
    			this.y += speed;
    
    			if (this.y >= 600) {
    				this.y = 0;
    			}
    		}
    	}
    }
    

    In the Main() constructor, add this to create the stars:

    
    
    
    for (var i:int = 0; i < numOfStars; i++) {
    		createStars();
    }
    

    Here’s the actual createStars() function:

    
    
    
    private function createStars():void
    {
    	var star:Star = new Star(
    		Math.random(),
    		Calculations.getRandomValue(1, 2),
    		Calculations.getRandomValue(2, 5)
    	);  //random alpha, size and speed
    
    	addChild(star);
    
    	star.x = Calculations.getRandomValue(0, 550);
    	star.y = Calculations.getRandomValue(0, 600);
    }
    

    With random alpha, size, position, and speed, a pseudo-3D background can be generated.

    Range indicator

    A range indicator circle can be made by simply creating another circle and adding it to the ship’s display list, just like how you added the power indicator text. Make sure the circle is centred on the ship, and has a radius equal to the ship’s push/pull range.

    Add transparancy (alpha value) to the circle with the below code:

    
    
    			graphics.beginFill(0xCCCCCC, 0.1);
    

    Try adding extra controls that make the range increase or decrease when the up and down arrow keys are pressed.


    Conclusion

    I hope you enjoyed this tutorial! Please do leave your comments.

    Next: Read this critique for a guide to taking Flux from a simple demo to a full game!


  9. Matt Stuttard Parker says:
    June 29, 2012 at 12:45 pm

    There are several methods used to produce menus within Unity, the main two being the built in GUI system and using GameObjects with Colliders that respond to interactions with the mouse. Unity’s GUI system can be tricky to work with so we’re going to use the GameObject approach which I think is also a bit more fun for what we’re trying to achieve here.


    Final Result Preview

    Please view the full post to see the Unity content.


    Step 1: Determine Your Game Resolution

    Before designing a menu you should always determine what resolution you are going to serve it to.

    Open the Player settings via the top menu, Edit > Project Settings > Player and enter your default screen width and height values into the inspector. I chose to leave mine as the default 600x450px as shown below.

    unity tutorial menus UI

    You then need to adjust the size of your Game view from the default "Free Aspect" to "Web (600 x 450)", else you could be positioning your menu items off the screen.

    unity tutorial menus UI

    Step 2: Choosing a Menu Background

    As you will have seen in the preview, our menu scene is going to have our game environment in the background so that when you click Play you enter seamlessly into the game.

    To do this you need to position your player somewhere in the scene where you like the background and round up the Y rotation value. This is so it’s easier to remember and to replicate later, so that the transition can be seamless from the menu into the game.

    unity tutorial menus UI

    Let’s now get on with the creation of the menu scene!


    Step 3: Creating the Menu Scene

    Make sure your scene is saved and is called "game" – you’ll see why later.

    Select the game scene within the Project view and duplicate it using Ctrl/Command + D, then rename the copy to "menu" and double-click it to open it.

    Note: You can confirm which scene is open by checking the top of the screen, it should say something like "Unity – menu.unity – ProjectName – Web Player / Stand Alone". You don’t want to start deleting parts accidently from your game scene!

    Now select and delete the GUI and PickupSpawnPoints GameObjects from the Hierarchy. Expand the "Player" and drag the "Main Camera" so that it’s no longer a child of the Player, then delete the Player.

    unity tutorial menus UI

    Next, select the terrain and remove the Terrain Collider Component by right-clicking and selecting Remove Component.

    Finally, select the "Main Camera" and remove the MouseLook Component by right-clicking and selecting Remove Component.

    If you run the game now nothing should happen and you shouldn’t be able to move at all. If you can move or rotate then redo the above steps.


    Step 4: Adjusting the Build Settings

    Currently when you build or play your game the only level included within that build is the "game" scene. This means that the menu scene will never appear. So that we can test our menu, we’ll adjust the build settings now.

    From the top menu select File > Build Settings and drag the menu scene from your Project View into the Build Settings’ "Scenes In Build" list as shown below

    unity tutorial menus UI

    (Make sure you rearrange the scenes to put "menu.unity" at the top, so that it’s the scene that’s loaded first when the game is played.)

    Perfect!


    Step 5: Adding the Play Button

    We’re going to use 3D Text for our menu, so go ahead and create a 3D Text GameObject via the top menu: GameObject > Create Other > 3D Text, then rename it "PlayBT". Set the Y rotation of the PlayBT text to match the Y rotation value of your Main Camera so that it’s facing directly at it and therefore easily readable.

    With the PlayBT selected, change the Text Mesh text property from Hello World to "Play", reduce the Character Size to 0.1 and increase the Font Size to 160 to make the text crisper.

    Note: If you want to use a font other than the default, either select the font before creating the 3D Text or drag the Font onto the 3DText’s TextMesh’s Font property and then drag the Fonts "Font Material" onto the Mesh Renderers Materials list, overwriting the existing Font Material. Quite a hassle I know!

    Finally, add a Box Collider via the top menu: Component > Physics > Box Collider. Resize the Box Collider to fit the text if it doesn’t fit it nicely.

    unity tutorial menus UI

    At this point in the tutorial you really need to have both the Scene and Game Views open at the same time since you are now going to move the PlayBT within the Scene View so that it’s centred within your Game View as shown below. I recommend first positioning it horizontally using a top down view and then revert to using a perspective view to position it vertically using the axis handles.

    unity tutorial menus UI
    unity tutorial menus UI

    So that’s our Play button all set up. Now let’s make it play!


    Step 6: The Mouse Handler Script

    Create a new JavaScript script within your scripts folder, rename it "MenuMouseHandler" and add it as a Component of the PlayBT GameObject by either dragging in directly onto PlayBT or by selecting PlayBT and dragging the script onto it’s Inspector.

    Replace the default code with the following:

    
    
    /**
    	Mouse Down Event Handler
    */
    function OnMouseDown()
    {
    	// if we clicked the play button
    	if (this.name == "PlayBT")
    	{
    		// load the game
    		Application.LoadLevel("game");
    	}
    }
      

    We’re using the MonoBehaviour OnMouseDown(…) function, invoked every time the BoxCollider is clicked by the mouse. We check whether the button clicked is called "PlayBT", and if so we use Application.LoadLevel(…) to load the "game" scene.

    Enough talk – go run it and watch your game come to life when you click Play!

    Note: If you click Play and have found yourself with a build settings error, don’t fret; you just need to check your build settings – revisit Step 4.


    Step 7: Ending the Game

    So the menu to start the game is great but the game technically never ends since when the timer runs out nothing happens… let’s fix that now.

    Open the CountdownTimer script and at the bottom of the Tick() function add the following line:

    
    
    Application.LoadLevel("menu");
      

    Now re-run your game and when the timer runs out you’ll be taken back to the menu! Easy Peasy!

    There we go – a basic menu added to our game. Now let’s make it a little more user friendly with a help screen to explain how to play.


    Step 8: Adding the Help Button

    The help button is identical to the PlayBT in practically every way, so go ahead and duplicate the PlayBT, rename it to HelpBT and position it below the Play button. Adjust the text property to say "Help" rather than "Play" and perhaps make the Font Size a little smaller as shown below – I used 100.

    unity tutorial menus UI

    Now open the MenuMouseHandler script and add the following else if block to your existing if statement.

    
    
    // if we clicked the help button
    else if (this.name == "HelpBT")
    {
        // rotate the camera to view the help &quot;page&quot;
    
    }

    If you check the preview you’ll see that when you click Help the camera rotates around to show the help menu. So, how do we do that?


    Step 9: God Save iTween

    Our camera rotation can all be done nice and cleanly in one line, thanks to iTween. Without iTween life wouldn’t be nearly as fun. As the name may give away it’s a tweening engine, built for Unity. It’s also free.

    unity tutorial menus UI

    Go ahead and open iTween within the Unity Asset store, then click Download/Import and import it all into your project. Once it’s imported you need to move the iTween/Plugins directory into the root of your Assets folder.

    unity tutorial menus UI

    You’re now all set to tween your life away!


    Step 10: Rotating the Camera

    Grab a piece of paper and a pen (or open a blank document) and make a note of your Main Camera’s Y rotation value, as circled below.

    unity tutorial menus UI

    Within the scene view rotate the camera around in whichever direction you like around the Y axis so that the Play and Help text are out of view and so that you’ve got a decent background for your help page. You can see mine below: I rotated from -152 to -8.

    unity tutorial menus UI

    Return to your MenuMouseHandler script and add the following line within the else if statement:

    
    
    iTween.RotateTo(Camera.main.gameObject, Vector3(0, -8, 0), 1.0);
    

    We use Camera.main to retrieve the main camera (defined by the "MainCamera" tag) from the scene and use iTween.RotateTo(…) to rotate the camera to a specific angle – in my case -8.

    (You need to replace the -8 within the above line with your camera’s current rotation.)

    Now go back to your scene and return your camera back to its original rotation that you wrote down at the start of this section, so that it’s facing the PlayBT. Run your game, click Help and the camera should spin around. Woo!

    Note: If you get an error about iTween not existing then you haven’t imported it properly – revisit Step 9.

    Now let’s build our Help page.


    Step 11: Building the Help Page

    Rotate your camera back to the Y rotation of your help page – in my case -8.

    Now we’re going to add a little explanation text as well as some more text to explain the different pickups and their scores. Finally, we’ll add a Back button to return to the main menu. You can arrange your page in whatever way you wish so feel free to get creative. Here we go…

    Duplicate the HelpBT, rename it HelpHeader, set its rotation to that of your camera, change the Anchor value to "upper center" and reduce the Font Size – I used 60.

    Next, copy and paste the below paragraph into the text property:

    "Collect as many Cubes as you can within the time limit.
    Watch out though, they change over time!

    Note: It’s worth noting that you can’t type multiline text into the text property; you have to type it in another program and then copy and paste it since pressing enter/return assigns the field.

    Finally remove the Box Collider and MenuMouseHandler Components within the Inspector since this text won’t need to be clickable. Hopefully you end up with something like this:

    unity tutorial menus UI

    Now drag a pickup prefab into the scene and position it on the screen. I put mine as shown below.

    unity tutorial menus UI

    Next, duplicate the HelpHeader, rename it to HelpPowerups, change the Anchor to "upper-left" and copy and paste the below paragraph into the text field.

    "Green: + 2 Points

    Pink: +/- Random Points

    Blue: Random Speed Boost"

    Reposition it so you have something like the below.

    unity tutorial menus UI

    All that’s left now is to add a Back button to return to the main menu.


    Step 12: The Help Page Back Button

    Duplicate the HelpBT, rename it BackBT, change its text to "Back", set its rotation to that of your camera and use the Scene View to reposition it within the Game View. I placed mine in the bottom corner as shown here:

    unity tutorial menus UI

    Now we just need to update our MenuMouseHandler script to handle mouse clicks from the BackBT as well. Add the following else if block to the bottom of the OnMouseDown() if statements:

    
    
    	// if we clicked the Back button
    	else if (this.name == "BackBT")
    	{
    		// rotate the camera to view the menu "page"
    		iTween.RotateTo(Camera.main.gameObject, Vector3(0, -152, 0), 1.0);
    	}
      

    This is nearly identical to the previous iTween statement, the only difference being the angle the camera is rotated to – -152 in my case. You need to change this number to the original Y rotation of your camera was (the one you wrote down, remember?)

    Now all you need to do it set your camera back to its original rotation – the value you just added to the iTween statement – so that it’s facing the main menu again.

    Run the game and your camera should spin round to reveal the help page and spin back round to the main menu. Congratulations, you’ve finished!


    Conclusion

    I hope you’ve enjoyed this Getting Started with Unity Session!

    In this part we’ve covered using GameObjects as menu items and the incredibly powerful tweening library, iTween.

    If you want an extra challenge, try using iTween to change the text colour on MouseOver and then back again on MouseExit. (You’ll find a list of Mouse handlers on this page.)

    Or add an iTween CameraFade and then fade it out when the timer runs out, then load then menu – rather than abruptly ending the game. You could then delay the call to Application.LoadLevel(...) using yield WaitForSeconds(...).

    Let me know how you get on in the comments!


  10. Kah Shiu Chong says:
    June 29, 2012 at 1:30 pm
    This entry is part 3 of 3 in the series The Math and ActionScript of Curves

    We’ve tackled drawing curves, and finding their quadratic and cubic roots, as well as handy applications for using quadratic roots within games. Now, as promised, we’ll look at applications for finding cubic roots, as well as curves’ gradients and normals, like making objects bounce off curved surfaces. Let’s go!


    Example

    Let’s take a look one practical use of this math:

    In this demo, the “ship” bounces off the edges of the SWF and the curve. The yellow dot represents the closest point to the ship that lies on the curve. You can adjust the shape of the curve by dragging the red dots, and adjust the movement of the ship using the arrow keys.


    Step 1: Shortest Distance to a Curve

    Let’s consider the scenario where a point is located near a quadratic curve. How do you calculate the shortest distance between the point and the curve?

    point to quadratic distance

    Well, let’s start with Pythagoras’s Theorem.

    \[
    Let\ the\ point\ be\ (x_p,\ y_p)\\
    and\ call\ the\ closest\ point\ on\ the\ curve\ (x_c,\ y_c)\\
    Then:\\
    z^2 = x^2 + y^2\\
    z^2 = (x_c-x_p)^2 + (y_c-y_p)^2\\
    Given\ y_c=ax_c^2 + bx_c + c,\\
    z^2 = (x_c-x_p)^2 + [(ax_c^2 + bx_c + c) -y_p]^2
    \]

    You can see that we have substituted \(y_c\) with the quadratic equation. At a glance, we can see the highest power is 4. Thus, we have a quartic equation. All we need to do is to find a minimum point in this equation to give us the shortest distance from a point to a quadratic curve.

    But before that, we’ll need to understand gradients on a curve…


    Step 2: Gradient of a Curve

    Before we look at the problem of minimizing a quartic equation, let’s try to understand gradients of a curve. A straight line has only one gradient. But a quadratic curve’s gradient depends on which point on the curve we refer to. Check out the Flash presentation below:

    Drag the red dots around to change the quadratic curve. You can also play with the slider’s handle to change the position of blue dot along x. As the blue dot changes, so will the gradient drawn.


    Step 3: Gradient Through Calculus

    This is where calculus will come in handy. You may have guessed that differentiating a quadratic equation would give you the gradient of the curve.

    \[
    f(x) = ax^2+bx+c\\
    \frac{df(x)}{dx} = 2ax+b
    \]

    So \(\frac{df(x)}{dx}\) is the gradient of a quadratic curve, and it’s dependant on the \(x\) coordinate. Well, good thing we’ve got a method to handle this: diff1(x:Number) will return the value after a single differentiation.

    To draw the gradient, we’ll need an equation to represent the line, \(y=mx+c\). The coordinate of the blue point \((x_p, y_p)\) will be substituted into the \(x\) and \(y\), and the gradient of the line found through differentiation will go into \(m\). Thus the y-intercept of line, \(c\) can be calculated through some algebra work.

    Check out the AS3:

    
    
    var x:Number = s.value
    var y:Number = quadratic_equation.fx_of(s.value)
    point.x = x;
    point.y = y;
    
    /**
     * y = mx + c;
     * c = y - mx;	<== use this to find c
     */
    var m:Number = quadratic_equation.diff1(x);
    var c:Number =  y - m * x;
    
    graphics.clear();
    graphics.lineStyle(1, 0xff0000);
    graphics.moveTo(0, c);
    graphics.lineTo(stage.stageWidth, m * stage.stageWidth + c);
    

    Step 4: Coordinate Systems

    Always bear in mind of the inverted y-axis of Flash coordinate space as shown in the image below. At first glance, the diagram on right may seem like a negative gradient – but due to the inverted y-axis, it’s actually a positive gradient.

    Positive gradient.

    The same goes for the minimum point as indicated below. Because of the inverted y-axis, the minimum point in Cartesian coordinate space (at (0,0)) looks like a maximum in Flash coordinate space. But by referring to the location of origin in Flash coordinate space relative to the quadratic curve, it’s actually a minimum point.

    Positive gradient.

    Step 5: Rate of Change for Gradient

    Now let’s say I’m interested in finding the lowest point on a curve – how do I proceed? Check out the image below (both figures are in the same coordinate space).

    Positive gradient.

    In order to get the minimum point, we’ll just equate \(\frac{df(x)}{dx} = 0\), since by definition we’re looking for the point where the gradient is zero. But as shown above, it turns out that the maximum point on a curve also satisfies this condition. So how do we discriminate between these two cases?

    Let’s try differentiation of the second degree. It’ll give us the rate of change of the gradient.

    \[
    \frac{df(x)}{dx} = 2ax+b\\
    \frac{df^2(x)}{dx^2} = 2a
    \]

    I’ll explain with reference to the image below (drawn in Cartesian coordinate space). We can see that, as we increment along the x-axis, the gradient changes from negative to positive. So the rate of change should be a positive value.

    We can also see that when \(\frac{df^2(x)}{dx^2}\) is positive, there’s a minimum point on the curve. Conversely if the rate is negative, a maximum point is present.

    Rate of change in gradient.

    Step 6: Back to the Problem

    Now we are ready to solve the problem presented in Step 1. Recall the quartic equation (where the highest degree is 4) we arrived at:

    \[
    z^2 = (x_c-x_p)^2 + [(ax_c^2 + bx_c + c) -y_p]^2
    \]

    quartic curve

    The same quartic equation, plotted

    Remember, we are interested to find the minimum point on this curve, because the corresponding point on the original quadratic curve will be the point that’s at the minimum distance from the red dot.

    point to quadratic distance

    So, let’s differentiate the quartic function to get to gradient of this curve, and then equate the gradient of this quartic function to zero. You will see that the gradient is actually a cubic function. I’ll refer interested readers to Wolfram’s page; for this tutorial, I’ll just pluck the result of their algebra workings:

    \[
    \frac{d(z^2)}{dx}=
    2(x_c-x_p) + 2(ax_c^2 + bx_c + c - y_p)(2ax_c+b)\\
    \frac{d(z^2)}{dx}= 2a^2(x_c)^3+3ab(x_c)^2+(b^2+2ac-2ay_p+1)(x_c)+(bc-by_p-x_p)\\
    Equate\ gradient\ to\ 0\\
    \frac{d(z^2)}{dx}=0\\
    2a^2(x_c)^3+3ab(x_c)^2+(b^2+2ac-2ay_p+1)(x_c)+(bc-by_p-x_p)=0\\
    Compare\ with\ cubic\ equation\\
    Ax^3+Bx^2+Cx+D=0\\
    A = 2a^2\\
    B=3ab\\
    C=b^2+2ac-2ay_p+1\\
    D=bc-by_p-x_p
    \]

    Solve for the roots of this (rather messy) cubic function and we’ll arrive at the coordinates of the three blue points as indicated above.

    Next, how do we filter our results for the minimum point? Recall from the previous step that a minimum point has a rate of change that’s positive. To get this rate of change, differentiate the cubic function that represents gradient. If the rate of change for the given blue point is positive, it’s one of the minimum points. To get the minimum point, the one that we’re interested in, choose the point with the highest rate of change.


    Step 7: Sample of Output

    So here’s a sample implementation of the idea explained above. You can drag the red dots around to customise your quadratic curve. The blue dot can also be dragged. As you move the blue dot, the yellow one will be repositioned so that the distance between the blue and yellow dots will be minimum among all points on the curve.

    As you interact with the Flash presentation, there may be times where three yellow dots appear all at once. Two of these, faded out, refer to the roots obtained from the calculation but rejected because they are not the closest points on the curve to the blue dot.


    Step 8: ActionScript Implementation

    So here’s the ActionScript implementation of the above. You can find the full script in Demo2.as.

    First of all, we’ll have to draw the quadratic curve. Note that the matrix m2 will be referred to for further calculation.

    
    
    private function redraw_quadratic_curve():void
    {
        var cmd:Vector.<int> = new Vector.<int>;
        var coord:Vector.<Number> = new Vector.<Number>;
    
        //redraw curve;
        m1 = new Matrix3d(
            curve_points[0].x * curve_points[0].x, curve_points[0].x, 1, 0,
            curve_points[1].x * curve_points[1].x, curve_points[1].x, 1, 0,
            curve_points[2].x * curve_points[2].x, curve_points[2].x, 1, 0,
            0,0,0,1
        );
    
        m2 = new Matrix3d(
            curve_points[0].y, 0, 0, 0,
            curve_points[1].y, 0, 0, 0,
            curve_points[2].y, 0, 0, 0,
            0,0,0,1
        )
    
        m1.invert();
        m2.append(m1);
        quadratic_equation.define(m2.n11, m2.n21, m2.n31);
    
        for (var i:int = 0; i < stage.stageWidth; i+=2)
        {
            if (i == 0) cmd.push(1);
            else		cmd.push(2);
    
            coord.push(i, quadratic_equation.fx_of(i));
        }
    
        graphics.clear();
        graphics.lineStyle(1);
        graphics.drawPath(cmd, coord);
    }
    

    And here’s the one that implements the mathematical concept explained. c1 refers to a point randomly positioned on stage.

    
    
    private function recalculate_distance():void
    {
        var a:Number = m2.n11;
        var b:Number = m2.n21;
        var c:Number = m2.n31;
    
        /*f(x) = Ax^3 + Bx^2 +Cx + D
         */
        var A:Number = 2*a*a
        var B:Number = 3*b*a
        var C:Number = b*b + 2*c*a - 2*a*c1.y +1
        var D:Number = c * b - b * c1.y - c1.x
    
        quartic_gradient = new EqCubic();
        quartic_gradient.define(A, B, C, D);
        quartic_gradient.calcRoots();
    
        roots = quartic_gradient.roots_R;
        var chosen:Number = roots[0];
    
        if (!isNaN(roots[1]) && !isNaN(roots[2])) {
    
            //calculate gradient and rate of gradient of all real roots
            var quartic_rate:Vector.<Number> = new Vector.<Number>;
    
            for (var i:int = 0; i < roots.length; i++)
            {
                if (!isNaN(roots[i])) 	quartic_rate.push(quartic_gradient.diff1(roots[i]));
                else 					roots.splice(i, 1);
            }
    
            //select the root that will produce the shortest distance
            for (var j:int = 1; j < roots.length; j++)
            {
                //the rate that corresponds with the root must be the highest positive value
                //because that will correspond with the minimum point
                if (quartic_rate[j] > quartic_rate[j - 1]) {
                    chosen = roots[j];
                }
            }
    
            //position the extra roots in demo
            position_extras();
        }
        else {
    
            //remove the extra roots in demo
            kill_extras();
        }
        intersec_points[0].x = chosen
        intersec_points[0].y = quadratic_equation.fx_of(chosen);
    }
    

    Step 9: Example: Collision Detection

    Let’s make use of this concept to detect the overlap between a circle and a curve.

    The idea is simple: if the distance between the the blue dot and the yellow dot is less than blue dot’s radius, we have a collision. Check out the demo below. The interactive items are the red dots (to control the curve) and the blue dot. If the blue dot is colliding with the curve, it will fade out a little.


    Step 10: ActionScript Implementation

    Well, the code is quite simple. Check out the full source in CollisionDetection.as.

    
    
    graphics.moveTo(intersec_points[0].x, intersec_points[0].y);
    graphics.lineTo(c1.x, c1.y);
    
    var distance:Number= Math2.Pythagoras(
        intersec_points[0].x,
        intersec_points[0].y,
        c1.x,
        c1.y)
    
    if (distance < c1.radius)  c1.alpha = 0.5;
    else                       c1.alpha = 1.0;
    
    t.text = distance.toPrecision(3);
    

    Step 11: Bouncing Off the Curve

    So now that we know when collision will occur, let’s try to program some collision response. How about bouncing off the surface? Check out the Flash presentation below.

    You can see the ship (triangle shape), is surrounded by a circle (translucent blue). Once the circle collides with the curve, the ship will bounce off the surface.


    Step 12: Controlling the Ship

    Here’s the ActionScript to control the ship.

    
    
    public function CollisionDetection2()
    {
        /**
         * Instantiation of ship & its blue-ish circular area
         */
        ship = new Triangle();	addChild(ship);
        ship.x = Math.random() * stage.stageWidth;
        ship.y = stage.stageHeight * 0.8;
    
        c1 = new Circle(0x0000ff, 15);	addChild(c1);
        c1.alpha = 0.2;
    
        /**
         * Ship's velocity
         */
        velo = new Vector2D(0, -1);
        updateShip();
    
        stage.addEventListener(KeyboardEvent.KEY_DOWN, handleKey);
        stage.addEventListener(KeyboardEvent.KEY_UP, handleKey);
        stage.addEventListener(Event.EXIT_FRAME, handleEnterFrame);
    
        /**
         * The curve and the calculations
         */
        quadratic_equation = new EqQuadratic();
    
        curve_points = new Vector.<Circle>;
        populate(curve_points, 0xff0000, 3);
    
        intersec_points = new Vector.<Circle>;
        populate(intersec_points, 0xffff00, 3, false);
    
        redraw_quadratic_curve();
    }
    
    private function handleKey(e:KeyboardEvent):void
    {
        if (e.type == "keyDown") {
            if (e.keyCode == Keyboard.UP) isUp = true;
            else if (e.keyCode == Keyboard.DOWN) isDown = true;
            if (e.keyCode == Keyboard.LEFT) isLeft = true;
            else if (e.keyCode == Keyboard.RIGHT) isRight = true;
        }
        if (e.type == "keyUp") {
            if (e.keyCode == Keyboard.UP) isUp = false;
            else if (e.keyCode == Keyboard.DOWN) isDown = false;
            if (e.keyCode == Keyboard.LEFT) isLeft = false;
            else if (e.keyCode == Keyboard.RIGHT) isRight = false;
        }
    }
    
    private function handleEnterFrame(e:Event):void
    {
        /**
         * Control the magnitude
         */
        if (isUp) 		velo.setMagnitude(Math.min(velo.getMagnitude()+0.2, 3));
        else if(isDown)	velo.setMagnitude(Math.max(velo.getMagnitude()-0.2, 1));
    
        /**
         * Control the direction
         */
        if (isRight) velo.setAngle(velo.getAngle() + 0.03);
        else if (isLeft) velo.setAngle(velo.getAngle() - 0.03);
    
        recalculate_distance();
    
        if (distance < c1.radius) bounce();
        updateShip();
    }
    
    /**
     * Update ship's position, orientation and it's area (the blue-ish circle)
     */
    private function updateShip():void {
        ship.x += velo.x;
        ship.y += velo.y;
        ship.rotation = Math2.degreeOf(velo.getAngle());
    
        c1.x = ship.x;
        c1.y = ship.y;
    
        if (ship.x > stage.stageWidth || ship.x < 0) velo.x *= -1;
        if (ship.y > stage.stageHeight || ship.y < 0) velo.y *= -1;
    }
    

    You can see that the keyboard controls are updating flags to indicate whether the left, up, right, or down keys are being pressed. These flags will be captured by the enterframe event handler and update the magnitude and direction of the ship.


    Step 13: Calculating the Reflection Vector

    I’ve already covered the vector calculation of reflection vector in this post. Here, I shall just cover how to obtain the normal vector from gradient.

    \[
    \frac{df(x)}{dx}=gradient\\
    line\ gradient=\frac{y}{x}\\
    Assume\ gradient=0.5\\
    y=0.5\\
    x=1\\
    Vector\ of\ left\ normal=
    \begin{bmatrix}-1 \\0.5\end{bmatrix}\\
    Vector\ of\ right\ normal=
    \begin{bmatrix}1 \\-0.5\end{bmatrix}
    \]


    Step 14: ActionScript Implementation

    So the ActionScript below will implement the mathematical concept explained in the previous step. Check out the highlighted lines:

    
    
    private function bounce():void
    {
        var gradient:Number = quadratic_equation.diff1(intersec_points[0].x);
        var grad_vec:Vector2D = new Vector2D(1, gradient);
    
        var left_norm:Vector2D = grad_vec.getNormal(false);
        var right_norm:Vector2D = grad_vec.getNormal();
        var chosen_vec:Vector2D;
    
        if (velo.dotProduct(left_norm) > 0) chosen_vec = left_norm
        else 								chosen_vec = right_norm
    
        var chosen_unit:Vector2D = chosen_vec.normalise();
        var proj:Number = velo.dotProduct(chosen_unit);
    
        chosen_unit.scale(-2*proj);
    
        velo = velo.add(chosen_unit);
    }
    

    Conclusion

    Well, thanks for your time! If you’ve found this useful, or have any questions, do leave some comments.


Leave a Reply

Click here to cancel reply.

search search search search search
Find an Article
Categories
  • Flash Video Training
  • Hints and Tips
  • Recommended
Please Support Our Sponsors
Recent Posts
  • Tuts+ Community Meetup in New York!
  • HTML5 Canvas Optimization: A Practical Example
  • Recreate the Cover Flow Effect Using Flash and AS3
  • Drawing Activetuts+ to a Close
  • Intro to Dart: Creating a Marquee
Tag Cloud
2011 ActionScript Active Activetuts+ Adobe animation Basic Basix Best Build Button Character Code Create Creating Critique Custom design Effect Effects Files Flash from Game Guide HTML5 Introduction Macromedia Motion Muzzle part Player Premium Professional Quick Silverlight Simple Text Tool Tutorial Tuts+ Using Video website Workshop
About Our Site:

Hey there and welcome to "Flash Video Training Source", a resource for anybody interested in learning more about Adobe's great tool. We feature educational videos, which will help you master Adobe Flash and help you get to know all of its features. We at "Flash Video Training Source" believe that video training and video... more

Why don't you follow us on Twitter and get the latest video tutorials twitted to your account. Just click on the floating twitter bar to your right!

Go Back In Time
May 2013
M T W T F S S
« Jul    
 12345
6789101112
13141516171819
20212223242526
2728293031  
Pretty Blank Box
top

Blogroll

  • Development Blog
  • Documentation
  • Plugins
  • Suggest Ideas
  • Support Forum
  • Themes
  • WordPress Planet

Meta

  • Log in
  • Entries RSS
  • Comments RSS
  • WordPress.org

Archives

  • July 2012
  • June 2012
  • May 2012
  • April 2012
  • March 2012
  • February 2012
  • January 2012
  • December 2011
  • November 2011
  • October 2011
  • September 2011
  • August 2011
  • July 2011
  • June 2011
  • May 2011
  • April 2011
  • March 2011
  • February 2011
  • January 2011
  • December 2010
  • November 2010
  • October 2010
  • September 2010
  • August 2010
  • July 2010
  • June 2010
  • May 2010
  • April 2010
Powered by WordPress  |  Designed by Elegant Themes  |  Lightning Fast Hosting by Site 5 Hosting