logo
468x60-2-495


  • Home
  • Privacy Policy
  • About
search
Oct 27, 2011 Posted on Oct 27, 2011 in Hints and Tips | 10 comments

AS3 101: Events – Basix

For this chapter of AS3 101, we will be diving into the mechanics of the Flash event system. If you’ve been following along so far, you’ll have seen events in use, dating all the way back to the first episode of the series. The editor and I felt that it was time to write up something to be formally included in the curriculum, so if you’ve ever seen those lines of code about adding event listeners or dispatching events, and not quite caught on, then this is the tutorial for you.

There already exists an Activetuts+ tutorial on the basics of Events, so the focus of this tutorial will be on dispatching events from your own classes, including creating custom event types and objects.

To be successful with this tutorial, you should feel comfortable with writing and using your own classes in ActionScript 3, as well as feeling secure with using the existing events provided by Flash, such MouseEvent.CLICK or Event.ENTER_FRAME. We will be focusing primarily on dispatching custom events from custom classes.


Preview

We’ll spend a lot of time on the theory for this tutorial, but in the end we’ll build a simple slider control that dispatches its own events:


Step 1: Why Use Event Dispatching?

This example is actually a rather simple example of why you’d want to dispatch your own events. When you write your own classes, you are ideally keeping them in their own black boxes and encapsulated. But you still need to have the various objects interoperate in order to create a useful program.

The event model provided by ActionScript 3 is a rather good and convenient way to facilitate communication between your classes, while maintaining a separation of responsibilities in your classes. So if we write our own custom class, such as the ActiveSlider class showcases above, we have a need to enable other objects to be aware of when the slider changes its value. If the slider can dispatch its own change event, then other objects that need to know that information can easily subscribe and be notified.

Personally, I find the need to dispatch my own events in my classes so common that my class template sets up each new class with the boilerplate it needs to be able to do so. As you learn to keep objects discrete, you’ll turn to event dispatching as the most common technique to do so.


Step 2: How to Dispatch Your Own Events

I have good news: dispatching your own events is actually very simple. It is one of the core tenets of ActionScript 3, built in to the Flash Player, and as such there is only one thing you need to do in order to gain the ability to dispatch events. This one thing is:

Extend EventDispatcher

That’s it: when writing your class, use the line:

public class MyClass extends EventDispatcher {

Of course, you need to import EventDispatcher, which is in the flash.events package. You will most likely need other classes in the package, so it might be most convenient to simply import the package with a wildcard.

import flash.events.*;

Step 3: Dispatch

Now you’re set up to dispatch an event. All you need to do now is call a method provided by EventDispatcher named dispatchEvent. Easy to grasp, no?

When you call dispatchEvent, you must provide at least one argument, an Event object. All built-in Event objects are in the flash.events package, so here’s where that wildcard import comes in handy. Each type of Event object will have its own requirements, but most often you simply need to pass it just one argument, as well. This argument is the event type, which is a String that names the event, like "click" or "complete". These are more commonly written as MouseEvent.CLICK or Event.COMPLETE, but the end result is the same; it’s an identifier that separates one type of event from another, and allows one Event object to manage multiple event types.

So, putting it all together, if you wanted to dispatch a "complete" event, you could do so like this:

dispatchEvent(new Event(Event.COMPLETE));

Just drop that line (or one like it) in whichever method it’s appropriate in your class. Your class will then utilize its inherited event dispatching system and any listeners will be notified for you. Speaking of listeners, let’s take a brief look at those, as well.


Step 4: Listen

Any other object in your application can listen for your custom events now. More good news: this is no different than registering for events for the built-in classes. In the previous step, we set up our hypothetical class to dispatch a COMPLETE event. To listen for that event, we could write this line somewhere else in our program:

var myObject:MyClass = new MyClass();
myObject.addEventListener(Event.COMPLETE, myCompleteHandler);
function myCompleteHandler(e:Event):void {
    trace("My object completes me.");
}

And that’s it. This should look familiar to anyone who has hooked up a COMPLETE listener to a Loader, for instance, so I won’t dwell any further on this.


Step 5: Where to Dispatch

Where you actually place the dispatchEvent line of code requires some consideration. Typically, it should be the last line of code of the method in which it is written. This is so that any other code that also runs in that method can set properties or otherwise update the internal state of the object. By dispatching after this internal update is complete, the object is in a “clean” state at the time of the dispatch.

Consider, for example, our working example. Let’s say the COMPLETE event is all about the processing of some data; a bunch of data so large that it will take several seconds to completely process, so the object’s purpose is to handle the processing asynchronously so as not to block the UI. And we’re dispatching the COMPLETE event as a way of saying that the data has been processed.

Now suppose that the main method in question looks something like this:

private function processDataChunk():void {
    _data += someDataProcess();
    if (done()) {
        closeData();
    }
}

OK, not very realistic, but it illustrates the point. We keep building up the internal data until some other internal logic determines we’re done, at which point we then write out some final bits of data to close the operation.

Now, let’s add the dispatchEvent call:

private function processDataChunk():void {
    _data += someDataProcess();
    if (done()) {
        dispatchEvent(new Event(Event.COMPLETE));
        closeData();
    }
}

What’s the issue with this approach? Any code that executes within listeners for the COMPLETE event will run before the closeData method is called. Therefore, the state of the dispatcher changes more than once within the span of the processDataChunk method, and is not “stable” until after the closeData call. Yet, we tell all of our listeners that we’re complete before that call. This could lead to some hard-to-track-down bugs where one object claims to be COMPLETE but really isn’t. The obvious solution is to switch some lines around:

private function processDataChunk():void {
    _data += someDataProcess();
    if (done()) {
        closeData();
        dispatchEvent(new Event(Event.COMPLETE));
    }
}

Step 6: Custom Events

You’re all set up to dispatch your own events. Now, what should you dispatch? There are a few options to consider:

  1. Simply reuse an event object and event type already provided by the Flash Player
  2. Reusing an existing event object, but provide a custom event type
  3. Re-Dispatch an existing event
  4. Create a custom event object
  5. Push vs. pull

This first option we’ve already seen in our previous examples. We have a need to dispatch an event related to the completion of some process, and as it happens Flash provides an event type (COMPLETE) associated with an event object (Event) that fits our criteria. We have no need to provide additional data with the event. Dispatching an Event.COMPLETE event is all we need.

We’ll explore these other options in the forthcoming steps.


Step 7: Custom Event Types

As hinted at back in the “Dispatch” step, event types are simply String identifiers. They can technically be any String you like. It’s usually sufficient to make it a single word (like “complete” or “click”) or very short phrase (like “ioError” or “keyFocusChange”); it only has to be unique within a given event dispatcher’s realm of available events.

In addition, Event objects (including subclasses, like MouseEvent or ProgressEvent) don’t really care what event type they are given when instantiated. An EventDispatcher will gladly dispatch events of any type identifier and of any class (as long as it’s the Event class or a subclass).

The upshot of this is that you can make up your own event type String, dispatch it, and set up listeners with it, and everything will be just fine. This is helpful when you want to dispatch an event but can’t necessarily find a good representation of the nature of the event in the built-in classes.

As an example, you might have a class that acts as a coordinator for several things at once: load some XML, load some images based on the XML data, and create a layout based on the loaded images’ sizes, ready for an initial animation, at which point you’d like to dispatch an event. While the COMPLETE event might be suitable, you may feel that a “ready” event more appropriately encapsulates the meaning.

This is as simple as deciding on the String to use, and then using it. Use it both when adding listeners, and when dispatching the event. If the String matches, the event will get to where it needs to go. For example, this is a partial listing of a hypothetical class:

public class MyClass extends EventDispatcher {

    // ... A bunch of other stuff not shown.

    private function determineReadiness():void {
        if (everythingIsReady) {
            dispatchEvent(new Event("ready"));
        }
    }

}

And code from elsewhere in the same program:

var myObject:MyClass = new MyClass();
myObject.addEventListener("ready", onObjectReady);

function onObjectReady(e:Event):void {
    // Do stuff now that it's ready.
}

And that would work.

However, it’s worth mentioning while we’re here that typing in matching Strings all over the place is not a good practice. The possibility for error is high, and the event system won’t tell you that you’ve typed "raedy" instead of "ready". The fact that the event system is flexible and simple to use – just pass it any old String for the event type – is also something of a weakness. Your dispatcher will gladly accept a listener for anything, even a "raedy" event. It doesn’t really reconcile what event types are registered against what event types are actually dispatched.

To help prevent this, the standard approach is to simply put the String you want to use in a static constant somewhere, and then never use that literal String again. Only use the constant. Of course, the possibility of typos is just a great as before, but if you’re using a READY constant and not the "ready" literal String, a mistype will trigger a compiler warning. You’ll be able to correct your error quickly and easily. A mistype with the literal Strings produces no compiler error, nor does it produce a run-time error. The only thing that happens is that the SWF does not seem to work properly, because the event listener doesn’t fire.

With this in mind, it’s most common to store these constants on the related Event class. We’ll get to custom Event classes in just a few steps. But in the situation outlined in this step (i.e., we’re reusing an Event class but not an event type), I find it more convenient to simply store that constant on the dispatcher class. So we might choose to do this:

public class MyClass extends EventDispatcher {

    public static const READY:String = "ready";

    // etc.

    private function determineReadiness():void {
        if (everythingIsReady) {
            dispatchEvent(new Event(READY));
        }
    }

}

And:

var myObject:MyClass = new MyClass();
myObject.addEventListener(READY, onObjectReady);

function onObjectReady(e:Event):void {
    // Do stuff now that it's ready.
}

This gives us the safety of storing event types in constants, while not forcing the inconvenience of creating a whole Event class that we don’t need. I must stress that this is a stylistic choice, and you may feel free to use this technique or not. I felt it warranted explanation, so that you could make your own informed decision. In either regard, you should definitely store your custom event type Strings in static constants. Where those static constants are defined is up to you.


Step 8: Re-Dispatching Events

There are several times when one class (let’s call it ClassX) owns a property that is typed as another class (we’ll call that one ClassY), while itself being owned by a third class (how about ClassZ?). ClassX is listening for an event from ClassY, but not only do we want to have ClassX respond to the event, we also want to consider that ClassX should dispatch a similar (or even the same) event so that ClassZ can also take further action.

As a more concrete example, we have a class (this will be “ClassX“) that is a sort of data manager. It loads an XML document, parses it, and stores data from the XML in its own properties. So it has an URLLoader object (this would be “ClassY“), and listens for the Event.COMPLETE event for when the XML document is loaded.

Then we have a main document class that owns the data manager (the document class is “ClassZ“). It’s coordinating the data loading with other UI elements, so it wants to know when the data is loaded and ready, so it can proceed to create and layout UI elements based on the data.

public class DataManager extends EventDispatcher {
    private var _xmlLoader:URLLoader;
    public function DataManager() {
        _xmlLoader = new URLLoader(new URLRequest("some.xml"));
        _xmlLoader.addEventListener(Event.COMPLETE, onLoadComplete);
    }
    // ... A bunch of other stuff
    private function onLoadComplete(e:Event):void {
        // ... XML parsing
        // With the XML parsed, we'd like to dispatch another event to signal being done.
    }
}

We could do this:

dispatchEvent(new Event(Event.COMPLETE));

But we could also do this:

dispatchEvent(e);

Here we simply re-dispatch the existing event. Not only do we reuse the event type and the Event class, but we’re actually reusing the entire Event object as it was passed in to our own listener.

It’s not rocket science, but it is a handy little technique that is surprisingly not so obvious.

“But wait,” you must be thinking, “if we redispatched an event that originated from the URLLoader object, wouldn’t the target of the event still be _xmlLoader when it gets back out to the document class?” And you would have a very good and thoughtful point, and I would be proud of you for thinking so studiously, but you would be wrong.

A rather magical thing happens when redispatching events. The target property gets set to the current dispatcher. You can find a working example of the code in this step in the download package, entitled redispatch.

Actually, it’s not all that magical. When calling dispatchEvent, if the Event object that is passed in already has a target set, then the clone method is called on the Event, creating an identical but discreet copy of the original Event, except for the value contained in target.


Step 9: Custom Event Objects

Everything mentioned so far is something you will want to know. But there will come a point when the best thing to do is to dispatch your own custom event. Not just a custom event type, but a whole custom Event class.

The process for doing this is straightforward, you just need to follow a few steps. We’ll discuss these in due course. Note that quite a bit of this is boilerplate code, and you could easily create a template for an Event subclass and change just a few key pieces and be off and running. The general steps, in shortened-as-if-you-knew-what-I-was-talking-about form:

