Advertisement
  1. Code
  2. Effects
Code

Create a Responsive Image Scroller in ActionScript 3.0

by
Difficulty:IntermediateLanguages:

This tutorial will demonstrate how to create a horizontally scrolling image viewer. It will cover xml parsing, loading and resizing external images, and creating intuitive and responsive scrolling!

Quick Introduction

I'm a firm believer in learning by coding and tinkering. So in this tutorial, I'm stating what to do and then showing the equivalent code; please dig into the code, change things and tinker - I think that's one of the best ways to learn! I expect that you have a basic understanding of ActionScript already and I won't explain the fundamentals. I hope the descriptions will be helpful, but if I don't explain something that you aren't quite following, feel free to ask about it in the comments.

Step 1: Set Up XML

We'll want nodes of images included in our xml. Each node will represent an image with attributes. We can add anything we like here, I'll stick to three attributes to each image node. The 'src' of the image (used to load it in), the title and the url we will link to from the scroller. I'll go ahead and wrap them all within an images node (in case I want to include anything else in the xml later, such as customization options - hint).

Each image node will need a source image, a title and a url. The source (src) will be the image that gets loaded into the scroller, the title will be what we call it and the url will be the url that we load from the scroller when users click on the image (it can be a larger image or even a website). I've gotten some images from the envato asset library and resized them to be used as the thumbnails as well. I shrank the thumbnails to fit into a 140px by 105px area, this is not required but will help to optimize the experience since we won't be loading in huge images. You'll see soon that any size image will work because we'll code it to resize any image that loads to fit into the scroller area!

Step 2: Set Up Flash

OK, now that we have our xml file finished, let's get started in Flash. Open Flash and create a new file (ActionScript 3.0). Adjust the stage size to something around 600 wide and 150 tall, set the background to any color you like (I chose a dark color to help the images stand out a bit more - #000033 if you wanna follow along) and step up the frame rate to 30 frames per second to give us smoother animation. Then let's go ahead and create a new layer calling it "ActionScript". On the first frame in the timeline click to the actions panel and we're ready to continue!

Step 3: Load XML

We need to load the information from the xml file (created in step 1) into our Flash file. It's a pretty simple step, but a foundation which can spring to many other creative applications. In just a few lines of code we initialize a URLLoader, an XML object to hold our data and a string to specify the path to the xml. Then we load the xml through the urlLoader object. That done, we need an Event listener to fire off when the file is fully loaded, we wouldn't want to start messing with the xml data before it finishes loading. As specified in the docs, the complete event passes the loaded content as a the event target data property, so we access the actual xml as e.target.data and assign it to our xml object.

Let's go ahead and double check that we've set that all up correctly and trace the image nodes of our xml to the output panel.

Step 4: Parse XML

Loading the xml is great, but we also have to read it and let our code know what to do with the data. So rather than just tracing out the xmlList we'll send it to another function that will take care of creating our scroller. The buildScroller function will accept an XMLList, so we'll loop through it, creating movie clip objects for each image in the scroller and assigning them properties according to the xml node attributes title, url and src. Later we'll build out this function to include much more so it will actually do what it is named for and build the scroller!

For now let's just trace this info to make sure everything is working according to plan. We can even wrap the content buildScroller function with trace statements so we always know where we are.

Step 5: Build Scroller MovieClip to Contain Each Image

Now that the build scroller function is created and that it creates objects for each node in the xml, let's add them to the stage!

We'll begin by creating a scroller MovieClip. This will be the container for all the objects we want to scroll, so each image node will have a movieclip within this scroller object. Let's go ahead and add it to the stage, then set the y value to 30. We won't yet see anything on the stage when we test, but we're about to add items to the scroller for each image in the xmlList.

Step 6: Adding Items to Scroller

We already have the movie clips created with properties, but we need to create something we can see, so let's create a box area to actually see these scroller items. Create a blackBox sprite and give it a shape with the graphics api. I've decided that I want my standard scroller item to be 140x105px so I'll create the blackBox to fit that area and I'll give it a 1px border on all sides. Move it up and to the left one pixel and give it 142x107 dimensions.

We add the blackbox sprite to the thisOne movieClip and also update the x value of the item. Since each will be 140 wide, I'll add some padding (20) and lay them out horizontally. I'll update the trace statement to output what is going on here.

Step 7: Adding Click Listener to Items

Alright, this isn't much yet because it just looks like a bunch of boxes that don't do anything. Let's add a listener to these boxes though, so that we can tell that they are each unique items in the scroller. Thinking of the final result, we'll add a click listener because we want users to be able to click the item in the scroller and go to the link we put in the xml. Let's make the clip buttonMode true, so that it's perceived as something that is click-able. Then add an event Listener for the MouseEvent.CLICK. For now we'll just have it listen for this click event and fire a function to trace the url we're aiming at.

Through the output we can see that each box has properties sent to it from the xml.

Step 8: Adding More Listeners to Scroller Items