  1. Subclass Event
  2. Call super(...)
  3. Store event types in public static constants
  4. Declare private properties to hold custom data
  5. Create public getters to provide read-only access to the custom info
  6. (Optional) Override the clone method
  7. (Optional) Override the toString method

To explain these process more deeply, we’ll get a start on our slider project and create the SliderEvent we will need for that. So we need to start our project before we can write some code, so a quick diversion in the next step, then we’ll start writing a custom Event class.


Step 10: Create the Project Structure

We’ll keep things pretty simple for this one, but we’ll nonetheless create packages for our classes.

Start by creating a folder for the entire project. Mine will be called slider.

Inside of this, create a com folder, and inside of that, an activetuts folder.

Now create two folders inside of activetuts: events and ui. Your final folder structure should look something like this:

  • slider
    • com
      • activetuts
        • events
        • slider

Now back to our Event class.


Step 11: Subclass Event

First, create a new text file in the slider/com/activetuts/events folder, and call it SliderEvent.as. We’ll pop in the boilerplate for any class first:

package com.activetuts.events {

    public class SliderEvent {

        public function SliderEvent() {

        }

    }

}

There should be nothing surprising here, and if you have ActionScript templates for your text editor, you shouldn’t even have to type that much in.

Now, we’ll modify this so that it extends Event.

package com.activetuts.events {

    import flash.events.Event;

    public class SliderEvent extends Event {

        public function SliderEvent() {

        }

    }

}

As you can see, we simply import the Event class, add extends Event to the class definition.


Step 12: Call super

Our superclass can handle a lot for us, which is great, but we do need to make sure we initialize the superclass properly when we initialize our subclass. We need to set up the constructor with arguments matching those found on Event‘s constructor, and pass those along with a call to super.

package com.activetuts.events {

    import flash.events.Event;

    public class SliderEvent extends Event {

        public function SliderEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=true) {
            super(type, bubbles, cancelable);
        }

    }

}

This is, so far, basic subclassing techniques. In fact, depending on your editor’s prowess with templates, you may be able to specify a super class when you create the file and have all of this done for you. Flash Builder, for example, is able to do this.


Step 13: Store Event Types in Public Static Constants

Presumably, there will be one or more event types associated with this event class. Just like the COMPLETE event is associated with the Event class, and the CLICK even with the MouseEvent class, our custom event class will likely have custom event types.

This is as simple as writing a line like the following for every event type you would like to add:

public static const EVENT_TYPE:String = "eventType";

Let’s do that now for the SliderEvent class.

package com.activetuts.events {

    import flash.events.Event;

    public class SliderEvent extends Event {

        public static const CHANGE:String = "sliderChange";

        public function SliderEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=true) {
            super(type, bubbles, cancelable);
        }

    }

}

We could theoretically use our class now. We can use the SliderEvent in dispatchEvent, and listen for and create events with the SliderEvent.CHANGE event type.

But we won’t stop there. There is more to consider. But before we do more code-writing, we need to take another detour into theory.


Step 14: Push vs. Pull

When an event is dispatched, sometimes it’s enough to simply know that the event has occurred. For example, most times that you are interested in Event.ENTER_FRAME, Event.COMPLETE, or TimeEvent.TIMER events, you probably just want to know that the event happened. There are other times, though, when you probably want to know more. When listening to MouseEvent.CLICK, you might be interested in whether the Shift key was held down, or the coordinates of the mouse at the time of the click. If you’re listening to ProgressEvent.PROGRESS, you will most likely want to know the actual progress of the load; that is, how many bytes have loaded and how many there are to load in total.

The difference between these two methodologies is sometimes known as “push” and “pull.” Those terms refer to how the event listener gets data related to the event. If the data is “pushed” then there is data stored within the event object, and in order to get the data the listener merely need to use properties on the event object. If data is to be “pulled,” though, generally the event object has very little information contained within – just the necessities: the type, the target, etc. This target, though, is indispensable, as it provides access to the event dispatcher to the event listener, allowing the listener to get the data it needs from the dispatcher.

In other words, you can either push a bunch of data to the listener inside the event object, or you can require the listener to pull the data out of the dispatcher as needed.

The pros and cons of each technique are somewhat balanced, in my opinion, and the path you choose for your event object depends on the situation at hand, and not a little bit on personal preference.

Exhibit A:

  Pros Cons
Push
  • Data is easily accessible in the event object
  • You may be pushing data that is unneeded. Bloating the event object with a bunch of data that is rarely used could lead to memory and/or performance issues.
Pull
  • Very easy to write. You probably don’t need a custom Event class to execute a pull event.
  • Very easy to use. If it’s just an Event class, the only required argument is the event type.
  • If data commonly pulled out of the dispatcher is expensive to compute and return, you may be taking a hit on performance by requiring the dispatcher to continually hand out that information.
  • Some data might be difficult to pull, e.g. the KeyboardEvent has a keyCode property to detail the key that was pressed to trigger the event.

This might be a good discussion for the comments; I’m sure many of you reading have passionate feelings about which methodology is better. Personally, I try to find the method that works best for the situation.

Having said that, it’s worth noting that to this point our SliderEvent class is rather “pull-ish.” For the sake of illustration, and because it’s not a terrible idea (though I did come up with several of those), we’ll continue on with making this an event that pushes data along with it; namely the value of the slider when it was changed.


Step 15: Declare Private Properties to Hold Custom Data

To implement a push event, we need to have a place to store the data being pushed. We’ll add a private property for that purpose.

You should still have SliderEvent open (if not… what are you waiting for?). Add the highlighted line:

package com.activetuts.events {

    import flash.events.Event;

    public class SliderEvent extends Event {

        public static const CHANGE:String = "sliderChange";

        private var _sliderValue:Number;

        public function SliderEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=true) {
            super(type, bubbles, cancelable);
        }

    }

}

Next we’ll modify the constructor so that we can accept a value parameter, and set the private property with that:

public function SliderEvent(type:String, sliderValue:Number, bubbles:Boolean=false, cancelable:Boolean=true) {
    _sliderValue = sliderValue;
    super(type, bubbles, cancelable);
}

This way we can easily create the SliderEvent and set up its push data in one line.

Why use private properties? In this case, we want to protect the data. In my opinion the data related to an event is immutable, so long as it’s associated with the event. Being able to change the data of an event object is like editing a history textbook. To be fair, this is my opinion and the standard used by Adobe with their built-in classes is to use writable properties (technically they use private properties and public getters and setters, but the end result is the same).


Step 16: Create Public Getters for the Custom Data

So the next step would be to make sure we can access the data being pushed. A private property by itself is not useful to this purpose. Therefore, we need to write a public getter for the _sliderValue property. We will choose to not write a setter, so that the property becomes read-only (as discussed in the last step).

Add this method to the class:

public function get sliderValue():Number {
    return _sliderValue;
}

This adds a getter so we can access the sliderValue in property-like fashion. I’m choosing not to add the matching setter. You can add one if you feel it’s worthwhile.


Step 17: Override the clone method

I mentioned the clone method a little while ago. You probably won’t call clone much yourself, but it’s not a bad idea to override the clone method so that your custom event plays nicely with the event system.

Add this method to your class:

override public function clone():Event {
    return new SliderEvent(type, sliderValue, bubbles, cancelable);
}

First, notice the signature of this method. We’re using override because this method is declared in Event, and we’re inheriting it. It also returns an object of type Event. Make sure, when writing your clone override, that you put the correct return type in. It’s easy to forget and put the type of your class there, but that will cause an incompatible override error, because the return types need to match.

All we’re really doing in the meat of the event is creating a new SliderEvent and passing in the same values that we have stored in the current event object. This creates an identical but discreet copy: a clone.

This is an optional step, but it’s a quick win and ensures that your custom event plays well with the rest of the event system.


Step 18: Override the toString method

One last thing, and again this is optional. But it’s also very useful as a debug tool, so it usually pays for itself within a few uses.

In case you haven’t been told yet, the toString method exists on all objects (it’s declared and defined in Object, the über-class from which all other classes inherit, whether you like it or not). It can be called explicitly, but the handy thing is that it get called automatically in a number of cases. For example, when you pass object to the trace function, any object that is not already a String will have toString called on it to make sure it is formatted nicely for the Output panel. It even gets called when working with Objects together with Strings, as with concatenation. For example, if you write this:

"The answer to life, the universe, and everything is " + 42;

ActionScript is smart enough to convert 42 into a String representation of the Number before concatenating the String. Trying to add a String and a Number is bad news, but converting a Number to a String and then concatenating it with another String is just fine.

So when you write your own classes, you can provide a toString method, which takes no arguments and returns a String, and return whatever String you like.

In the case of Event objects, Adobe helpfully provides a formatToString method to help all Events look similar when traced. We’ll use it in the method we’re about to add to our class:

override public function toString():String {
    return formatToString("SliderValue", "type", "sliderValue");
}

First, note the method signature. Again, it’s an override so we have that keyword. It’s public, it takes no parameters, and returns a String (which should be obvious).

Next, note the single line in the method body. We call formatToString, which is defined in Event, so it’s easy to use. The first argument we pass to it is the String name of the class. After that, the arguments are open-ended. You can pass in one, 15, or none. We’re passing in two. No matter how many you pass in, they should all be Strings, and they should match property names on your class. "type" is defined by Event, but "sliderValue" is defined by our own class. Either way, what happens is that the name of the property is printed, followed by an equals sign, which is followed by the actual value of that property. In short, it will end up looking like this:

[language="text"]
[SliderValue type="sliderChange" sliderValue=0.34146341463414637]

This is entirely non-functional but very useful. It can provide a quick glimpse into the event when things aren’t working the way you think they should.


Step 19: Building the Slider

At this point, we’ve been through the key concept of this tutorial: writing a custom Event class. But we really need to put it to the test. We’ll spend the remainder of our time building the simple slider application that was previewed at the beginning of the tutorial.

We already have a project folder structure; we just need a few more files. We’ll start with the FLA file.

Create a new Flash file (ActionScript 3.0, of course) and save it as ActiveSlider.fla in the root of your project folder. I’m going to assume that you don’t need step-by-step details on how to put this simple FLA together, and instead I’ll lay out the key elements. You can use the FLA file found in the start folder of the download package for reference, as well, or even just copy that FLA to your project folder and call this step done.

There are three main objects on the stage.

  1. The slider track. This is a long, narrow strip that indicates to where the slider can be moved. The slider moves “in” the track.
    • Needs to be a Movie Clip
    • For easiest math, should have artwork arranged so that the registration point is at the top left corner
    • Name it track_mc
    • Place in the upper center; it should take up most of the width of the stage and have space below it.
  2. The slide grip. This is a button-sized element that indicates the current position of the slider. It’s the piece that moves along the track and responds to the mouse.
    • Needs to be a Movie Clip.
    • Again, for math, should have the registration point at the top left
    • Name it grip_mc
    • Place it over the track, so that it is vertically centered with the track, and somewhere within the left and right ends of the track
    • It should be stacked on top of the track, so that the grip obscures the track (put it on a layer higher)
  3. The output field. This is a text field that, for our own demonstration purposes, displays the current value of the slider.
    • Needs to be a dynamic Text Field.
    • Name it output_tf
    • Fonts are inconsequential; set it to whatever you like and embed as necessary
    • Place it in the lower portion of the stage, so that it doesn’t conflict with the space required by the slider.
The stage of our FLA

Other than hooking up the document class, which we’ll write in two steps, the FLA is ready for business.


Step 20: The ActiveSlider Class

The main UI class with which we’ll work is the ActiveSlider class. This will extend EventDispatcher, target the two Movie Clips on the stage, and set up mouse interactivity for slider behavior. Most exciting of all, it will dispatch a SliderEvent.

Start by making a new class file called ActiveSlider.as in the com/activetuts/slider folder of your project. This class isn’t too intense (at least, not for our purposes here. A slider class could get much more involved), and I’ll just present the code in full and discuss as we go:

package com.activetuts.slider {

    import flash.display.*;
    import flash.events.*;
    import flash.geom.*;

Nothing exciting, just setting up the package and imports.

    public class ActiveSlider extends EventDispatcher {

        private var _track:Sprite;
        private var _grip:Sprite;
        private var _grabOffset:Point;

We’ll need these three properties. The first two keep track of the Sprites (or MovieClips) that make up the slider. The third is used while dragging the slider grip; it helps keep the grip’s position offset from the mouse by an amount relative to where the grip was clicked in the first place.

        public function ActiveSlider(track:Sprite, grip:Sprite) {
            _track = track;
            _grip = grip;
            if (_grip.parent != _track.parent) {
                throw new Error("The track and the grip Sprites are not in the same container.")
            }

            _grip.addEventListener(MouseEvent.MOUSE_DOWN, onDown);

            if (_grip.stage) {
                addStageListener();
            } else {
                _grip.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
            }
        }

This is the constructor. It accepts two Sprite arguments, which get passed on to the first two of those properties for storage. It then does a simple check to make sure the two Sprites are in the same coordinate space by checking that their parent properties reference the same object. If they don’t, then our math for placing the grip might be unreliable, so we throw an error as a way of alerting the developer. The rest of the constructor is devoted to adding two event listeners. The first is a MOUSE_DOWN event and straight forward. But the second is trying to add a MOUSE_UP event to the stage, which might or might not exist depending on whether the grip Sprite is on the display list or not. The next two methods might make this a little clearer:

        private function onAddedToStage(e:Event):void {
            _grip.removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
            addStageListener();
        }

        private function addStageListener():void {
            _grip.stage.addEventListener(MouseEvent.MOUSE_UP,   onUp);
        }

The onAddedToStage method is an event listener for the ADDED_TO_STAGE event, which was set up in the constructor, but only if the grip Sprite did not already have a reference to the stage. The addStageListener method simply adds the MOUSE_UP event listener to the stage. So, if there is a stage reference in the constructor, we call addStageListener directly. If there is not a stage reference, we set up the ADDED_TO_STAGE event, and when the grip is added to the display list, and thus has a stage reference, the onAddedToStage method fires which then in turn calls addStageListener. It also removes the ADDED_TO_STAGE event listener, because we only need to do this once.

        private function onDown(e:MouseEvent):void {
            _grabOffset = new Point(e.localX, e.localY);
            _grip.addEventListener(Event.ENTER_FRAME, onFrame);
        }

        private function onUp(e:MouseEvent):void {
            _grip.removeEventListener(Event.ENTER_FRAME, onFrame);
        }

Next we have our two mouse event listeners. In onDown, the key line is to then add an ENTER_FRAME event listener. In onUp, we remove that listener. Also in onDown, we make note of where on the grip the mouse click actually happened, and store that in _grabOffset. This will play into our onFrame method next.

        private function onFrame(e:Event):void {
            _grip.x = _grip.parent.mouseX - _grabOffset.x;

            var gripBounds = _grip.getBounds(_grip.parent);
            var trackBounds = _track.getBounds(_grip.parent);

            if (gripBounds.x < trackBounds.x) {
                _grip.x = _track.x;
            } else if (gripBounds.right > trackBounds.right) {
                _grip.x = trackBounds.right - gripBounds.width
            }

            trace(this.value);
        }

This is the main meat of our slider logic. This method fires repeated on an ENTER_FRAME event, but only when the mouse has been pressed down on the grip, and only for as long as the mouse remains pressed.

First, we set the grip’s x property to match the mouse position, only we need to offset it based on the original mouse position, so that it moves smoothly and doesn’t jump so that its left edge is at the mouse.

The next two lines calculate the bounding rectangles of both the grip and track Sprites. We’ll use these rectangles in the upcoming math, so we’ll keep things tidier by pre-calculating the rectangles and storing them in variables.

Then there is the if block. This just constrains our slider to within the track. It’s a simple check to see if the x of the grip, as calculated in the first line of the method, is lower than (to the left of) the x of the track. If it is, it would be too far, so we need to move the grip to that minimum value. Similarly, we check to see if the grip’s right edge is greater than (to the right of) the track’s right edge, and if so we need to reel it back in to that maximum value.

Finally, we have a reliable grip position, and for now we just trace the current slider value, which is calculated in the final bit of code for the class:

        private function get value():Number {
            return (_grip.x - _track.x) / (_track.width - _grip.width);
        }

    }

}

This is a simple getter, although the math being used for the return value might be a little confusing. It determines the current grip position as a percentage of the range of motion of the grip. It would be more obvious if it were just this:

return _grip.x / _track.width;

…which is reasonable but doesn’t take into account that the grip doesn’t actually travel the entire width of the track. It goes all the way to the left edge, but only as far right as the right edge of the track minus the width of the grip. So this is more accurate:

return _grip.x / (_track.width - _grip.width);

This makes the width by which we divide the range of motion. However, there may still be a gotcha in that the track may be offset to the left or right from its container, meaning that the values we get aren’t quite right. We need to neutralize that by subtracting the x position of the track from the grip’s x, and we end up with this:

return (_grip.x - _track.x) / (_track.width - _grip.width);

For reference, here is the complete class, with my ramblings left out:

package com.activetuts.slider {

    import flash.display.*;
    import flash.events.*;
    import flash.geom.*;

    public class ActiveSlider extends EventDispatcher {

        private var _track:Sprite;
        private var _grip:Sprite;
        private var _grabOffset:Point;

        public function ActiveSlider(track:Sprite, grip:Sprite) {
            _track = track;
            _grip = grip;
            if (_grip.parent != _track.parent) {
                throw new Error("The track and the grip Sprites are not in the same container.")
            }

            _grip.addEventListener(MouseEvent.MOUSE_DOWN, onDown);

            if (_grip.stage) {
                addStageListener();
            } else {
                _grip.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
            }
        }

        private function onAddedToStage(e:Event):void {
            _grip.removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
            addStageListener();
        }

        private function addStageListener():void {
            _grip.stage.addEventListener(MouseEvent.MOUSE_UP, onUp);
        }

        private function onDown(e:MouseEvent):void {
            _grabOffset = new Point(e.localX, e.localY);
            _grip.addEventListener(Event.ENTER_FRAME, onFrame);
        }

        private function onUp(e:MouseEvent):void {
            _grip.removeEventListener(Event.ENTER_FRAME, onFrame);
        }

        private function onFrame(e:Event):void {
            _grip.x = _grip.parent.mouseX - _grabOffset.x;

            var gripBounds = _grip.getBounds(_grip.parent);
            var trackBounds = _track.getBounds(_grip.parent);

            if (gripBounds.x < trackBounds.x) {
                _grip.x = _track.x;
            } else if (gripBounds.right > trackBounds.right) {
                _grip.x = trackBounds.right - _grip.width
            }

            trace(this.value);
        }

        private function get value():Number {
            return (_grip.x - _track.x) / ((_track.width - _grip.width) - _track.x);
        }

    }

}

We have not added in our SliderEvent class yet; we’ll take a separate step to do that. But first, we need our document class so we can actually use the ActiveSlider.


Step 21: The Document Class

We need one more file to make it work: our document class. Make a new class file named SliderDemo in the project root folder. Add in the following code:

package  {

    import flash.display.*;
    import flash.events.*;
    import com.activetuts.slider.ActiveSlider;

    public class SliderDemo extends Sprite {

        private var _slider:ActiveSlider;

        public function SliderDemo() {
            _slider = new ActiveSlider(track_mc, grip_mc);
        }

    }

}

This is much simpler that our ActiveSlider class. It really just sets up an ActiveSlider into the property named _slider.

Go back to the FLA file, and enter SliderDemo into the document class field, and you should be able to try this out. The slider should be able to move back and forth, and constrain itself to the width of the track.

Now for one last task. We need to dispatch, and listen for, a SliderEvent.CHANGE event. We’ll do that next.


Step 22: Dispatching the SliderEvent

Go back to the ActiveSlider class, and make a single-line change to the onFrame method:

private function onFrame(e:Event):void {
    _grip.x = _grip.parent.mouseX - _grabOffset.x;

    var gripBounds = _grip.getBounds(_grip.parent);
    var trackBounds = _track.getBounds(_grip.parent);

    if (gripBounds.x < trackBounds.x) {
        _grip.x = _track.x;
    } else if (gripBounds.right > trackBounds.right) {
        _grip.x = trackBounds.right - _grip.width
    }

    dispatchEvent(new SliderEvent(SliderEvent.CHANGE, this.value));
}

We’ve removed the trace and replaced it with a real, live event dispatch. For this to work, though, we need to import the SliderEvent class:

package com.activetuts.slider {

    import flash.display.*;
    import flash.events.*;
    import flash.geom.*;
    import com.activetuts.events.SliderEvent;

Step 23: Listening For the SliderEvent

Finally, go back to the SliderDemo class, and change it so it listens for and reacts to the SliderEvent:

package  {

    import flash.display.*;
    import flash.events.*;
    import com.activetuts.slider.ActiveSlider;
    import com.activetuts.events.SliderEvent;

    public class SliderDemo extends Sprite {

        private var _slider:ActiveSlider;

        public function SliderDemo() {
            _slider = new ActiveSlider(track_mc, grip_mc);
            _slider.addEventListener(SliderEvent.CHANGE, onSliderChange);
        }

        private function onSliderChange(e:SliderEvent):void {
            trace(e);
            output_tf.text = e.sliderValue.toString();
        }

    }

}

We’re again importing the SliderEvent class, and after creating the ActiveSlider, adding a listener called onSliderChange to the slider. That method is the biggest addition, but still is a regular event listener. It’s much like any other event listener, only we’re making sure to type the event argument as SliderEvent, because that’s what we’re getting.

The first line of code is a bit superfluous, but I wanted to see what happens when you trace our SliderEvent object. You’ll see, when you run this, a typical-for-Flash formatting of the event object.

The event object represented as a String

The second line does what we were after to begin with. It simply grabs the sliderValue property, turns it into a String, then sticks that String into the TextField on the stage, so we can see the slider value in the movie.


Step 24: Wrapping Up

When you start rolling your own custom events, you start working with ActionScript 3 the way it was meant to be used. Events help you decouple classes from each other, and a well structured event flow in your application can really make the difference between something that is easy to work with and something that is buggy and temperamental. With this (theoretically) final instalment of AS3 101, you should be well on your way to becoming a ninja.

Thanks for reading, and I’ll see you back here on Activetuts+ before you know it!



View full post on Activetuts+

Sep 12, 2011 Posted on Sep 12, 2011 in Hints and Tips | 10 comments

Get Up to Speed With HTML – Basix

We’ll soon be publishing our first HTML5 tutorials here at Activetuts+, but before we start, here’s a fast and easy tutorial to get up to speed on the basics of HTML – even if you’ve never done any before.


The Difference Between HTML and .html

Create a new file, anywhere on your computer, and call it page.html. In Windows, the easiest way to do that is right-click an empty spot within a folder, click New > Text File, then make sure you delete the “.txt” at the end of a file. Windows will probably tell you that it’s dangerous to change the file extension like this; just click OK. Alternatively, you can open a text editor (like Notepad or TextEdit), click File > New, and enter page.html as the filename.

Once you’ve created the file, open it in a text editor; there are plenty of fancy editors that offer all sorts of HTML-friendly features, but for this tutorial, the aforementioned Notepad or TextEdit will do just fine. (If you just double-click the file, it’ll probably open in your browser, so you’ll either need to open the text editor first and use File > Open to select the file, or (in Windows) right-click the file and choose Open With > Notepad.) Make sure you use a simple text editor rather than a word processor.

Enter this in your file:

Is this HTML?

Save it, and open it in your browser – or just click here to open mine. It’ll look something like this:

HTML beginner tutorial guide

So there you go! You’ve created a web page – a .html page – and it displays just fine, with no error messages. That’s it, end of the tutorial, thanks for reading.

Just kidding, of course.

Browsers Aren’t Psychic

Here’s an experiment: take an image file, copy it (so that you don’t damage the original image), and rename the copy to something.html. Then, try to open this with your browser. Click here to open the screenshot above, after it’s been renamed from .png to .html, in your browser.

Yikes. That’s a lot of gobbledegook. But if you open the original .png file in your browser, it’ll load just fine. Your browser can obviously cope with these files, so what gives?

When you open a .html file with your browser, it says, “Hey, I know how to deal with .html files!” – it assumes that the contents of the file are written using HyperText Markup Language (HTML for short, as you’ll have guessed), and tries to use everything it knows about this markup language to display the page. Image files aren’t written using HTML, so when it tries to display something that makes any sense using its HTML rules, it fails miserably.

There are other file extensions that browsers automatically associate with HTML – like .htm – and browsers can also be told to assume that other types of files will contain HTML – like ones ending in .php or .aspx.

So, not every file that’s written in HTML will end in .html. But does this mean that Is this HTML? is perfect HTML in itself? Well… not exactly.

People Make Mistakes

While the actual contents of an image file are usually generated by a program like Paint or Photoshop based on a user’s input, the contents of a .html file may be typed directly into the file by the user. And users, being human, make mistakes.

Browsers, in general, err on the side of forgiveness; rather than pettily refusing to display a page if the user has made even a simple mistake – like certain overzealous English teachers – it’ll try to guess what the user meant and display the page to the best of its abilities.

Is this HTML?, you will be shocked to hear, is not ideal HTML, in that it does not contain all of the information a browser would like to see – but it’ll be displayed anyway.

This means, then, that files containing HTML don’t always end in .html, and files ending in .html don’t always contain perfect HTML. To confuse the issue even further, sometimes you won’t even save a file at all, but rather type HTML straight into a big text box, the contents of which a computer will later insert in the middle of a bigger HTML file, like I’m doing now:

HTML beginner tutorial guide

What Makes a “Proper” HTML Page?

All right, so a single line of English doesn’t count as by-the-book HTML, that’s no surprise. What should we add to our simple file, then?

Tags

Tags are the most important element of HTML. A bit like how blog post tags identify the topics of articles, or hashtags identify which hilarious meme a Tweet is joining in on, HTML tags identify something about whatever it is they’re tagging. This is vague, I know, but you’ll see why.

For example, in our current page:

Is this HTML?

…what is “Is this HTML?”. It’s text, sure. Specifically, we could say it’s a paragraph of text. And in order to show this, we can tag the paragraph by wrapping it in <p> tags (p for paragraph – and no, before you ask, there’s no “sentence” tag):

<p>Is this HTML?</p>

Each tag starts with an opening chevron < and ends with a closing chevron >, with the name of the tag between the chevrons. Note that the second tag has a slash / directly before the tag name; this indicates that it’s a closing tag, and therefore marks the end of the paragraph started by the opening <p> tag. The whole paragraph (including tags), <p>Is this HTML?</p> can be called a p-block.

None of this makes the page display any differently, though; the browser was displaying the contents of the original file as if they were in a paragraph anyway. Some tags that will change the appearance of the text are b – for bold – and i for italic. Try this:

<p>Is <i>this</i> <b>HTML</b>?</p>

We’ve got tags within tags now: the italic-tagged text and the bold-tagged text are both inside the paragraph block; this is called a hierarchical structure. It’s like a tree, with the p being the trunk, and b and i being branches. I hope you can see that this wouldn’t make sense:

<p>Is <i>this</i> <b>HTML?</p></b>

…although, your browser would actually display that, because it is so lenient.

Anyway, save this and open it in your browser:

<p>Is <i>this</i> <b>HTML</b>?</p>

Click here to see mine. You’ll see that it displays with bold and italic text, like this:


Is this HTML?


Any experienced HTML developers reading this over your shoulder will be furiously scratching themselves and calling me a fool for using these exact tags – you’ll see why soon – but just ignore them for the moment.

Okay, now compare these three snippets:

<p>Is <i>this</i> <b>HTML</b>?</p>
<p>This is certainly a paragraph.</p>
<p>Is <i>this</i> <b>HTML</b>?</p><p>This is certainly a paragraph.</p>
<p>Is <i>this</i> <b>HTML</b>?</p>

<p>This is certainly a paragraph.</p>

How do you think they’ll each display?

The obvious answer is that the first will display the two paragraphs on separate lines, one after the other; the second will display the two paragraphs on one line; and the third will display them on separate lines with a huge gap between them.

This isn’t true.

All three cases will display in the same way, like so.

Why? Because HTML doesn’t care about carriage returns (new lines). It has a rule that says, by default, “paragraph blocks start on new lines”. Even this will display in the same way:

<p>Is
<i>this</i>
<b>HTML</b>?

</p>

<p>

This is
certainly
a paragraph.

</p>

While we’re at it, so will this:

<p>Is         <i>this</i>       <b>HTML</b>?</p>
<p>This is                 certainly              a paragraph.</p>

HTML does care about spaces, but only one at a time. If there are two or more in a row, they get condensed down to one.

Why? Well, it’s really part of a bigger theme that explains your developer friend’s itchiness:

Content, Not Presentation

Whenever a post on any Tuts+ site is tagged “Basix”, our WordPress software automatically adds a tiny speech bubble with a “b” inside over the top of the image at the top of the post . Similarly, my Twitter client is configured so that any Tweets that have been hashtagged “#bieberfever” are displayed in giant bold red text so that I don’t miss them.

But neither Basix nor #bieberfever imply anything about the presentation of the thing they are attached to; Basix says “this tutorial is written for beginners”, and #bieberfever says “this Tweet is about Justin Bieber”. They each imply something about the content. Their presentations change because of external rules that decide how certain types of content should be displayed.

HTML follows the same ideals, and that’s why the b and i tags are looked down upon. They only exist because when HTML was invented (about 18 years ago), the creators hadn’t decided on this “separate content from presentation” mindset, so browsers have (again, due to their lenience) continued to display bold and italic tags ever since.

Still, this doesn’t mean that you can’t use italic or bold text in your HTML files! No, you just have to use different tags, which identify something about the content rather than the presentation. See, when you add italics to a section of text, you’re trying to emphasize the content – so instead of using an i tag, you should use an em tag. And when you make some text bold, you’re trying to strengthen it on the page – so you should use a strong tag.

Your HTML should therefore look like this:

<p>Is <em>this</em> <strong>HTML</strong>?</p>
<p>This is certainly a paragraph.</p>

By default, your browser will display that in exactly the same way as it did when you used old b and i tags. You may well ask why we’d bother changing it, then – the answer lies in the phrase “by default”.

Individual web pages – even individual paragraphs – can tell the browser to display em and strong tags differently: suppose you decide that a dotted underline is a better way of strengthening the text, and small caps are a better way of showing emphasis. You can reconfigure em to do one and strong to do the other on your site, and the appearance of all the text will change, without you having to alter the textual content at all. But it wouldn’t make any sense to have the b-for-bold tag display a dotted underline, would it?

There are a few other tags like b and i that are no longer in use (said to be “deprecated”); you can find out more about any particular tag on W3Schools.

I’ll explain a bit more about changing the appearance of web pages later on. I can’t explain everything, as it’s a huge subject, with a Tuts+ site all to itself.

Required Tags

Okay, so we’ve got a basic HTML page that displays correctly, and contains no deprecated tags. Great! But there are some tags that every HTML page requires, officially. Let’s add them one by one.

<html>
<p>Is <em>this</em> <strong>HTML</strong>?</p>
<p>This is certainly a paragraph.</p>
</html>

The html tag says, “hey, browser, this is an HTML document!” To which the browser would presumably respond, “yeah, thanks, I’d guessed that!” if it were a sarcastic human being rather than a piece of software. All of the document should go inside the html tag; to go back to the tree metaphor, html should always be the trunk.

<html>
<body>
<p>Is <em>this</em> <strong>HTML</strong>?</p>
<p>This is certainly a paragraph.</p>
</body>
</html>

The body contains the actual content of the page. “As opposed to what?” As opposed to…

<html>
<head>

</head>
<body>
<p>Is <em>this</em> <strong>HTML</strong>?</p>
<p>This is certainly a paragraph.</p>
</body>
</html>

…the head tag, which contains information about the page, like…

<html>
<head>
<title>This is an HTML page</title>
</head>
<body>
<p>Is <em>this</em> <strong>HTML</strong>?</p>
<p>This is certainly a paragraph.</p>
</body>
</html>

…the title. If you look at the title bar of your browser with your old HTML page loaded, it’ll just say something like “page.html” (or maybe “Untitled”, or the name of the browser). If you use the code above, though, it’ll say “This is an HTML page”. Note that “This is an HTML page” does not appear anywhere in the actual content of the page, though: this illustrates the difference between the head and the body.

That HTML is getting a little hard to read now, so you might prefer to use the Tab key to indent the lines:

<html>
	<head>
		<title>This is an HTML page</title>
	</head>
	<body>
		<p>Is <em>this</em> <strong>HTML</strong>?</p>
		<p>This is certainly a paragraph.</p>
	</body>
</html>

Indenting lines like this also helps illustrate that tree-like structure. If you accidentally copied and pasted a tag at the wrong level, it’d be really obvious, like this:

<html>
	<head>
		<title>This is an HTML page</title>
	</head>
	<body>
		<p>Is <em>this</em> <strong>HTML</strong>?</p>
	</body>
		<p>This is certainly a paragraph.</p>
</html>

That second paragraph is clearly out of place.

Doctype

I’ve mentioned a few times that browsers are very forgiving when trying to display broken (or non-standard) HTML. This is a blessing and a curse.

It means that sloppy HTML will still be displayed, which is great for anybody that ever makes a mistake i.e. the whole of humankind – but different browsers will display non-standard HTML in different ways.

It means that the people that make the browsers can come up with all sorts of new tags and features that aren’t part of standard HTML but that do display in their browser, which is great for driving the power of what can be done with HTML forward, beyond the official standards – but not all browsers will support the same set. (For instance, years and years ago, Netscape Navigator allowed you to create blinking text using the <blink> tag, while Internet Explorer allowed you to create text that scrolled across the screen using the <marquee> tag; neither tag was supported by the other browser, and both effects were very annoying.)

It means that browser developers broke the rules of (or flat out ignored) some areas of the official HTML standards, so that there was a difference between how a page should display, and how it actually looked.

In a nutshell, it means that, even today, different browsers display the same pages differently.

To attempt to get around this we have doctypes. For example, stick this at the top of your page (even before the html tag):

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

…and the browser will display the page in “quirks mode”, meaning, “using the non-standard practices from the late 90s”. Replace it with this:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

…and it’ll display it in “standards mode”, meaning, “using the official HTML standards”. Except, some older browsers that are still in use, like Internet Explorers 6 and 7, still don’t fully follow all the standards. And different browsers still each have their own additional features.

Doctypes are a mess – there are lots and lots of them – but fortunately we don’t really have to worry about them, here at Activetuts+, because we’re focusing exclusively on HTML5. And HTML5 has only one doctype:

<!DOCTYPE html>

Ahhh. Okay, sure, older browsers don’t really know what to do with that, but they can’t handle HTML5 anyway, so it doesn’t matter to us. We’ve just got to hope that today’s browsers stick to the HTML5 standards and don’t get into that old mess again.

So now you should edit your HTML page to add a doctype:

<!DOCTYPE html>
<html>
	<head>
		<title>This is an HTML page</title>
	</head>
	<body>
		<p>Is <em>this</em> <strong>HTML</strong>?</p>
	</body>
		<p>This is certainly a paragraph.</p>
</html>

It’s a weird tag, because it doesn’t actually enclose anything (there’s no </!DOCTYPE html>), it’s got a space in it, and it’s partly in capitals. That’s because it’s not a tag at all, it just looks a bit like one because of the chevrons. Don’t worry about it.

Attributes

Okay, we’ve used this Language to Markup some Text, but what the heck makes that Text so “Hyper”, the H of HTML?

Hypertext is defined as text, displayed on some sort of electronic device, with hyperlinks to other pieces of text. (The term was coined in the 60s, which explains why it sounds so corny.) And you know what hyperlinks are: bits of text that link to other pages when you click them, like this.

We create hyperlinks using the a tag – for anchor, because you use it to anchor a URL to some text. No, I don’t know why they didn’t use h or l.

But this alone isn’t enough:

<!DOCTYPE html>
<html>
	<head>
		<title>This is an HTML page</title>
	</head>
	<body>
		<p>Is <em>this</em> <strong>HTML</strong>?</p>
		<p>This is certainly a paragraph.</p>
		<p>And <a>this</a> is a hyperlink.</p>
	</body>
</html>

I mean, how could it? There’s no URL there.

We have to use an attribute of the a tag, like so:

<!DOCTYPE html>
<html>
	<head>
		<title>This is an HTML page</title>
	</head>
	<body>
		<p>Is <em>this</em> <strong>HTML</strong>?</p>
		<p>This is certainly a paragraph.</p>
		<p>And <a href>this</a> is a hyperlink.</p>
	</body>
</html>

We’ve added an href (hypertext reference) attribute to the a tag, which will allow it to hold a URL (though we haven’t specified the URL yet). Note that it’s still an a tag, not an a href tag, and that the closing tag is still </a>, not </a href>; this is why tag names are always a single word, with no spaces.

To set the href’s value to a specific URL, we use an equals sign, and enclose the URL in quotes:

<!DOCTYPE html>
<html>
	<head>
		<title>This is an HTML page</title>
	</head>
	<body>
		<p>Is <em>this</em> <strong>HTML</strong>?</p>
		<p>This is certainly a paragraph.</p>
		<p>And <a href="http://active.tutsplus.com/">this</a> is a hyperlink.</p>
	</body>
</html>

Try it out. Clicking the link will take you to the Activetuts+ homepage.

Attributes make HTML a lot more powerful. Putting a p tag around some text just says, “this is a paragraph” – it attaches one piece of information to the text – but with attributes we can say so much more; here we’ve said, “the word ‘this’ is an anchor, and it refers to http://active.tutsplus.com/”.

Self-Closing Tags

This is all very plain, so let’s add an image.

Except… hmm, how exactly do we mark up a piece of text to make it an image? You might guess at something like this:

<image href="http://website.com/some_image.png">picture of a cat</image>

…which is a good guess, but not correct.

In this case, it makes no sense to have the image’s tag – which is img, by the way – tag any text. We write it (without any attributes, for now) like so:

<img />

The slash at the end indicates that the tag is closing itself. It’s a bit of a weird concept, and is where the whole idea of tags tagging text falls down a bit. If you prefer, you can call HTML tags elements instead.

Anyway, let’s insert this into our page:

<!DOCTYPE html>
<html>
	<head>
		<title>This is an HTML page</title>
	</head>
	<body>
		<p>Is <em>this</em> <strong>HTML</strong>?</p>
		<p>This is certainly a paragraph.</p>
		<p>And <a href="http://active.tutsplus.com/">this</a> is a hyperlink.</p>
		<img />
	</body>
</html>

Like the a tag, the img won’t display anything without any attributes. Let’s add some.

We’ll need an image file to use; this file has to be accessible by anyone reading your page, so while you could use the file path of a picture on your computer, you’d be the only one that could see it.

I’ll use my Twitter avatar, since that’s online, and hope it doesn’t change before you read this tutorial. It’s: http://a3.twimg.com/profile_images/1403171562/VectorMJWSquareTransparent.png, so, not exactly brief.

Rather than using href for the attribute that points to this URL, we have to use src (short for “source”) – after all, it’s not actually a hyperlink. So:

<!DOCTYPE html>
<html>
	<head>
		<title>This is an HTML page</title>
	</head>
	<body>
		<p>Is <em>this</em> <strong>HTML</strong>?</p>
		<p>This is certainly a paragraph.</p>
		<p>And <a href="http://active.tutsplus.com/">this</a> is a hyperlink.</p>
		<img src="http://a3.twimg.com/profile_images/1403171562/VectorMJWSquareTransparent.png" />
	</body>
</html>

If you load this page, you’ll see my avatar at the bottom – unless I’ve changed it or Twitter has gone down, in which case you’ll see a “broken image” symbol.

In case the image does break, we can add an alternative piece of text to be shown instead, using the alt attribute:

<!DOCTYPE html>
<html>
	<head>
		<title>This is an HTML page</title>
	</head>
	<body>
		<p>Is <em>this</em> <strong>HTML</strong>?</p>
		<p>This is certainly a paragraph.</p>
		<p>And <a href="http://active.tutsplus.com/">this</a> is a hyperlink.</p>
		<img src="http://a3.twimg.com/profile_images/1403171562/VectorMJWSquareTransparent.png"
			alt="MichaelJW's Twitter Avatar" />
	</body>
</html>

(Remember, HTML doesn’t care about tabs, new lines, and spaces, so it doesn’t matter that I’ve shoved the new attribute on a separate line.)

Try changing the src URL to one that won’t work (like, http://blahblahblah/), and you’ll see the alternative text (click here for an example). Well, you might, depending on your browser; the HTML 5 standards suggest doing this, but don’t insist on it. Chrome doesn’t do it, much to my surprise.

Anyway, it’s a good habit to get in to, because it also allows blind people – who are reading your page via text-to-speech software – to hear the contents of the images.

Nested Tags

We’ve seen that tags can be nested, as in our case of some italic emphasized text within a paragraph, or paragraphs within a body, but I want to make it clear that you can make things more complex if you wish.

For example, you can mark up some emphasized text with an anchor:

<!DOCTYPE html>
<html>
	<head>
		<title>This is an HTML page</title>
	</head>
	<body>
		<p>Is <em>this</em> <strong>HTML</strong>?</p>
		<p>This is certainly a paragraph.</p>
		<p>And <a href="http://active.tutsplus.com/"><em>this</em></a> is a hyperlink.</p>
		<img src="http://a3.twimg.com/profile_images/1403171562/VectorMJWSquareTransparent.png"
			alt="MichaelJW's Twitter Avatar" />
	</body>
</html>

…as long as you don’t do something silly like:

<p>And <a href="http://active.tutsplus.com/"><em>this</a></em> is a hyperlink.</p>

You can even tag an image with an anchor, as if it were a piece of text:

<!DOCTYPE html>
<html>
	<head>
		<title>This is an HTML page</title>
	</head>
	<body>
		<p>Is <em>this</em> <strong>HTML</strong>?</p>
		<p>This is certainly a paragraph.</p>
		<p>And <a href="http://active.tutsplus.com/"><em>this</em></a> is a hyperlink.</p>
		<a href="http://twitter.com/MichaelJW/">
			<img src="http://a3.twimg.com/profile_images/1403171562/VectorMJWSquareTransparent.png"
				alt="MichaelJW's Twitter Avatar" />
		</a>
	</body>
</html>

See the results here.

There are a ton of other tags I could cover, like h1, h2, h3 (etc.) for headings; pre for inserting big blocks of sourcecode or ASCII art (inside which, unusually, HTML does pay attention to extra spaces and new lines); table for inserting tabulated information; input for adding buttons and textboxes; iframe, which lets you insert a whole extra webpage inside the current webpage; and more – but this is enough about the content, because we need to talk about another aspect of HTML.


Presentation: CSS

HTML – the language – isn’t concerned with presentation, it’s true. But HTML pages need to be able to modify their presentation, or everything would be Times New Roman with purple links, like in the examples we’ve seen so far!

For this purpose we have another language, which we embed inside HTML pages, which is all about presentation: Cascading Style Sheets (CSS).

A Simple Example

Remember earlier I mentioned that we could make strong tags display with a dotted underline, and em tags display in small caps? We can do that using the CSS language. It looks like this, on its own:

strong {
	border-bottom: 1px dotted;
}

em {
	font-variant: small-caps;
}

Doesn’t look at all like HTML, does it? You can probably read it well enough, though. We have the name of a tag, followed by a pair of curly brackets (“braces”), inside which are all the properties of the text that we wish to set. Each property then has a value, with a colon separating the property from its value, and a semi-colon at the end of each property-value pair. Together, this is called a style sheet. Simple enough.

We apply a style sheet to the page like so:

<!DOCTYPE html>
<html>
	<head>
		<title>This is an HTML page</title>
		<style type="text/css">
			strong {
				border-bottom: 1px dotted;
			}

			em {
				font-variant: small-caps;
			}
		</style>
	</head>
	<body>
		<p>Is <em>this</em> <strong>HTML</strong>?</p>
		<p>This is certainly a paragraph.</p>
		<p>And <a href="http://active.tutsplus.com/"><em>this</em></a> is a hyperlink.</p>
		<a href="http://twitter.com/MichaelJW/">
			<img src="http://a3.twimg.com/profile_images/1403171562/VectorMJWSquareTransparent.png"
				alt="MichaelJW's Twitter Avatar" />
		</a>
	</body>
</html>

Test the page. You’ll see that the word “this” now uses small capitals (in both cases, because they’re both emphasized), and “HTML” has a dotted underline.

However, the em tag still has an italics effect, and strong is still displaying words in bold. What gives?

This is what the “Cascading” in “Cascading Style Sheets” refers to: the browser has its own, default CSS styles (like “em” means “italics”), and these cascade down, so that the CSS styles that you apply are simply added on top, rather than replacing the existing ones. It’s as if the browser has a style sheet that looks like this:

strong {
	font-weight: bold;
}

em {
	font-style: italic;
}

(Yes, I know, it’s counter-intuitive not to use the same property to set italics and bold styles.)

This then cascades down, so that it’s as if the overall style sheet – including your variations – looks like this:

strong {
	font-weight: bold;
	border-bottom: 1px dotted;
}

em {
	font-style: italic;
	font-variant: small-caps;
}

Note that your properties are added after the browser’s own. Since the browser computes these properties one at a time, in order, we can cancel out the browser’s styles by changing our set of styles like so:

strong {
	border-bottom: 1px dotted;
	font-weight: normal;
}

em {
	font-variant: small-caps;
	font-style: normal;
}

Then, the overall style sheet will look like this:

strong {
	font-weight: bold;
	border-bottom: 1px dotted;
	font-weight: normal;
}

em {
	font-style: italic;
	font-variant: small-caps;
	font-style: normal;
}

When the browser comes across text that’s been tagged strong, it’ll say, okay, first, I need to make this bold. Then, I need to give it a 1 pixel thick, dotted border, at the bottom of the text. Then, I need to make the font weight normal. Wait, didn’t I make this bold a second ago? Oh well, never mind.

Result: normal-weighted text, with a dotted border across the bottom. Let’s incorporate this new set of styles into our page:

<!DOCTYPE html>
<html>
	<head>
		<title>This is an HTML page</title>
		<style type="text/css">
			strong {
				border-bottom: 1px dotted;
				font-weight: normal;
			}

			em {
				font-variant: small-caps;
				font-style: normal;
			}
		</style>
	</head>
	<body>
		<p>Is <em>this</em> <strong>HTML</strong>?</p>
		<p>This is certainly a paragraph.</p>
		<p>And <a href="http://active.tutsplus.com/"><em>this</em></a> is a hyperlink.</p>
		<a href="http://twitter.com/MichaelJW/">
			<img src="http://a3.twimg.com/profile_images/1403171562/VectorMJWSquareTransparent.png"
				alt="MichaelJW's Twitter Avatar" />
		</a>
	</body>
</html>

Load the page. Perfect!

Other Sources of CSS

Sticking the style sheet in a style tag within the head of a page is called embedding it, but there are other ways we can affect the overall style of the page.

For instance, we can put style sheet into its own .css file (called an external style sheet), and tell the page to use it. To do that, we use a place a self-closing link tag within the head, whose rel attribute is stylesheet and whose href tag is the URL of a .css file.

You should be able to figure out how to write that from the description; try it with the style sheet we use at Activetuts+: http://active.tutsplus.com/wp-content/themes/tuts/style.css. If you need help, expand the code box below.

<!DOCTYPE html>
<html>
	<head>
		<title>This is an HTML page</title>
		<link rel="stylesheet" href="http://active.tutsplus.com/wp-content/themes/tuts/style.css" />
		<style type="text/css">
			strong {
				border-bottom: 1px dotted;
				font-weight: normal;
			}

			em {
				font-variant: small-caps;
				font-style: normal;
			}
		</style>
	</head>
	<body>
		<p>Is <em>this</em> <strong>HTML</strong>?</p>
		<p>This is certainly a paragraph.</p>
		<p>And <a href="http://active.tutsplus.com/"><em>this</em></a> is a hyperlink.</p>
		<a href="http://twitter.com/MichaelJW/">
			<img src="http://a3.twimg.com/profile_images/1403171562/VectorMJWSquareTransparent.png"
				alt="MichaelJW's Twitter Avatar" />
		</a>
	</body>
</html>

Click here to see the result. It’s a mess, to be honest, but you can see that it’s loaded the styles.

External style sheets are applied after the browser’s defaults, but before any embedded ones. This means you can create a single external style sheet to use across your entire web site, and then tweak it by embedded specific styles for each page, if you wish.

In fact, you can get even more specific, and apply a style to just one single element. This is called an inline style, and it’s done by entering the CSS into the style property of a tag:

<!DOCTYPE html>
<html>
	<head>
		<title>This is an HTML page</title>
		<link rel="stylesheet" href="http://active.tutsplus.com/wp-content/themes/tuts/style.css" />
		<style type="text/css">
			strong {
				border-bottom: 1px dotted;
				font-weight: normal;
			}

			em {
				font-variant: small-caps;
				font-style: normal;
			}
		</style>
	</head>
	<body>
		<p>Is <em>this</em> <strong>HTML</strong>?</p>
		<p>This is certainly a paragraph.</p>
		<p>And <a href="http://active.tutsplus.com/"><em>this</em></a> is a hyperlink.</p>
		<a href="http://twitter.com/MichaelJW/">
			<img src="http://a3.twimg.com/profile_images/1403171562/VectorMJWSquareTransparent.png"
				alt="MichaelJW's Twitter Avatar" />
		</a>
		<p style="color: red;">Check it out, this paragraph is red.</p>
	</body>
</html>

Check out the result of the above change. Inline styles are applied after all the other styles.

Note that you don’t have to enter the name of the element and use curly braces – you’ve already defined which tag you want to style. You can apply multiple styles within the same style attribute; just type them one after the other (no new line needed), and make sure there’s a semi-colon between each of them.

What if you want to style just a few words within a paragraph? You could wrap them in an em tag, and style that tag like so:

<p>Only <em style="font: red;">some of these words</em> are red.</p>

…but then they’ll be in italics too, right? So you cancel that out like so:

<p>Only <em style="font: red; font-style: normal;">some of these words</em> are red.</p>

…but that’s no good either, because you can’t guarantee that the em tag doesn’t have other styles attached to it as well – and since you don’t know, you can’t cancel them all out. Fortunately, there’s a tag to help.

The <span> Tag

The span tag provides no visual changes by itself, which means it’s perfect for our example above:

<p>Only <span style="font: red; font-style: normal;">some of these words</span> are red.</p>

It’s unlikely – not impossible, but unlikely – that someone will have applied certain styles to all span tags in an embedded or an external style sheet, so you should be safe using this.

Ah, but now look what we’re doing. We’re applying presentation rules right there in the content – exactly the sort of situation that the em and strong tags were invented to avoid! It’s not technically invalid HTML, but it’s still dodgy, and should be used sparingly or not at all.

However, sometimes you will want to say, “this section of text is different to the others, but none of the existing HTML tags describe that difference very well.” Maybe you’re writing a page about animals, and you decide that it would be useful to tag all the words that represent species – like “cat” and “dog” and so on – so that you can apply an style to all of them at once later.

HTML doesn’t have a species tag, though. It’s tempting to say, “well, on my website, I’m going to say that the strong tag is always used to represent species” – but this is a bad idea; it’s not what strong is for.

Instead, you can use classes. Any tag can be given a class like so:

<p>I have a <span class="species">cat</span>, a <span class="species">dog</span> and a <span class="species">fish</span>.</p>

Setting a class doesn’t do anything on its own, but you can then define a style for each class in your style sheet:

<!DOCTYPE html>
<html>
	<head>
		<title>This is an HTML page</title>
		<link rel="stylesheet" href="http://active.tutsplus.com/wp-content/themes/tuts/style.css" />
		<style type="text/css">
			strong {
				border-bottom: 1px dotted;
				font-weight: normal;
			}

			em {
				font-variant: small-caps;
				font-style: normal;
			}

			.species {
				outline: 1px dashed blue;
			}
		</style>
	</head>
	<body>
		<p>Is <em>this</em> <strong>HTML</strong>?</p>
		<p>This is certainly a paragraph.</p>
		<p>And <a href="http://active.tutsplus.com/"><em>this</em></a> is a hyperlink.</p>
		<a href="http://twitter.com/MichaelJW/">
			<img src="http://a3.twimg.com/profile_images/1403171562/VectorMJWSquareTransparent.png"
				alt="MichaelJW's Twitter Avatar" />
		</a>
		<p style="color: red;">Check it out, this paragraph is red.</p>
		<p>I have a <span class="species">cat</span>, a <span class="species">dog</span> and a <span class="species">fish</span>.</p>
	</body>
</html>

Note that to define a style for a class, rather than a tag, you have to place a dot before its name in the CSS.

Take a look at the page now. It looks like something you might have found on Geocities about ten years ago, but at least it’s showing some important HTML principles. Classes’ styles are added after embedded styles and before inline ones, so the whole cascading order looks like this:

  • Browser defaults
  • External
  • Embedded
  • Classes
  • Inline

So, we’ve looked at content and presentation within HTML files. There’s one important aspect left.


Code: JavaScript

HTML and CSS are not programming languages. They don’t actually do anything. They just tell text how it is structured and how it should look.

JavaScript is a programming language. It does stuff.

One of the simplest examples of JavaScript code is alert('Hello'). When the browser runs this code, it’ll make a little dialog box appear, with the word “Hello” inside.

Much like with CSS, we can embed JavaScript into a page, add it via an external file, or attach it to a single tag. To embed it, we put it inside a script tag in the head, rather than a style tag:

<!DOCTYPE html>
<html>
	<head>
		<title>This is an HTML page</title>
		<link rel="stylesheet" href="http://active.tutsplus.com/wp-content/themes/tuts/style.css" />
		<style type="text/css">
			strong {
				border-bottom: 1px dotted;
				font-weight: normal;
			}

			em {
				font-variant: small-caps;
				font-style: normal;
			}

			.species {
				outline: 1px dashed blue;
			}
		</style>
		<script>
			alert('Hello');
		</script>
	</head>
	<body>
		<p>Is <em>this</em> <strong>HTML</strong>?</p>
		<p>This is certainly a paragraph.</p>
		<p>And <a href="http://active.tutsplus.com/"><em>this</em></a> is a hyperlink.</p>
		<a href="http://twitter.com/MichaelJW/">
			<img src="http://a3.twimg.com/profile_images/1403171562/VectorMJWSquareTransparent.png"
				alt="MichaelJW's Twitter Avatar" />
		</a>
		<p style="color: red;">Check it out, this paragraph is red.</p>
		<p>I have a <span class="species">cat</span>, a <span class="species">dog</span> and a <span class="species">fish</span>.</p>
	</body>
</html>

Check out the result.

Linking to external JavaScript is easy, too; you put your code in a .js file, and add it to your page like this:

<script src="http://example.com/folder/someCode.js"></script>

So, it’s the same tag as we used to embed some code, except it’s empty, and it has a src attribute. I’m not going to give an example of this, but feel free to try your own.

Inline JavaScript – i.e., attaching code to specific elements – works a little differently than inline CSS. A first guess at how we could do this might be:

<span script="alert('Hello')">Some code is attached to this text.</span>

…but, if you think about it, this doesn’t make sense. When would the alert appear? When the page loaded? When that specific section of text loaded? When it was on the page? When it was clicked? You can’t guess, and neither can the browser.

Instead, there are a whole bunch of attributes that you can stick JavaScript into; they’re called event attributes, and they trigger the JavaScript inside them for different reasons.

For instance, one such attribute is onclick, which triggers the JavaScript inside it whenever the user clicks the contents of the tag with their mouse. It looks like this:

<!DOCTYPE html>
<html>
	<head>
		<title>This is an HTML page</title>
		<link rel="stylesheet" href="http://active.tutsplus.com/wp-content/themes/tuts/style.css" />
		<style type="text/css">
			strong {
				border-bottom: 1px dotted;
				font-weight: normal;
			}

			em {
				font-variant: small-caps;
				font-style: normal;
			}

			.species {
				outline: 1px dashed blue;
			}
		</style>
		<script>
			alert('Hello');
		</script>
	</head>
	<body>
		<p>Is <em>this</em> <strong>HTML</strong>?</p>
		<p>This is certainly a paragraph.</p>
		<p>And <a href="http://active.tutsplus.com/"><em>this</em></a> is a hyperlink.</p>
		<a href="http://twitter.com/MichaelJW/">
			<img src="http://a3.twimg.com/profile_images/1403171562/VectorMJWSquareTransparent.png"
				alt="MichaelJW's Twitter Avatar" />
		</a>
		<p style="color: red;">Check it out, this paragraph is red.</p>
		<p>I have a <span class="species">cat</span>, a <span class="species">dog</span> and a <span class="species">fish</span>.</p>
		<p onclick="alert('I can see it in your eyes...')">Is it me you're looking for?</p>
	</body>
</html>

Load the page and click the last paragraph – yes, you can click it, even though it’s not a hyperlink. Tada! You’re half-way to programming a duet.

That’s Not All

I’m not going to go into a lot of detail on JavaScript here, because that’s what the bulk of our future HTML5 tutorials are going to focus on. However, you should know that JavaScript can do a lot more than make annoying dialog boxes appear.

Besides making the browser do stuff on its own, JavaScript can alter and create HTML (as well as CSS and JavaScript code itself). It’s hard to overstate how powerful that makes it.

And as if that weren’t enough: if you’re using Chrome, you can play Angry Birds in your browser, written in JavaScript, HTML, CSS… and, okay, a touch of Flash for the sounds.


What Next?

If you’re interested in learning more about the design and appearance of webpages, check out our sister site Webdesigntuts+. One of our other sister sites, Nettuts+, has already published a lot of articles on HTML, CSS, and JavaScript that you should dig in to.

We’ll be focusing on the latest version of HTML – HTML5 – and using it to create apps and games for modern browser. If you want to keep up to date with what we’re doing, then you can follow us on Twitter, like us on Facebook, subscribe to us through RSS, or sign up to our free email newsletter.

Here’s one last tip for the curious: you can view the HTML of any web page on the Internet by right-clicking a blank area and selecting “View Source”. I should warn you: some sites make the markup all messy so that you can’t read (and copy) it; some sites’ markup is just naturally messy. But try it out!



View full post on Activetuts+

Sep 6, 2011 Posted on Sep 6, 2011 in Hints and Tips | 10 comments

Animate a Cartoon Explosion With Flash Professional – Basix

In this tutorial we’ll show you how to animate an awesome explosion in Flash, which you could use for an cartoony action game. We take you from conception to completion, then show you how to export it as well as how to import it into other scenes.


Final Result Preview

Let’s take a look at the final result we will be working towards:


Step 1: Choose the Type of Explosion You Would Like

Decide what kind of explosion would be best fitting for your scene. Is it a small explosion? A nuke? A 60′s Batman-esque, flashy, “WHAM”? In this case we will be doing a smaller explosion, but with experience you could do anything you want.

What you will be creating in this tutorial.

Step 2: Look for References

Once you know what you want to animate look for reference. The Internet is amazing for this because you can just search for movie clips related to what you’d like to do and carefully study them.

Searching for explosions on Youtube.

Step 3: Begin to Draw

Once you are ready grab a few pieces of paper and begin to draw your explosion. Animation is planned through keyframes, which are generally the most extreme parts of the animation which tell the rough story of how something is going to move. In this case, the first thing that you should be thinking about is the initial flash of light.

Drawing of the first frame of animation

Step 4: Draw All the Keyframes

Next, draw the keys explaining how the smoke and light comes out of the bomb. You will at the very least want one where the smoke is first coming out of the light, then one when the smoke is at its largest and most extreme, and then a frame at the end. Here are our keyframe drawings, which illustrate this process:

Drawing of all of the keyframes.

Step 5: Draw All the In-Betweens

Draw the in-betweens for these frames. Basically, you are now drawing all of the frames which fit in the middle of these keyframes. We will include our sketches here for reference.

Every single frame drawing.

Step 6: Scan Your Drawings

At this point we scan all of our drawings so that we can trace them in Flash.

A photo of a scanner.

Step 7: Change the Basic Flash Settings

Open Flash and change your settings to whatever would be the best fit for your current scene. You can see all of your basic settings in the properties panel on the right hand side of the screenshot. In our case, we will be working at 550x500px and 24 frames per second, with a white background.

The basic settings in Flash.

Step 8: Import Your Drawings

Next you should import all of your line drawings into Flash Pro’s Library. The Library is basically a place where all of the files that you are using in your animation are stored for safe-keeping. You can do this by going to File > Import > Import to Stage, then selecting all of your drawings and hitting Open.

After this they will appear all on the same keyframe, but if you select them all, right-click and hit “Distribute to Layers,” they will appear as seperate layers, all on the same keyframe. Then you can simply drag and drop individual keys into the right positions, either on their own layers on all on one layer, whichever you’d prefer.

Showing how to get to Flash's Library.

Step 9: Draw Your Initial Lines

Add a new layer to your timeline, then begin to draw over your old lines using the Line tool. We generally do not bother using the brush tool because you end up with too many nodes on the lines which can make things extremely difficult to change in any way later. What you will basically need to do is draw lines using the line tool, then use the selection tool to manipulate the curve between the two points. (More Flash drawing tips are available here.)

Showing me drawing and then manipluating a line.

Step 10: Convert Lines to Fills

Once the frame has been entirely traced with the line tool we select all of the lines, then go to Modify > Shape > Convert Lines to Fills. Occasionally there will be glitches where bits of the line disappear. If this happens then start off by selecting smaller chunks of the image, then eventually doing the whole graphic together. Once you do this you can then edit the line depth using the selection tool and clicking and dragging on the edges of lines.

Showing the Convert Lines to Fills Dialogue Box

Step 11: Color Your Drawings

Color in the lines using the paint bucket tool.

Paint Bucket Tool

Step 12: Finish All of the Frames of Animation

Repeat Steps 9-11 until all of the frames are finished.

Final Frame of Animation Completed

Step 13: Organize Your Animation

Select everything on a frame, hit F8 and turn it into a Symbol. Properly name it and it will appear in your library to be used and re-used at any time. Organization is really important while you’re animating. Things can get confusing fast if you don’t name and sort everything properly so please do so. You can even create folders in the library.

Showing the Convert to Symbol Dialogue

Step 14: Onion Skinning

One important tool which can really help you animate is the Onion Skin tool. With Onion Skinning you can easily view the frames closest to the one that you are editing so that you can tell right away if a piece of animation is going to work as planned or not. The Onion Skin button is located at the bottom of your timeline.

Onion Skin Tool

Step 15: Preview the Animation

To preview your full animation at any time, go to Control > Test Movie > Test. It will preload your whole animation and then show you exactly how it will look once exported.

Test Movie Dialogue

Step 16: Export the Movie

When you’re ready to export just go to File > Export > Export Movie. Name it whatever you’d like, pick .swf from the drop down menu, and then hit save. Depending on the size of your animation you may have to wait a short while.

Export Movie Dialogue

Step 17: Export as a GIF

Exporting .gif images is nearly the same. When you hit File > Export > Export Movie just pick .gif instead of .swf from the drop-down menu.

GIF Export Dialogue

Step 18: Import your Animation into an Existing Scene

To import an explosion into an already exisitng scene, first open both scenes. Then, select all of the frames of the explosion animation on the timeline, copy all of the frames, and then hit Ctrl + F8. A dialogue will appear. Name the explosion, then save it as a Graphic. Hit OK. A blank screen should appear with no animation on it. Then click on the first frame of the new timeline and paste all of your frames. After this hit the “Scene 1″ button under the timeline but above the animation window to go back to your original timeline. Once you do this your animation should be in the Library. Select your animation in the library, right click and copy it. You will then be able to paste it into the library of any other FLA that you have open.

A compilation of screengrabs related to the text.

Step 19: Create a Movie Clip

Making movie clips is almost the same as what we described in the previous step. To create a movie clip, follow the instructions from the last step exactly, but pick “Movie Clip,” instead of “Graphic,” when you reach the dialogue after hitting Ctrl + F8. The difference between a Graphic and a Movie Clip is that the Movie Clip can be uniquely identified using ActionScript, which is the coding language that Flash uses to make games and interactive media. When the movie is compiled a copy is created from the library and transformed for the animation. The copy can be blurred, scaled, etc., during runtime, without having to create separate animations at design time, thus cutting down on the amount of computer memory needed and keeping the SWF file size small.

Create New Symbol -- Movie Clip.

Step 20: Create a Sprite Sheet

To create a sprite sheet of your animation, first hit File > Export > Export Movie and select PNG sequence to create a set of PNG graphics, one for each frame. After they are created you can use any image editing software (such as Photoshop) to import them as a batch and then copy/paste them all into one larger image file.

Screenshot showing export as PNG

Alternatively, you could make your Flash scene larger, make each frame of animation appear at once, and then move the individual images into place before exporting a single image.

Example sprite sheet
Click to enlarge.

A third option is to use Keith Peters’s tool, SWFSheet.

The final result.

We hope you enjoyed this tutorial! If you make an explosion with it, please share it in the comments :)



View full post on Activetuts+

Jun 13, 2011 Posted on Jun 13, 2011 in Hints and Tips | 1 comment

Coffee Break Quiz #1: ActionScript 3 Basix

Have you seen the quizzes over on Nettuts+? They’re brilliant. So we’re doing some too :)