Let's finish off the event listeners! We'll want to listen to each of these items to know when a user clicks, mouses over and mouses out.

Step 9: Loading and Adding the Images

Now the part I'm sure you've been getting anxious about, let's get the images loaded into the scroller items so we can see what they are! We'll do this in the buildScroller function. Right after the blackbox is created and the properties are assigned for the current item let's also create another sprite to contain the actual image.

We'll use a loader object and a URLRequest object to handle the loading of the image, which is newly standardized with ActionScript 3. We'll pass the src of the image to the urlrequest object, then load the urlrequest with our loader object and finally we'll add the loader to the thisThumb sprite adding that in turn to the thisOne movieClip. Whew.

It's pretty self explanatory - and in just a couple of lines of code we've loaded the src images from our xml into Flash!

Step 10: Adding Event Listeners to the Image Loading Process

When we load the images, we need to create some event listeners to tell us when the loading is complete. Best practice deal with any errors (in case there is a typo in the path to the image or we don't have access or something). So just before we load the images let's add an event listener for the loader's contentLoaderInfo object for a complete event and also an i/o error. Then we'll need to create the event handler functions.

For the completeHandler let's just trace the image title for now, we'll have to walk up the hierarchy of the event target's parent's parent's title to find it, because of the way we nested our sprite within our scroller item objects (the thisOne Sprite).

Step 11: Tweening the Images

I'm using Tweener for this tutorial, but there are various tweening engines. If you're not familiar with it

Tweener (caurina.transitions.Tweener) is a Class used to create tweens and other transitions via ActionScript code for projects built on the Flash platform... In layman's terms, Tweener helps you move things around on the screen using only code, instead of the timeline.

So first go download it from the google code repository (be sure to get the as3 version) unzip it and put the caurina folder into the same directory as your .fla file, then import the code into your project by placing this in the first line of code:

Then let's have the images fade in once they're loaded, instead of just popping like they are. First we'll set the initial alpha value of the scroller item to 0, so it can fade in properly. Then jump back to our complete event listener handler function and add the Tweener code.

Step 12: Resizing the Images

Now, since I resized all my images and created thumbnails beforehand, this step is not as important, but is still great to include so that in case the dimensions change or I add another image later, the scroller will be able to handle it and resize it. The resize function will scale an image to fit within an area as I have explained before on my blog. Basically though, in the completeHandler we'll resize the image to fit an area, even if the image is correctly sized, the resizeMe function will still center the image for us.

Step 13: Adding Movement

We'll start by just adding the basics. We want users to be able to intuitively control this scroller, so we'll use their mouse position as direction only initially. If the mouse is positioned in the left half of the stage we want to move the scroller to the right, so the user moves in the direction they want the scroller to reveal itself. I prefer this to the direct relationship of moving the scroller the same way the mouse goes, but that's a discussion for another day.

To implement this is pretty simple, we just add an event listener at the end of the buildScroller function, for every time we enter the frame to position the scroller. Then in the handler function we'll create an if/else statement and set the new speed variable depending on mouse position. If the mouse x position is on the left half of the stage, we want the scroller to move one way and if it is on the right half of the stage we want it to move the other direction. Then we apply this speed to the x position of the scroller container. This is now starting to look like something useful because it is now interactive and responsive!

Essentially all we are doing is moving the scroller container clip to one direction of the other, but we're doing it every frame, so it animates the position over time. Remember this scroller clip contains all the items we created, so it's like putting things into a box and moving the box. The items don't have to be moved, just the container! We move it either 5 pixels to the left or 5 pixels to the left every single frame (this 5 could be anything, I just chose 5 'cause it looked right). This leaves a lot to be desired, but it's the first step. We have our scroller moving and have given the end user the power to control this movement!

Notice that we're using the stage properties to find the stage size even though we set the stage size earlier and know exactly what size it is. This is because it will help the code to be self containing and portable. If we were to use the actual values we would have to remember to update them if we ever changed the scroller size or wanted to use this in a different application. We'll create more variables soon that will allow us to fully customize the scroll interaction.

Step 14: Better Movement - Mouse Limits