Grab a coffee and have a go at these 10 questions on ActionScript 3. If you ace them and feel like telling the world, share your score on Twitter! Feel free to let us know if there are any specific quiz topics you’d like to see.



How The..?

This quiz was built with the jQuizzy Quiz Engine by Siddharth, ace reviewer for Envato. jQuizzy is available for purchase over on Codecanyon :)



Thanks also to Orman Clark and MediaLoot for their graphical contributions to the Activetuts+ Coffee Break Quizzes.



View full post on Activetuts+

May 27, 2011 Posted on May 27, 2011 in Hints and Tips | 10 comments

AS3 101: Variables – Basix

Twice a month, we revisit some of our readers’ favorite posts from throughout the history of Activetuts+. This classic tutorial was first published in June, 2009 and was the first in what has become an astounding series.

This is the beginning of a series which will walk through some of the fundamental concepts of programming, as they apply to ActionScript 3.0. To kick things off, we’ll talk about variables.


AS3 101

This tut is aimed squarely at those who have little-to-no scripting experience, but if you’ve used variables without really getting into the intricacies of datatyping and casting, you may want to follow along.

Thanks also to Davide Di Stefano for allowing us to deface his icon.


Introduction

Over the following steps, we’ll build a simple example, the main feature of which is the row of buttons that act as a group. The currently selected button has a different appearance, it can’t be clicked on again and the appearance is restored to its original state when another button is clicked. We’ll use a variable to keep track of what’s going on.


Step 1: What are Variables?

First things first: let’s define what a variable is. If you remember high school mathematics, you may recall that variables are "stand-in" values. That is, they are symbols (usually single letters, such as "x", or the "E" and "m" in E=mc2) which represent a numeric value. It is understood that the value might change depending on other factors in an equation.

In programming, a variable is exactly the same thing, with two main exceptions. First, in programming, a variable can hold more than just a number. It can hold a sequence of text characters (called a "string"), it can denote true or false (called a "boolean"), or it can hold something much more complex, like a date, an XML document, or a movie clip.

The second main difference with mathematics is that programming variables usually have descriptive names, rather than just a single-letter name. There are exceptions, of course: "x," "y," and "z" are commonly used to reference positions and "i" is commonly used denote the current iteration through a loop. A name which is relevant to the value being stored is not only common, but also helpful in keeping your program legible. For instance, if you wanted to keep track of how many particles you have on screen, you might name your variable "particleCount" or "totalParticles."

Like mathematic variables, programmatic variables have the potential for being changed during the course of the program. For instance, if you started with 10 particles, the variable "particleCount" would have the numeric value of 10. However, if you generated 10 more particles, the variable would then have the numeric value of 20. This is one of the key features of variables. You have a name that references a value, but that value is not necessarily going to be the same every time you access it. This is a mysterious but powerful aspect of variables. You’ll learn to appreciate this, even if it’s confusing at first.