You can see above that we still have a way to go with our movement controls of the scroller. There are boundaries to add to the mouse positions that cause the scrolling (we'd like it to only scroll when you are on the stage and over the scroller), limits we'd like to apply to the scroller (so that it doesn't scroll off the page) and we want to make the scroller speed dynamic.

Let's start first by adding a statement to check if we are over the scroller. To do this we'll check the mouseY position, the scroller.y and scroller.height properties. Let's also add a bit more to the mouseX statements, let's ensure that it's a bit more precise and only include the x values from 0 to the center of the stage (stage.stageWidth/2) and from the center to the edge.

Step 15: Better Movement - Scroller Limits

Now we'll want to apply boundaries to the scroller itself so that it doesn't scroll off the page and leave us with a blank stage and a user who doesn't know or remember which way the images went.

We need to watch the scroller x position and if it goes too far either way reset it to our limit. Remember that the scroller x position is found at its left edge, so when it is at a 0 x position it is flush with the left edge of the stage. So first off if the x position of the scroller is greater than 0 after the speed is calculated and applied, we want to set it back to our limit, 0. This will keep the scroller from moving too far into the stage. We can even add some padding to the stage and since we have the padding between each scroller item of 20, let's make it consistent. Rather than using 0 here, let's make it the same 20 value.

We want the scroller to stop moving left once it's last item is fully on stage. This left limit can be found by finding the width of the scroller and the stage width. If the scroller is moved so far to the left that it's x position is less than it's own width (negative) but factor back in the stage width (plus stageWidth) we need to hold it right there. To add the padding on this end we subtract 20.

Step 16: Dynamic Movement

To make the movement more fluid and dynamic we only need to update two lines of code. You guessed it, the two lines that set the speed need to be adjusted to determine the speed by the distance mouseX is from the center of the stage rather than a flat value of 5. We find the distance the mouse is horizontally from the center axis of the stage (stage.stageWidth/2), and we want the scroller to move to the right if we're on the left side and vice versa. In both instances we find the negative difference between the two. Then we should scale it down by dividing it by, let's try 8, because if we don't, the scroller is way too fast (go ahead, try it).

Step 17: User Friendly Movement

Now test this and think about your end user. You'll be looking at this image scroller and maybe wanting to look a bit closer or focus in on an image that catches your eye. You want this scroller to stop moving, (if I move to the center of the stage it still drifts to one side of the other) and I focus more on fighting the scroller than I do on the image I want to look at.

This is an example of a non-transparent user control. We want the user to be able to intuitively use this scroller to the point that they don't even think about it. If the user has to think about it, or even worse, fight your app to get it to do something, you lose and they will look elsewhere for their content. So let's avoid the struggle and give the scroller a dead area at the center of the stage. Then they can rest at ease by moving to the center of the scroller to inspect something or stop the motion sickness. It's a really easy thing to do and has a big payoff, making the scroller easier to use. Rather than using the center of the stage for all our calculations we'll give it some padding.

Step 18: Abstracting Movement More

Let's abstract this out a bit. We have multiple places where we are adding padding to values or measurements. It'd be best practice to create a variable to hold our padding value and apply the same value easily by applying the variable every time we want padding. This would help us update if a client later says "I like it, but can we spread it out some?" or the dreaded... "Something's off about this...", then we'd just update the variable and it would be ready to go. I always try to create controls for myself, the programmer, to make it easy to customize a project.

I've created a variable named "padding" here and am applying it everywhere that makes sense. Notice that in a couple places I multiply it by 2, use your own judgment here - if you want more padding give it more, of course we could take it further and have a "padding_small" variable and another "padding_large" variable, but one will do justice for the purpose of this tutorial. You get the idea. This doesn't really change the end file, but it can help to make your life much easier and your code simpler, more understandable or readable.

Step 19: Adding Scale Tweens

With this idea of using variables to customize our file, let's add some bling with the Tweener library we already added. It's great to call out the item in the scroller the user rolls over, so let's have it scale a bit larger to help it stand out. This is where the beauty of Tweening comes in. Just one line of code, some variables and we can tell it to tween the scaleX and scaleY of the scroll item. If we're scaling the item we'll want to also translate its coordinates a bit so the item is still centered, this looks like tricky math, but it's actually pretty simple.

First, we add a variable to each object to store it's starting x position, we can just call it myx and put it on the same line where we calculate the x (we do this so we can reliably move the item back to it's rightful place when we need to). We need to move it so the item is still centered, so we find its current width and factor it by half the scale we are applying. We do this for x and y. Then we need to tween it back to its starting size and coordinates on the mouse out event handler.

Step 20: Adding Border Tweens

Let's make them stand out even more by fading the white 'blackBox' around the thumbnails (just realizing that I named the white box black =) ). This one is easier than the previous step. Just add a couple of variables for the fade in and out values (alpha) and add the Tweens to both the over and out event listener handler function. We'll also need to ensure that we can address the blackBox sprite so when we initialize it let's explicitly name it. While we're at it we can set the initial alpha of the box to equal the thumbFadeOut variable.

Step 21: Adding Link on Click

Speaking of all the event listeners, we still haven't finished coding the click event. We want to have the click basically be a link click and link the user to the url specified in the xml. For this, we just pass the link value from the event's target that we are currently tracing, to a URLRequest object and try to navigate to it with our friend navigateToURL. There we have it.

Conclusion

I hope you enjoyed this tutorial and that you learned something. You should now have a pretty good grasp on AS3 and xml, loading and resizing images, easy animating with tweening, mouse event listeners, scrolling and user friendly interactive design!

Was it easy to follow? I usually do tutorials in open source examples so I don't know if I droned on too much here.. Feel free to let me know in the comments. This tutorial is meant to be a spring board for ideas; there are tons of other things we could to with this file and get many other effects going, but this should get you started!

Advertisement
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.