To sum up this definition, a variable is basically a container to which you assign a name and in which you put a value. You can always get the value contained inside by referencing the variable by name and you can put a new value inside the container at any point. Any time you access the variable by name, you get the current value contained therein. For further reading, you may want to see what Wikipedia has to say about variables.


Step 2: Declaring a Variable

Enough theory, let’s actually get to work with making variables. Create a new Flash document (ActionScript 3.0). Click on the first frame of the first layer (it should be the only frame).

Open up the Actions panel by choosing Window > Actions (or pressing F9 on Windows or Opt-F9 on Mac).

In the Actions panel, type the following:

var message;

At this point, the varible is declared. This means that the container exists, but currently has no associated value.

This is the bare minimum you need to declare a variable. The word "var" is known as a keyword, meaning it’s reserved by the ActionScript language and has a specific meaning. In this case, it declares a variable. It needs to be followed by the variable name you want to use; if you don’t follow the var keyword with a variable name you’ll get an error when you try to test the movie.


Step 3: Naming your Variables

There are a few rules you should follow when naming your variables. Some are enforced by the ActionScript compiler, others are just conventions which, when followed, help you and others make better sense of your code.

First, the ActionScript language dictates that you can only use certain characters in your variable name. These are any alpha-numeric characters (letters and numbers), the underscore and the dollar sign. Any other character (hyphens, the space, the period, etc) is not allowed. Usually this is because many other characters have special significance in ActionScript.

ActionScript also imposes the rule that the variable name must not start with a number. Numbers are, however, allowed after the first character.

It also bears mentioning that ActionScript is case-sensitive, meaning that you must match the letter’s case when referring to a variable. In otherwords, the variable "message" is not the same as the variable "MESSAGE". This may seem restrictive as first, but there are actually good reasons for enforcing this. Space doesn’t permit a discourse on these reasons, however. For now, just learn to type your variables’ names exactly the same each time you want to use them.

The ActionScripting community at large has come to a general consensus on how to name your variables, although the following rules are more conventions and guidelines, rather than being enforced by ActionScript.

For starters, you should use descriptive names. This is a sort of self-documenting technique. If you name your variable "message," it’s likely you already have an idea of what the intended role of the contained value is. If it were simply "m," then that’s far less clear. It’s tempting to use abbreviated variable names and while you are initially writing your script it might mean less typing and still make sense. The next person to look at your code, or you yourself six months later, will likely be confused.

Another convention is the use of camel case. This is a technique for turning two or more words into a single word. Remember that you can’t use spaces (or any other white space, for that matter) in your names, so if you wanted to use the phrase "total particles" you have to find a way of getting rid of that space. "totalparticles" works, but the separation between the words is lost. Camel case is a method of capitalization that says that the entire word is lower case except for the first letter of each word, with the exception of the first letter of the first word. In other words, applying camel case to "total particles" results in "totalParticles".

There are more guidelines for choosing variable names, but they start to get more esoteric from here. For now, keep in mind the above rules and you’ll be off to a great start. Wikipedia has a few articles on the subject, including a short section in the previously linked article on variables in general, this article on naming conventions, and a short article on an effect called shadowing. Some other interesting reads are this list of bad variable names,this pronouncement of the two worst variables names ever and this anecdote describing why variable names matter.


Step 4: Setting a Value

Now that our variable is declared, we can put a value into it. On the next line of the Actions panel, type the following code:

message = "Hello";

We start by simply using the variable by its name. Then we follow it with an equals sign, which is known as the assignment operator. Following that, we have a quoted sequence of characters (ending with a semi-colon, which is just the way you end lines in ActionScript – you’ll see a lot of terminating semicolons in code).

The assignment operator requires that there be something on either side of it. It works by taking the value on the right side ("Hello", in this case) and putting it into the variable on the left side (message).

If we were to run this code, we would have a variable named "message," which contains a value of "Hello." It’s not doing anything else, so there’s nothing to see at the moment, but it may be a good idea to test the movie anyway to make sure you don’t get any errors, in case you typed something in wrong.

The script should look like this so far:


Step 5: Getting the Value

We now have a named container that has a value inside of it. Let’s access that value. In this case, we’ll simply trace the value to the Output panel.

On a new line of code, write the following:

trace(message);

The whole script will look like this:

As you may know, the trace function takes whatever you pass to it in between the parentheses and puts it into the Output panel. When you test the movie, you should see the Output panel open automatically and the value of the message variable (“Hello”, without the quotes) printed to it.

Any time you use the variable by name and are not putting it on the left side of the assignment operator (the equals sign), you are asking ActionScript to get the value contained by the variable and use that value. This is called evaluating the variable.


Step 6: Manipulating the Value

Now let’s prove that we can put different values into the same container. On the next line, let’s set the value of the message variable again:

message = "How are you?";

And then on the line after that, trace it out again:

trace(message);

The whole script will look like this:

Run the movie and you should now have two traces:

Notice that lines 3 and 5 are identical – they both trace message, but they produce different results! Each time we ask for message to be traced, the current value of the variable is evaluated and used. First it gets set to "Hello" and that shows up in the Output panel. After that we set it to "How are you?" and then that shows up in the Output panel.

It’s not rocket science, but this is one of the more confounding aspects of using variables. If you can master this, you’ll be well on your way to becoming an ActionScript guru.


Step 7: Understanding Datatypes

ActionScript supports something called strong typing. It’s an interesting language in that it’s only strongly-typed if you tell it to be so and it can be strongly-typed at certain points and weakly-typed in others. There is something to be said for the ease of use of a weakly-typed language, but most serious programmers will be able to talk for a few hours on the merits of strong typing. So what is it?

Strong typing simply means that when we declare a variable, we can also declare what kind of value can be put into it. That is, if we say that our message variable can only contain a string (as it happens to do so currently), then if we tried to put a number or date into it, ActionScript will complain in the form of an error. Causing errors might seem like a hindrance, but when you empower the computer to catch your errors for you, you actually end up saving time. Weakly typing your variables will avoid compiler errors, but might allow logical errors (for instance, trying to uppercase a number), in which case things can fail without warning. Allowing room for compiler errors through strongly-typing your code actually saves you time in the long run.

A datatype is, in a nutshell, the type of data that a value is. That is, values can be a string, a number, a boolean, a date, an XML document, a movie clip and many more built-in types – even types you create. Our message variable is implicitly of type String (note the capital "S"), so let’s make that type explicit. We’ll make our code strongly-typed, by decalring a datatype. Back on the first line of code, where we declare the message variable, modify it to read:

var message:String;

The colon specifies that what’s about to follow is a datatype and then you’ll see the datatype itself. All built-in datatypes will start with a capital letter and that is a common convention for custom datatypes as well. We won’t be getting into writing custom datatypes, however.

If you run the code at this point, you should see that it functions exactly the same.

For a longer discourse on datatypes and strong typing, head over to Wikipedia.


Step 8: Causing an Error

We can, however, illustrate how strong typing works by intentionally causing an error. Let’s add some more code, assigning the variable to yet another value. This time, though, we’ll try to put a number into it instead of a String. At the end, type the following:

message = 42;
trace(message);

Test the movie and you should see the following error:

1067: Implicit coercion of a value of type int to an unrelated type String.

The language is a little archaic, but it simply means that we have a number (or an "int") value and we tried to put it into a variable that was previously declared to only contain Strings.

Let’s throw another error. Delete the two lines of code you just added and replace them with the following line:

isNaN(message);

Then run the movie. You should get the following error:

The isNaN() function expects a number to be passed in to it through the parentheses (NaN means Not a Number, which is a special value meaning a number that doesn’t actually have a value. This function tests for that case). Since we’re passing in a String, we get basically the reverse error of what we had before.

Note that if you remove the String datatype from the variable and then re-run these two experiments, you won’t get an error. The code will actually execute and in this case the lack of datatyping isn’t such a big deal. In larger projects, having this kind of insurance can prevent errors and bugs that bring down your whole movie.


Step 9: Create a Button

That should be enough of an introduction; let’s see a specific use of variables in action. We’ll now start making the button group example shown at the start of this tutorial.

Create a new ActionScript 3 Flash file and create some art to serve as a button. Turn it into a movie clip.


Step 10: Create Four Instances

Drag the symbol on the stage four times so that there are four instances of the button. While it’s not necessary for the function of the movie, you may want to arrange them in a row at the top of the stage. Give each an instance name by clicking on each one individually and typing the name into the instance name field of the Properties panel.

I’ve named my buttons "button1," "button2,""button3," and "button4." For simplicity in following along with the code, be consistent and use my names.


Step 11: Create a Text Field

Underneath the row of buttons, create a dynamic text field, give it an instance name (I used "output") and go ahead and make it as big as will fit on the stage. The purpose of this text field will be to log the names of the buttons as they are clicked. We don’t need too much horizontal space but should have as much vertical space as possible.


Step 12: Hook Up Click Listeners

Create a new layer to hold your code, lock it and then click in the frame for that layer. Open the Actions panel. Write the following code to hook up an action to respond to mouse clicks for each button:

button1.addEventListener(MouseEvent.CLICK, buttonClick);
button2.addEventListener(MouseEvent.CLICK, buttonClick);
button3.addEventListener(MouseEvent.CLICK, buttonClick);
button4.addEventListener(MouseEvent.CLICK, buttonClick);
function buttonClick(event:MouseEvent):void {
	trace("click");
}

For now, the actual action taken in response to a click is trivial, but it’s enough for us to test. If you’ve done everything correctly so far, you should be able to test the movie and click on each of the four buttons. Every time you click, you will see the word "click" show up in the Output panel.


Step 13: Understanding Event.target

You may be wondering how we’ll accomplish our goal with just a single function. How will that one function react appropriately for each of the four different buttons?

Without getting into too much detail into the event paradigm of ActionScript 3, every function that acts as an event listener will receive an event object as a parameter. There are several kinds of event objects, from regular Event objects to MouseEvents to KeyboardEvents to ProgressEvents and more, but every event object will have a few common characteristics. One of the most useful of these is the "target" property. Every event object defines a target property that points to the thing that actually caused the event.

We can tell which button was clicked by accessing the target of the MouseEvent in the function. To see this in action, change the function contents to:

trace(event.target.name);

The whole script looks like this:

Rerun the movie and click on the buttons again. You should see the appropriate name show up in the Output panel.

This works because the event object itself is held in the variable called "event." That object has a property (a property is basically a variable, except that it belongs to an object) called "target", and using dot syntax we can access the target variable from the event variable. The target is the movie clip that was actually clicked and caused the event. By accessing the name property of that movie clip, we can get an indication of which button was clicked to print to the Output panel.


Step 14: Output the Button Name

Let’s now actually do something when a button is clicked. We’ll put the button’s name into the text field. Add the following to the buttonClick function (replacing, if you like, the trace statement)

output.appendText(event.target.name + "\n");
output.scrollV = output.maxScrollV;

The first line puts the name of the clicked button into the text field. The appendText() method will take the current text and add to it. We’ll put a newline character (the "\n") at the end of the added text to make sure the next bit of text added will be on a new line.

The second line makes sure that the last line of text is always visible. In a nutshell, this line sets the scroll amount (which line of text is at the top of the visible area) to the maximum amount based on how many lines there are.


Step 15: Create a Selected State

Remember that our goal is to make the clicked button the selected button, so we want to visually represent that. To easily make a visual change to the button, we’ll just set the alpha to something slightly transparent.

Replace the trace statement with the following:

event.target.alpha = 0.7;

The alpha property of a movie clip adjusts the transparency and ranges from 0 to 1, with 1 being fully opaque. Therefore, 0.7 is something that’s 70% opaque, or 30% transparent.

Run the movie and click on a button. You should see it change. Of course, we still have quite a bit to implement, so once a button obtains the selected look, it stays that way.


Step 16: Disable Event.target

You’ll notice that if you click on a button, you can continue to click on it, as evidenced by the name showing up each time you click. We want something like a group of tab buttons, where a button that is currently selected can’t be clicked. We can easily accomplish this by setting the mouseEnabled property of the recently-clicked button (still event.target) to false.

event.target.mouseEnabled = false;

The whole script at this point should look like the following:


Step 17: Variable to Hold the Current Button

So far we’re off to a good start, but while the button is reacting appropriately when we click it the first time, we have issues after that. The button is kind of stuck in the selected state and is never restored to its normal state when another button is clicked.

Now we can introduce the variable that will solve all of our problems. We need a variable that will contain the movie clip that is the currently selected button. By storing it in a variable, the information about which button is currently selected can persist from click to click.

We’ll call it "currentButton" and we’ll give it a datatype of MovieClip. At the top of the script, write this line:

var currentButton:MovieClip;

Step 18: Set the Variable to Event.target

Now, every time we click on a button, we want to track that button in the currentButton variable, so that at any given time we know which button is the current one. This is done with the following modification to the buttonClick function:

currentButton = event.target as MovieClip;

Notice the "as MovieClip" in the preceding code. We’ll gloss over all of the gory details here, but this is a necessity due to strong typing. Our currentButton variable is declared as being a MovieClip. However, the target property of the Event object is declared as being an Object, which is a very generic datatype. The target is defined as an Object so that it can be generic; lots of things can create events and so the target won’t necessarily always be a MovieClip. The problem is that the two datatypes don’t really match; we’re promising that only MovieClips will go into the currentButton variable, but we’re trying to put an Object in.

The best thing we can do is assume that the event’s target is, in fact, a MovieClip and so we perform a cast on it. The "as" operator takes the value on the left and treats it as though it were of the datatype specified on the right. The assumption is reasonable, since the code is inside of a function that should only ever get called when the user clicks on a MovieClip and that MovieClip creates the MouseEvent.

Note that casting is not without its problems. The biggest problem comes in the form of a cast that can’t be honored. For example, if we were to try to cast our event.target as an XML object, well, then that wouldn’t work at all, would it? MovieClips and XML objects have very little in common. When the cast is attempted, we would get an empty value back, which leaves us with a broken program. If we’re lucky we’ll get a runtime error saying that the cast can’t be completed; if we’re unlucky we’ll get the empty value and are left wondering why things didn’t work as planned.

Casting should be avoided if its not necessary, but in some cases (like this one) it’s pretty much the only option. If we didn’t cast the target, we’d get a compiler error. Go ahead and try it if you’d like to see what happens.


Step 19: Use currentButton

While not strictly necessary, we may as well use our new currentButton variable instead of event.target in the body of the function. It’s not necessary because while we’re in the function, we have access to event.target and our code will work just fine without making the following change. However, there are two compelling reasons to get in the habit of using typed (and casted, if need be) variables where possible.

The first reason is the main reason. As mentioned in the last step about casting, event.target is not typed as a MovieClip. Yet we know that it is, so we cast it as such. Think back to step 9, where we deliberately typed a variable as one thing and tried to use it as another, which caused errors. Now, if we go and tell the variable currentButton to set its alpha to 0.7, currentButton is a MovieClip and MovieClip has an alpha property and all is good. If we accidentally tried to set the aplah property (it happens more often than you would think), Flash would complain about it and let us know and we’d be able to correct our mistake quickly. Using event.target (which is a very generic, loosely-typed variable), it may take longer to find that typo.

The second reason has to do with performance. In this particular case, we’re not going to see huge gains from using a typed variable instead of event.target. In ActionScript 3, it is faster to use a value out of a single typed variable that it is out of an untyped property (as event.target is). In critical applications this might give you an extra few processor cycles.

So, in this step we are simply changing out occurences of event.target with currentButton, after it has been set.

Your code should look something like the following:


Step 20: Deselect the Old Current Button

Now that we have a variable declared and holding a value, we can use it to restore the visual appearance of the previously selected button. That is, if you click on button1 and it changes appearance, then you click on button2, we want button1 to look normal again.

The next bit of code needs to happen before we set the currentButton variable. Otherwise, we’ll be affecting the current button, not the previous button.

currentButton.alpha = 1;

This will restore the previous button’s appearance, but we won’t be able to click on it. We previously disabled it by setting its mouseEnabled property to false, so we can enable it by setting it back to true. Place this code immediately after the last bit of code we wrote:

currentButton.mouseEnabled = true;

The code should look like this:


Step 21: Check for null Value

If you tried running the movie after the last step, you’ll have run into a runtime error involving a "null object." This is ActionScript’s way of saying that a variable didn’t have a value before you tried doing something with it.

What happened was that when the movie starts, the currentButton variable is declared, but it doesn’t have a value yet. It only gets a value when you click on a button. Well, when you click on a button, the buttonClick function runs and the first thing it does is try to set the alpha of whatever is in currentButton. Unfortunately, nothing is in currentButton and so the "null object" error gets thrown. At that point, script execution stops and so we end up never getting to a place where we can actually set currentButton.

This is easily avoided, though. We simply need to check that currentButton doesn’t equal null before continuing. Replace the first two lines with:

if (currentButton) {
	currentButton.alpha = 1;
	currentButton.mouseEnabled = true;
}

Without getting into too much detail, this sets up a condition that only runs the statement after the parentheses if the statement inside the parentheses has a value. In other words, if currentButton has not been set, then skip the part about setting its alpha and pick up with the next line of code.

Here is the full code, in text form for reference:

var currentButton:MovieClip;

button1.addEventListener(MouseEvent.CLICK, buttonClick);
button2.addEventListener(MouseEvent.CLICK, buttonClick);
button3.addEventListener(MouseEvent.CLICK, buttonClick);
button4.addEventListener(MouseEvent.CLICK, buttonClick);
function buttonClick(event:MouseEvent):void {
	if (currentButton) {
		currentButton.alpha = 1;
		currentButton.mouseEnabled = true;
	}
	currentButton = event.target as MovieClip;
	trace(currentButton.name);
	output.appendText(currentButton.name + "\n");
	output.scrollV = output.maxScrollV;
	currentButton.alpha = 0.7;
	currentButton.mouseEnabled = false;
}

At this point, you have created a variable. It has a name and a datatype. It stores several different values over time, so that at certain points in time you can track the current value and do something with it. You learned about casting and why variables are the building block of all programs of any complexity.

I hope you enjoyed this beginner’s article, feel free to leave questions and opinions in the comments section. We have plenty more tutorials planned for the AS3 101 series, so stay tuned!



View full post on Activetuts+

Page 1 of 41234»
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
June 2013
M T W T F S S
« Jul    
 12
3456789
10111213141516
17181920212223
24252627282930
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