Jun 30, 2012
Posted on Jun 30, 2012 in Hints and Tips | 10 comments
If you’ve been doing JavaScript development long enough, you’ve most likely crashed your browser a few times. The problem usually turns out to be some JavaScript bug, like an endless while loop; if not, the next suspect is page transformations or animations – the kind that involve adding and removing elements from the webpage or animating CSS style properties. This tutorial focuses on optimising animations produced using JS and the HTML5 <canvas> element.
This tutorial starts and ends with what the HTML5 animation widget you see below:
We will take it with us on a journey, exploring the different emerging canvas optimization tips and techniques and applying them to the widget’s JavaScript source code. The goal is to improve on the widget’s execution speed and end up with a smoother, more fluid animation widget, powered by leaner, more efficient JavaScript.
The source download contains the HTML and JavaScript from each step in the tutorial, so you can follow along from any point.
Let’s take the first step.
Step 1: Play the Movie Trailer
The widget above is based on the movie trailer for Sintel, a 3D animated movie by the Blender Foundation. It’s built using two of HTML5′s most popular additions: the <canvas> and <video> elements.
The <video> loads and plays the Sintel video file, while the <canvas> generates its own animation sequence by taking snapshots of the playing video and blending it with text and other graphics. When you click to play the video, the canvas springs to life with a dark background that’s a larger black and white copy of the playing video. Smaller, colored screen-shots of the video are copied to the scene, and glide across it as part of a film roll illustration.
In the top left corner, we have the title and a few lines of descriptive text that fade in and out as the animation plays. The script’s performance speed and related metrics are included as part of the animation, in the small black box at the bottom left corner with a graph and vivid text. We’ll be looking at this particular item in more detail later.
Finally, there’s a large rotating blade that flies across the scene at the beginning of the animation, whose graphic is loaded from an external PNG image file.
Step 2: View the Source
The source code contains the usual mix of HTML, CSS and Javascript. The HTML is sparse: just the <canvas> and <video> tags, enclosed in a container <div>:
<div id="animationWidget" >
<canvas width="368" height="208" id="mainCanvas" ></canvas>
<video width="184" height="104" id="video" autobuffer="autobuffer" controls="controls" poster="poster.jpg" >
<source src="sintel.mp4" type="video/mp4" ></source>
<source src="sintel.webm" type="video/webm" ></source>
</video>
</div>
The container <div> is given an ID (animationWidget), which acts as a hook for all the CSS rules applied to it and its contents (below).
#animationWidget{
border:1px #222 solid;
position:relative;
width: 570px;
height: 220px;
}
#animationWidget canvas{
border:1px #222 solid;
position:absolute;
top:5px;
left:5px;
}
#animationWidget video{
position:absolute;
top:110px;
left:380px;
}
While HTML and CSS are the marinated spices and seasoning, its the JavaScript that’s the meat of the widget.
- At the top, we have the main objects that will be used often through the script, including references to the canvas element and its 2D context.
- The
init() function is called whenever the video starts playing, and sets up all the objects used in the script.
- The
sampleVideo() function captures the current frame of the playing video, while setBlade() loads an external image required by the animation.
- The pace and contents of the canvas animation are controlled by the
main() function, which is like the script’s heartbeat. Run at regular intervals once the video starts playing, it paints each frame of the animation by first clearing the canvas, then calling each one of the script’s five drawing functions:
drawBackground()
drawFilm()
drawTitle()
drawDescription()
drawStats()
As the the names suggest, each drawing function is responsible for drawing an item in the animation scene. Structuring the code this way improves flexibility and makes future maintenance easier.
The full script is shown below. Take a moment to assess it, and see if you can spot any changes you would make to speed it up.
(function(){
if( !document.createElement("canvas").getContext ){ return; } //the canvas tag isn't supported
var mainCanvas = document.getElementById("mainCanvas"); // points to the HTML canvas element above
var mainContext = mainCanvas.getContext('2d'); //the drawing context of the canvas element
var video = document.getElementById("video"); // points to the HTML video element
var frameDuration = 33; // the animation's speed in milliseconds
video.addEventListener( 'play', init ); // The init() function is called whenever the user presses play & the video starts/continues playing
video.addEventListener( 'ended', function(){ drawStats(true); } ); //drawStats() is called one last time when the video end, to sum up all the statistics
var videoSamples; // this is an array of images, used to store all the snapshots of the playing video taken over time. These images are used to create the 'film reel'
var backgrounds; // this is an array of images, used to store all the snapshots of the playing video taken over time. These images are used as the canvas background
var blade; //An canvas element to store the image copied from blade.png
var bladeSrc = 'blade.png'; //path to the blade's image source file
var lastPaintCount = 0; // stores the last value of mozPaintCount sampled
var paintCountLog = []; // an array containing all measured values of mozPaintCount over time
var speedLog = []; // an array containing all the execution speeds of main(), measured in milliseconds
var fpsLog = []; // an array containing the calculated frames per secong (fps) of the script, measured by counting the calls made to main() per second
var frameCount = 0; // counts the number of times main() is executed per second.
var frameStartTime = 0; // the last time main() was called
// Called when the video starts playing. Sets up all the javascript objects required to generate the canvas animation and measure perfomance
function init(){
if( video.currentTime > 1 ){ return; }
bladeSrc = new Image();
bladeSrc.src = "blade.png";
bladeSrc.onload = setBlade;
backgrounds = [];
videoSamples = [];
fpsLog = [];
paintCountLog = [];
if( window.mozPaintCount ){ lastPaintCount = window.mozPaintCount; }
speedLog = [];
frameCount = 0;
frameStartTime = 0;
main();
setTimeout( getStats, 1000 );
}
// As the scripts main function, it controls the pace of the animation
function main(){
setTimeout( main, frameDuration );
if( video.paused || video.ended ){ return; }
var now = new Date().getTime();
if( frameStartTime ){
speedLog.push( now - frameStartTime );
}
frameStartTime = now;
if( video.readyState < 2 ){ return; }
frameCount++;
mainCanvas.width = mainCanvas.width; //clear the canvas
drawBackground();
drawFilm();
drawDescription();
drawStats();
drawBlade();
drawTitle();
}
// This function is called every second, and it calculates and stores the current frame rate
function getStats(){
if( video.readyState >= 2 ){
if( window.mozPaintCount ){ //this property is specific to firefox, and tracks how many times the browser has rendered the window since the document was loaded
paintCountLog.push( window.mozPaintCount - lastPaintCount );
lastPaintCount = window.mozPaintCount;
}
fpsLog.push(frameCount);
frameCount = 0;
}
setTimeout( getStats, 1000 );
}
// create blade, the ofscreen canavs that will contain the spining animation of the image copied from blade.png
function setBlade(){
blade = document.createElement("canvas");
blade.width = 400;
blade.height = 400;
blade.angle = 0;
blade.x = -blade.height * 0.5;
blade.y = mainCanvas.height/2 - blade.height/2;
}
// Creates and returns a new image that contains a snapshot of the currently playing video.
function sampleVideo(){
var newCanvas = document.createElement("canvas");
newCanvas.width = video.width;
newCanvas.height = video.height;
newCanvas.getContext("2d").drawImage( video, 0, 0, video.width, video.height );
return newCanvas;
}
// renders the dark background for the whole canvas element. The background features a greyscale sample of the video and a gradient overlay
function drawBackground(){
var newCanvas = document.createElement("canvas");
var newContext = newCanvas.getContext("2d");
newCanvas.width = mainCanvas.width;
newCanvas.height = mainCanvas.height;
newContext.drawImage( video, 0, video.height * 0.1, video.width, video.height * 0.5, 0, 0, mainCanvas.width, mainCanvas.height );
var imageData, data;
try{
imageData = newContext.getImageData( 0, 0, mainCanvas.width, mainCanvas.height );
data = imageData.data;
} catch(error){ // CORS error (eg when viewed from a local file). Create a solid fill background instead
newContext.fillStyle = "yellow";
newContext.fillRect( 0, 0, mainCanvas.width, mainCanvas.height );
imageData = mainContext.createImageData( mainCanvas.width, mainCanvas.height );
data = imageData.data;
}
//loop through each pixel, turning its color into a shade of grey
for( var i = 0; i < data.length; i += 4 ){
var red = data[i];
var green = data[i + 1];
var blue = data[i + 2];
var grey = Math.max( red, green, blue );
data[i] = grey;
data[i+1] = grey;
data[i+2] = grey;
}
newContext.putImageData( imageData, 0, 0 );
//add the gradient overlay
var gradient = newContext.createLinearGradient( mainCanvas.width/2, 0, mainCanvas.width/2, mainCanvas.height );
gradient.addColorStop( 0, '#000' );
gradient.addColorStop( 0.2, '#000' );
gradient.addColorStop( 1, "rgba(0,0,0,0.5)" );
newContext.fillStyle = gradient;
newContext.fillRect( 0, 0, mainCanvas.width, mainCanvas.height );
mainContext.save();
mainContext.drawImage( newCanvas, 0, 0, mainCanvas.width, mainCanvas.height );
mainContext.restore();
}
// renders the 'film reel' animation that scrolls across the canvas
function drawFilm(){
var sampleWidth = 116; // the width of a sampled video frame, when painted on the canvas as part of a 'film reel'
var sampleHeight = 80; // the height of a sampled video frame, when painted on the canvas as part of a 'film reel'
var filmSpeed = 20; // determines how fast the 'film reel' scrolls across the generated canvas animation.
var filmTop = 120; //the y co-ordinate of the 'film reel' animation
var filmAngle = -10 * Math.PI / 180; //the slant of the 'film reel'
var filmRight = ( videoSamples.length > 0 )? videoSamples[0].x + videoSamples.length * sampleWidth : mainCanvas.width; //the right edge of the 'film reel' in pixels, relative to the canvas
//here, we check if the first frame of the 'film reel' has scrolled out of view
if( videoSamples.length > 0 ){
var bottomLeftX = videoSamples[0].x + sampleWidth;
var bottomLeftY = filmTop + sampleHeight;
bottomLeftX = Math.floor( Math.cos(filmAngle) * bottomLeftX - Math.sin(filmAngle) * bottomLeftY ); // the final display position after rotation
if( bottomLeftX < 0 ){ //the frame is offscreen, remove it's refference from the film array
videoSamples.shift();
}
}
// add new frames to the reel as required
while( filmRight <= mainCanvas.width ){
var newFrame = {};
newFrame.x = filmRight;
newFrame.canvas = sampleVideo();
videoSamples.push(newFrame);
filmRight += sampleWidth;
}
// create the gradient fill for the reel
var gradient = mainContext.createLinearGradient( 0, 0, mainCanvas.width, mainCanvas.height );
gradient.addColorStop( 0, '#0D0D0D' );
gradient.addColorStop( 0.25, '#300A02' );
gradient.addColorStop( 0.5, '#AF5A00' );
gradient.addColorStop( 0.75, '#300A02' );
gradient.addColorStop( 1, '#0D0D0D' );
mainContext.save();
mainContext.globalAlpha = 0.9;
mainContext.fillStyle = gradient;
mainContext.rotate(filmAngle);
// loops through all items of film array, using the stored co-ordinate values of each to draw part of the 'film reel'
for( var i in videoSamples ){
var sample = videoSamples[i];
var punchX, punchY, punchWidth = 4, punchHeight = 6, punchInterval = 11.5;
//draws the main rectangular box of the sample
mainContext.beginPath();
mainContext.moveTo( sample.x, filmTop );
mainContext.lineTo( sample.x + sampleWidth, filmTop );
mainContext.lineTo( sample.x + sampleWidth, filmTop + sampleHeight );
mainContext.lineTo( sample.x, filmTop + sampleHeight );
mainContext.closePath();
//adds the small holes lining the top and bottom edges of the 'fim reel'
for( var j = 0; j < 10; j++ ){
punchX = sample.x + ( j * punchInterval ) + 5;
punchY = filmTop + 4;
mainContext.moveTo( punchX, punchY + punchHeight );
mainContext.lineTo( punchX + punchWidth, punchY + punchHeight );
mainContext.lineTo( punchX + punchWidth, punchY );
mainContext.lineTo( punchX, punchY );
mainContext.closePath();
punchX = sample.x + ( j * punchInterval ) + 5;
punchY = filmTop + 70;
mainContext.moveTo( punchX, punchY + punchHeight );
mainContext.lineTo( punchX + punchWidth, punchY + punchHeight );
mainContext.lineTo( punchX + punchWidth, punchY );
mainContext.lineTo( punchX, punchY );
mainContext.closePath();
}
mainContext.fill();
}
//loop through all items of videoSamples array, update the x co-ordinate values of each item, and draw its stored image onto the canvas
mainContext.globalCompositeOperation = 'lighter';
for( var i in videoSamples ){
var sample = videoSamples[i];
sample.x -= filmSpeed;
mainContext.drawImage( sample.canvas, sample.x + 5, filmTop + 10, 110, 62 );
}
mainContext.restore();
}
// renders the canvas title
function drawTitle(){
mainContext.save();
mainContext.fillStyle = 'black';
mainContext.fillRect( 0, 0, 368, 25 );
mainContext.fillStyle = 'white';
mainContext.font = "bold 21px Georgia";
mainContext.fillText( "SINTEL", 10, 20 );
mainContext.restore();
}
// renders all the text appearing at the top left corner of the canvas
function drawDescription(){
var text = []; //stores all text items, to be displayed over time. the video is 60 seconds, and each will be visible for 10 seconds.
text[0] = "Sintel is an independently produced short film, initiated by the Blender Foundation.";
text[1] = "For over a year an international team of 3D animators and artists worked in the studio of the Amsterdam Blender Institute on the computer-animated short 'Sintel'.";
text[2] = "It is an epic short film that takes place in a fantasy world, where a girl befriends a baby dragon.";
text[3] = "After the little dragon is taken from her violently, she undertakes a long journey that leads her to a dramatic confrontation.";
text[4] = "The script was inspired by a number of story suggestions by Martin Lodewijk around a Cinderella character (Cinder in Dutch is 'Sintel'). ";
text[5] = "Screenwriter Esther Wouda then worked with director Colin Levy to create a script with multiple layers, with strong characterization and dramatic impact as central goals.";
text = text[Math.floor( video.currentTime / 10 )]; //use the videos current time to determine which text item to display.
mainContext.save();
var alpha = 1 - ( video.currentTime % 10 ) / 10;
mainContext.globalAlpha = ( alpha < 5 )? alpha : 1;
mainContext.fillStyle = '#fff';
mainContext.font = "normal 12px Georgia";
//break the text up into several lines as required, and write each line on the canvas
text = text.split(' ');
var colWidth = mainCanvas.width * .75;
var line = '';
var y = 40;
for(var i in text ){
line += text[i] + ' ';
if( mainContext.measureText(line).width > colWidth ){
mainContext.fillText( line, 10, y );
line = '';
y += 12;
}
}
mainContext.fillText( line, 10, y );
mainContext.restore();
}
//updates the bottom-right potion of the canvas with the latest perfomance statistics
function drawStats( average ){
var x = 245.5, y = 130.5, graphScale = 0.25;
mainContext.save();
mainContext.font = "normal 10px monospace";
mainContext.textAlign = 'left';
mainContext.textBaseLine = 'top';
mainContext.fillStyle = 'black';
mainContext.fillRect( x, y, 120, 75 );
//draw the x and y axis lines of the graph
y += 30;
x += 10;
mainContext.beginPath();
mainContext.strokeStyle = '#888';
mainContext.lineWidth = 1.5;
mainContext.moveTo( x, y );
mainContext.lineTo( x + 100, y );
mainContext.stroke();
mainContext.moveTo( x, y );
mainContext.lineTo( x, y - 25 );
mainContext.stroke();
// draw the last 50 speedLog entries on the graph
mainContext.strokeStyle = '#00ffff';
mainContext.fillStyle = '#00ffff';
mainContext.lineWidth = 0.3;
var imax = speedLog.length;
var i = ( speedLog.length > 50 )? speedLog.length - 50 : 0
mainContext.beginPath();
for( var j = 0; i < imax; i++, j += 2 ){
mainContext.moveTo( x + j, y );
mainContext.lineTo( x + j, y - speedLog[i] * graphScale );
mainContext.stroke();
}
// the red line, marking the desired maximum rendering time
mainContext.beginPath();
mainContext.strokeStyle = '#FF0000';
mainContext.lineWidth = 1;
var target = y - frameDuration * graphScale;
mainContext.moveTo( x, target );
mainContext.lineTo( x + 100, target );
mainContext.stroke();
// current/average speedLog items
y += 12;
if( average ){
var speed = 0;
for( i in speedLog ){ speed += speedLog[i]; }
speed = Math.floor( speed / speedLog.length * 10) / 10;
}else {
speed = speedLog[speedLog.length-1];
}
mainContext.fillText( 'Render Time: ' + speed, x, y );
// canvas fps
mainContext.fillStyle = '#00ff00';
y += 12;
if( average ){
fps = 0;
for( i in fpsLog ){ fps += fpsLog[i]; }
fps = Math.floor( fps / fpsLog.length * 10) / 10;
}else {
fps = fpsLog[fpsLog.length-1];
}
mainContext.fillText( ' Canvas FPS: ' + fps, x, y );
// browser frames per second (fps), using window.mozPaintCount (firefox only)
if( window.mozPaintCount ){
y += 12;
if( average ){
fps = 0;
for( i in paintCountLog ){ fps += paintCountLog[i]; }
fps = Math.floor( fps / paintCountLog.length * 10) / 10;
}else {
fps = paintCountLog[paintCountLog.length-1];
}
mainContext.fillText( 'Browser FPS: ' + fps, x, y );
}
mainContext.restore();
}
//draw the spining blade that appears in the begining of the animation
function drawBlade(){
if( !blade || blade.x > mainCanvas.width ){ return; }
blade.x += 2.5;
blade.angle = ( blade.angle - 45 ) % 360;
//update blade, an ofscreen canvas containing the blade's image
var angle = blade.angle * Math.PI / 180;
var bladeContext = blade.getContext('2d');
blade.width = blade.width; //clear the canvas
bladeContext.save();
bladeContext.translate( 200, 200 );
bladeContext.rotate(angle);
bladeContext.drawImage( bladeSrc, -bladeSrc.width/2, -bladeSrc.height/2 );
bladeContext.restore();
mainContext.save();
mainContext.globalAlpha = 0.95;
mainContext.drawImage( blade, blade.x, blade.y + Math.sin(angle) * 50 );
mainContext.restore();
}
})();
Step 3: Code Optimization: Know the Rules
The first rule of code performance optimization is: Don’t.
The point of this rule is to discourage optimization for optimization’s sake, since the process comes at a price.
A highly optimized script will be easier for the browser to parse and process, but usually with a burden for humans who will find it harder to follow and maintain. Whenever you do decide that some optimization is necessary, set some goals beforehand so that you don’t get carried away by the process and overdo it.
The goal in optimizing this widget will be to have the main() function run in less than 33 milliseconds as it’s supposed to, which will match the frame rate of the playing video files (sintel.mp4 and sintel.webm). These files were encoded at a playback speed of 30fps (thirty frames per second), which translates to about 0.33 seconds or 33 milliseconds per frame ( 1 second ÷ 30 frames ).
Since JavaScript draws a new animation frame to the canvas every time the main() function is called, the goal of our optimization process will be to make this function take 33 milliseconds or less each time it runs. This function repeatedly calls itself using a setTimeout() Javascript timer as shown below.
var frameDuration = 33; // set the animation's target speed in milliseconds
function main(){
if( video.paused || video.ended ){ return false; }
setTimeout( main, frameDuration );
The second rule: Don’t yet.
This rule stresses the point that optimization should always be done at the end of the development process when you’ve already fleshed out some complete, working code. The optimization police will let us go on this one, since the widget’s script is a perfect example of complete, working program that’s ready for the process.
The third rule: Don’t yet, and profile first.
This rule is about understanding your program in terms of runtime performance. Profiling helps you know rather than guess which functions or areas of the script take up the most time or are used most often, so that you can focus on those in the optimization process. It is critical enough to make leading browsers ship with inbuilt JavaScript profilers, or have extensions that provide this service.
I ran the widget under the profiler in Firebug, and below is a screenshot of the results.
Step 4: Set Some Performance Metrics
As you ran the widget, I’m sure you found all the Sintel stuff okay, and were absolutely blown away by the item on the lower right corner of the canvas, the one with a beautiful graph and shiny text.
It’s not just a pretty face; that box also delivers some real-time performance statistics on the running program. Its actually a simple, bare-bones Javascript profiler. That’s right! Yo, I heard you like profiling, so I put a profiler in your movie, so that you can profile it while you watch.
The graph tracks the Render Time, calculated by measuring how long each run of main() takes in milliseconds. Since this is the function that draws each frame of the animation, it’s effectively the animation’s frame rate. Each vertical blue line on the graph illustrates the time taken by one frame. The red horizontal line is the target speed, which we set at 33ms to match the video file frame rates. Just below the graph, the speed of the last call to main() is given in milliseconds.
The profiler is also a handy browser rendering speed test. At the moment, the average render time in Firefox is 55ms, 90ms in IE 9, 41ms in Chrome, 148ms in Opera and 63ms in Safari. All the browsers were running on Windows XP, except for IE 9 which was profiled on Windows Vista.
The next metric below that is Canvas FPS (canvas frames per second), obtained by counting how many times main() is called per second. The profiler displays the latest Canvas FPS rate when the video is still playing, and when it ends it shows the average speed of all calls to main().
The last metric is Browser FPS, which measures how many the browser repaints the current window every second. This one is only available if you view the widget in Firefox, as it depends on a feature currently only available in that browser called window.mozPaintCount., a JavaScript property that keeps track of how many times the browser window has been repainted since the webpage first loaded.
The repaints usually occur when an event or action that changes the look of a page occurs, like when you scroll down the page or mouse-over a link. It’s effectively the browser’s real frame rate, which is determined by how busy the current webpage is.
To gauge what effect the un-optimized canvas animation had on mozPaintCount, I removed the canvas tag and all the JavaScript, so as to track the browser frame rate when playing just the video. My tests were done in Firebug’s console, using the function below:
var lastPaintCount = window.mozPaintCount;
setInterval( function(){
console.log( window.mozPaintCount - lastPaintCount );
lastPaintCount = window.mozPaintCount;
}, 1000);
The results: The browser frame rate was between 30 and 32 FPS when the video was playing, and dropped to 0-1 FPS when the video ended. This means that Firefox was adjusting its window repaint frequency to match that of the playing video, encoded at 30fps. When the test was run with the un-optimized canvas animation and video playing together, it slowed down to 16fps, as the browser was now struggling to run all the JavaScript and still repaint its window on time, making both the video playback and canvas animations sluggish.
We’ll now start tweaking our program, and as we do so, we’ll keep track of the Render Time, Canvas FPS and Browser FPS to measure the effects of our changes.
Step 5: Use requestAnimationFrame()
The last two JavaScript snippets above make use of the setTimeout() and setInterval() timer functions. To use these functions, you specify a time interval in milliseconds and the callback function you want executed after the time elapses. The difference between the two is that setTimeout() will call your function just once, while setInterval() calls it repeatedly.
While these functions have always been indispensable tools in the JavaScript animator’s kit, they do have a few flaws:
First, the time interval set is not always reliable. If the program is still in the middle of executing something else when the interval elapses, the callback function will be executed later than originally set, once the browser is no longer busy. In the main() function, we set the interval to 33 milliseconds – but as the profiler reveals, the function is actually called every 148 milliseconds in Opera.
Second, there’s an issue with browser repaints. If we had a callback function that generated 20 animation frames per second while the browser repainted its window only 12 times a second, 8 calls to that function will be wasted as the user will never get to see the results.
Finally, the browser has no way of knowing that the function being called is animating elements in the document. This means that if those elements scroll out of view, or the user clicks on another tab, the callback will still get executed repeatedly, wasting CPU cycles.
Using requestAnimationFrame() solves most of these problems, and it can be used instead of the timer functions in HTML5 animations. Instead of specifying a time interval, requestAnimationFrame() synchronizes the function calls with browser window repaints. This results in more fluid, consistent animation as no frames are dropped, and the browser can make further internal optimizations knowing an animation is in progress.
To replace setTimeout() with requestAnimationFrame in our widget, we first add the following line at the top of our script:
requestAnimationFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
setTimeout;
As the specification is still quite new, some browsers or browser versions have their own experimental implementations, this line makes sure that the function name points to the right method if it is available, and falls back to setTimeout() if not. Then in the main() function, we change this line:
setTimeout( main, frameDuration );
…to:
requestAnimationFrame( main, canvas );
The first parameter takes the callback function, which in this case is the main() function. The second parameter is optional, and specifies the DOM element that contains the animation. It is supposed to be used by to compute additional optimizations.
Note that the getStats() function also uses a setTimeout(), but we leave that one in place since this particular function has nothing to do with animating the scene. requestAnimationFrame() was created specifically for animations, so if your callback function is not doing animation, you can still use setTimeout() or setInterval().
Step 6: Use the Page Visibility API
In the last step we made requestAnimationFrame power the canvas animation, and now we have a new problem. If we start running the widget, then minimize the browser window or switch to a new tab, the widget’s window repaint rate throttles down to save power. This also slows down the canvas animation since it is now synchronized with the repaint rate – which would be perfect if the video did not keep playing on to the end.
We need a way to detect when the page is not being viewed so that we can pause the playing video; this is where the Page Visibility API comes to the rescue.
The API contains a set of properties, functions and events we can use to detect if a webpage is in view or hidden. We can then add code that adjusts our program’s behavior accordingly. We will make use of this API to pause the widget’s playing video whenever the page is inactive.
We start by adding a new event listener to our script:
document.addEventListener( 'visibilitychange', onVisibilityChange, false);
Next comes the event handler function:
// Adjusts the program behavior, based on whether the webpage is active or hidden
function onVisibilityChange() {
if( document.hidden && !video.paused ){
video.pause();
}else if( video.paused ){
video.play();
}
}
Step 7: For Custom Shapes, Draw the Whole Path At Once
Paths are used to create and draw custom shapes and outlines on the <canvas> element, which will at all times have one active path.
A path holds a list of sub-paths, and each sub-path is made up of canvas co-ordinate points linked together by either a line or a curve. All the path making and drawing functions are properties of the canvas’s context object, and can be classified into two groups.
There are the subpath-making functions, used to define a subpath and include lineTo(), quadraticCurveTo(), bezierCurveTo(), and arc(). Then we have stroke() and fill(), the path/subpath drawing functions. Using stroke() will produce an outline, while fill() generates a shape filled by either a color, gradient or pattern.
When drawing shapes and outline on the canvas, it is more efficient to create the whole path first, then just stroke() or fill() it once, rather than defining and drawing each supbath at a time. Taking the profiler’s graph described in Step 4 as an example, each single vertical blue line is a subpath, while all of them together make up the whole current path.
The stroke() method is currently being called within a loop that defines each subpath:
mainContext.beginPath();
for( var j = 0; i < imax; i++, j += 2 ){
mainContext.moveTo( x + j, y ); // define the subpaths starting point
mainContext.lineTo( x + j, y - speedLog[i] * graphScale ); // set the subpath as a line, and define its endpoint
mainContext.stroke(); // draw the subpath to the canvas
}
This graph can be drawn much more efficiently by first defining all the subpaths, then just drawing the whole current path at once, as shown below.
mainContext.beginPath();
for( var j = 0; i < imax; i++, j += 2 ){
mainContext.moveTo( x + j, y ); // define the subpaths starting point
mainContext.lineTo( x + j, y - speedLog[i] * graphScale ); // set the subpath as a line, and define its endpoint
}
mainContext.stroke(); // draw the whole current path to the mainCanvas.
Step 8: Use an Off-Screen Canvas To Build the Scene
This optimization technique is related to the one in the previous step, in that they are both based on the same principle of minimizing webpage repaints.
Whenever something happens that changes a document’s look or content, the browser has to schedule a repaint operation soon after that to update the interface. Repaints can be an expensive operation in terms of CPU cycles and power, especially for dense pages with a lot of elements and animation going on. If you are building up a complex animation scene by adding up many items one at a time to the <canvas>, every new addition may just trigger a whole repaint.
It is better and much faster to build the scene on an off screen (in memory) <canvas>, and once done, paint the whole scene just once to the onscreen, visible <canvas>.
Just below the code that gets reference to the widget’s <canvas> and its context, we’ll add five new lines that create an off-screen canvas DOM object and match its dimensions with that of the original, visible <canvas>.
var mainCanvas = document.getElementById("mainCanvas"); // points to the on-screen, original HTML canvas element
var mainContext = mainCanvas.getContext('2d'); // the drawing context of the on-screen canvas element
var osCanvas = document.createElement("canvas"); // creates a new off-screen canvas element
var osContext = osCanvas.getContext('2d'); //the drawing context of the off-screen canvas element
osCanvas.width = mainCanvas.width; // match the off-screen canvas dimensions with that of #mainCanvas
osCanvas.height = mainCanvas.height;
We’ll then do as search and replace in all the drawing functions for all references to “mainCanvas” and change that to “osCanvas”. References to “mainContext” will be replaced with “osContext”. Everything will now be drawn to the new off-screen canvas, instead of the original <canvas>.
Finally, we add one more line to main() that paints what’s currently on the off-screen <canvas> into our original <canvas>.
// As the scripts main function, it controls the pace of the animation
function main(){
requestAnimationFrame( main, mainCanvas );
if( video.paused || video.currentTime > 59 ){ return; }
var now = new Date().getTime();
if( frameStartTime ){
speedLog.push( now - frameStartTime );
}
frameStartTime = now;
if( video.readyState < 2 ){ return; }
frameCount++;
osCanvas.width = osCanvas.width; //clear the offscreen canvas
drawBackground();
drawFilm();
drawDescription();
drawStats();
drawBlade();
drawTitle();
mainContext.drawImage( osCanvas, 0, 0 ); // copy the off-screen canvas graphics to the on-screen canvas
}
Step 9: Cache Paths As Bitmap Images Whenever Possible
For many kinds of graphics, using drawImage() will be much faster than constructing the same image on canvas using paths. If you find that a large potion of your script is spent repeatedly drawing the same shapes and outlines over and over again, you may save the browser some work by caching the resulting graphic as a bitmap image, then painting it just once to the canvas whenever required using drawImage().
There are two ways of doing this.
The first is by creating an external image file as a JPG, GIF or PNG image, then loading it dynamically using JavaScript and copying it to your canvas. The one drawback of this method is the extra files your program will have to download from the network, but depending on the type of graphic or what your application does, this could actually be a good solution. The animation widget uses this method to load the spinning blade graphic, which would have been impossible to recreate using just the canvas path drawing functions.
The second method involves just drawing the graphic once to an off-screen canvas rather than loading an external image. We will use this method to cache the title of the animation widget. We first create a variable to reference the new off-screen canvas element to be created. Its default value is set to false, so that we can tell whether or not an image cache has been created, and saved once the script starts running:
var titleCache = false; // points to an off-screen canvas used to cache the animation scene's title
We then edit the drawTitle() function to first check whether the titleCache canvas image has been created. If it hasn’t, it creates an off-screen image and stores a reference to it in titleCache:
// renders the canvas title
function drawTitle(){
if( titleCache == false ){ // create and save the title image
titleCache = document.createElement('canvas');
titleCache.width = osCanvas.width;
titleCache.height = 25;
var context = titleCache.getContext('2d');
context.fillStyle = 'black';
context.fillRect( 0, 0, 368, 25 );
context.fillStyle = 'white';
context.font = "bold 21px Georgia";
context.fillText( "SINTEL", 10, 20 );
}
osContext.drawImage( titleCache, 0, 0 );
}
Step 10: Clear the Canvas With clearRect()
The first step in drawing a new animation frame is to clear the canvas of the current one. This can be done by either resetting the width of the canvas element, or using the clearRect() function.
Resetting the width has a side effect of also clearing the current canvas context back to its default state, which can slow things down. Using clearRect() is always the faster and better way to clear the canvas.
In the main() function, we’ll change this:
osCanvas.width = osCanvas.width; //clear the off-screen canvas
…to this:
osContext.clearRect( 0, 0, osCanvas.width, osCanvas.height ); //clear the offscreen canvas
Step 11: Implement Layers
If you’ve worked with image or video editing software like Gimp or Photoshop before, then you’re already familiar with the concept of layers, where an image is composed by stacking many images on top of one another, and each can be selected and edited separately.
Applied to a canvas animation scene, each layer will be a separate canvas element, placed on top of each other using CSS to create the illusion of a single element. As an optimization technique, it works best when there is a clear distinction between foreground and background elements of a scene, with most of the action taking place in the foreground. The background can then be drawn on a canvas element that does not change much between animation frames, and the foreground on another more dynamic canvas element above it. This way, the whole scene doesn’t have to be redrawn again for each animation frame.
Unfortunately, the animation widget is a good example of a scene where we cannot usefully apply this technique, since both the foreground and background elements are highly animated.
Step 12: Update Only The Changing Areas of an Animation Scene
This is another optimization technique that depends heavily on the animation’s scene composition. It can be used when the scene animation is concentrated around a particular rectangular region on the canvas. We could then clear and redraw just redraw that region.
For example, the Sintel title remains unchanged throughout most of the animation, so we could leave that area intact when clearing the canvas for the next animation frame.
To implement this technique, we replace the line that calls the title drawing function in main() with the following block:
if( titleCache == false ){ // If titleCache is false, the animation's title hasn't been drawn yet
drawTitle(); // we draw the title. This function will now be called just once, when the program starts
osContext.rect( 0, 25, osCanvas.width, osCanvas.height ); // this creates a path covering the area outside by the title
osContext.clip(); // we use the path to create a clipping region, that ignores the title's region
}
Step 13: Minimize Sub-Pixel Rendering
Sub-pixel rendering or anti-aliasing happens when the browser automatically applies graphic effects to remove jagged edges. It results in smoother looking images and animations, and is automatically activated whenever you specify fractional co-ordinates rather than whole number when drawing to the canvas.
Right now there is no standard on exactly how it should be done, so subpixel rendering is a bit inconsistent across browsers in terms of the rendered output. It also slows down rendering speeds as the browser has to do some calculations to generate the effect. As canvas anti-aliasing cannot be directly turned off, the only way to get around it is by always using whole numbers in your drawing co-ordinates.
We will use Math.floor() to ensure whole numbers in our script whenever applicable. For example, the following line in drawFilm():
punchX = sample.x + ( j * punchInterval ) + 5; // the x co-ordinate
…is rewritten as:
punchX = sample.x + ( j * punchInterval ) + 5; // the x co-ordinate
Step 14: Measure the Results
We’ve looked at quite a few canvas animation optimization techniques, and it now time to review the results.
This table shows the before and after average Render Times and Canvas FPS. We can see some significant improvements across all the browsers, though it’s only Chrome that really comes close to achieving our original goal of a maximum 33ms Render Time. This means there is still much work to be done to get that target.
We could proceed by applying more general JavaScript optimization techniques, and if that still fails, maybe consider toning down the animation by removing some bells and whistles. But we won’t be looking at any of those other techniques today, as the focus here was on optimizations for <canvas> animation.
The Canvas API is still quite new and growing every day, so keep experimenting, testing, exploring and sharing. Thanks for reading the tutorial.



View full post on Activetuts+
Jun 30, 2012
Posted on Jun 30, 2012 in Hints and Tips | 10 comments
You’ve undoubtedly seen the “Cover Flow” view in effect. It’s all over the place on Apple’s stuff. And you’ve also probably seen a number of implementations of Cover Flow in Flash. In this tutorial, you’ll get one more. We’ll leverage the built-in 3D capabilities of Flash Player 10 (that’s pre-Stage3D) and build our own XML-driven version of Cover Flow.
Note: This tutorial was originally published in April 2011 – before Stage3D was released – as a freebie for our newsletter subscribers. Since Activetuts+ has now shut down, we’re making it free to all readers.
Final Result Preview
Check out the demo to see what we’re working towards.

Click to view the demo.
Step 1: Create an ActionScript 3 Flash File
The very first thing to do is create a Flash file in which we’ll work. Open up Flash CS4 or CS5 and choose File > New, and select Flash File (ActionScript 3.0), and press OK. Save this file into a folder that will be dedicated to this project.
I will be setting the stage size to 600 x 400. Feel free to use whatever size you want, but I would recommend 600 x 400 as a minimum, considering that the Coverflow effect is best when it has ample room for displaying itself. Also, choose a fairly high frame rate, such as the default 24. This will make for smoother animations.
Save this file as CoverFlow.fla in a folder you can dedicate to this project.
Step 2: Create the Test Document Class
Our goal will be to create a reusable CoverFlow class, but to develop it we need a place for it to live. We’ll use the Flash file we just created to act as a testing ground for the CoverFlow class as we develop it, and so we’ll need a document class to go with the Flash file. This class will function to provide a place to instantiate and test the CoverFlow class. It will, as such, provide an example for how to use the CoverFlow class once it is complete.
In the text editor of your choice, create a new file and save it as CoverFlowTest.as in the same folder as your Flash file.
Stub out a simple class:
package {
import flash.display.*;
import flash.events.*;
import flash.net.*;
import flash.utils.*;
public class CoverFlowTest extends Sprite {
public function CoverFlowTest() {
trace("CoverFlowTest");
}
}
}
This doesn’t do much, but will trace out a message if it’s hooked up correctly, which we’ll do next.
Step 3: Wire the Document Class to the FLA
In the Flash file, click somewhere on the empty stage, and open the Properties panel (Command/Control-F3, or Window > Properties). In the Class field, type in CoverFlowTest to assign the document class.
Test your movie now, and you should see the aforementioned trace.
Step 4: Create the CoverFlow Class
Next we’ll create the file for the CoverFlow class. This will live in a package, so first create the folder structure. Starting in the project folder (at the same level as your FLA), create a folder called com. Inside of that, create another folder called tutsplus. Inside of this, create one more folder called coverflow.
Now create another text file called CoverFlow.as inside of the coverflow folder.
Add the following boilerplate:
package com.tutsplus.coverflow {
import flash.display.*;
import flash.geom.*;
import flash.events.*;
import flash.net.*;
import flash.text.*;
import flash.utils.*;
public class CoverFlow extends Sprite {
public function CoverFlow() {
trace("CoverFlow");
}
}
}
This is very similar to the document class, only we’re anticipating the need for more classes, so there are more import statements. This class will also extend Sprite, so that we can treat CoverFlow as a display object.
Step 5: Create a CoverFlow Instance
Now to make sure we can create and work with CoverFlow in our document class. Back in CoverFlowTest.as, import the CoverFlow class. After the other imports:
import com.tutsplus.coverflow.CoverFlow;
Now we need a property to store the CoverFlow instance. Before the constructor:
private var coverFlow:CoverFlow;
And now to create the instance and add it to the display list. In the constructor, remove the trace and replace it with:
coverFlow = new CoverFlow();
addChild(coverFlow);
Test it now, and you should now see “CoverFlow” trace in the Output panel. If so, all is good. We can now start building CoverFlow.
Here is the whole document class code, for reference:
package {
import flash.display.*;
import flash.events.*;
import flash.net.*;
import flash.utils.*;
import com.tutsplus.coverflow.CoverFlow;
public class CoverFlowTest extends Sprite {
private var coverFlow:CoverFlow;
public function CoverFlowTest() {
coverFlow = new CoverFlow();
addChild(coverFlow);
}
}
}
Step 6: Create a Cover Class
A Cover class will be a single item in the entire “flow.” We’ll start by perfecting the class on a single item, then worry about loading data and building the “flow” after that is taken care of.
Again, in your text editor, create a new class file. Save it as Cover.as in the same com/tutsplus/coverflow folder as the CoverFlow class (as opposed to the CoverFlowTest class…yes, we have some potentially confusing names. I’ll try to help you keep things straight throughout this tutorial).
Add the following boilerplate (see a pattern yet?):
package com.tutsplus.coverflow {
import flash.display.*;
import flash.geom.*;
import flash.events.*;
import flash.net.*;
import flash.utils.*;
public class Cover extends Sprite {
public function Cover() {
trace("Cover");
}
}
}
This is actually identical to the CoverFlow boilerplate, except for the usage of the word “Cover” instead of “CoverFlow.” These will end up being quite different, don’t worry, I’m just making sure we have files in place before going too far down the coding rabbit hole.
Step 7: Create a Cover Instance
So, we’ll have the CoverFlow object create and use a Cover object. In the end, CoverFlow will be responsible for creating and managing several Cover objects, but for now, as we build the Cover class, we’ll just have it create and display a single Cover object.
In CoverFlow, instead of tracing “CoverFlow,” let’s have it do this object creation.
public function CoverFlow() {
var test:Cover = new Cover();
addChild(test);
}
If you test it now, you should see “Cover” being traced (remember, that’s a single Cover object, not the previous test traces we’ve been using).
However, let’s go a step further and try to display something onscreen. In the Cover file, remove the trace and add this:
public function Cover() {
graphics.beginFill(0xff0000);
graphics.drawRect(0, 0, 200, 200);
}
Now, instead of tracing to the Output panel, you should see a red square appear in the upper left corner of your movie. If that happens, we’re pretty much set to continue working. What this means is that not only is the code executing all the way down to the individual Cover object, but we’ve successfully added elements to the stage so that we can create visual objects.
Step 8: Put Covers in a Container
We just added our Cover object directly to the CoverFlow’s display list. For reasons that may not be clear at the moment, we’re going to eventually need them in an extra container; that is, CoverFlow will contain a Sprite, which will contain all Cover instances. As we progress through this tutorial, we’ll add other, non-Cover display objects, and it will be very convenient to make sure all Covers are easily managed.
First, in CoverFlow, declare a Sprite property that will reference our container.
private var _coversContainer:Sprite;
And in the constructor, create that Sprite and add it to the display list. Also, instead of adding the test Cover object to the CoverFlow’s display list, add it to the _coversContainer Sprite:
public function CoverFlow() {
_coversContainer = new Sprite();
addChild(_coversContainer);
var test:Cover = new Cover();
_coversContainer.addChild(test);
}
If you test now, you should see exactly the same thing as before, which is good. We don’t want it to look any different, but we want a different functionality under the hood.
Step 9: Set the CoverFlow Size
There are a few things that we should take care of now. The size of the container that holds the CoverFlow display is one of them, as the the width and height will be used elsewhere. This will be as simple as a few properties and matching setters and getters.
First, in CoverFlow.as, add two properties at the beginning of the class:
private var _width:Number;
private var _height:Number;
And after the constructor, add the following setters and getters:
override public function set width(num:Number):void {
_width = num;
}
override public function get width():Number {
return _width;
}
override public function set height(num:Number):void {
_height = num;
}
override public function get height():Number {
return _height;
}
Since CoverFlow is a subclass of Sprite, there already are width and height setters and getters. So we need to be sure to override them. We don’t want the default behavior of stretching, so we’ll want to control that on our own. We’ll come back to these setters in a few steps.
However, having a size for the CoverFlow object is important enough to require these parameters in the constructor. The width and height determine much of the final layout, so we’ll add some parameters to the constructor and then immediately set our properties with them:
public function CoverFlow(w:Number, h:Number) {
_width = w;
_height = h;
_coversContainer = new Sprite();
addChild(_coversContainer);
var test:Cover = new Cover();
_coversContainer.addChild(test);
}
And of course we need to supply some arguments to this from CoverFlowTest. In that file, update the line that creates a new CoverFlow to this:
coverFlow = new CoverFlow(stage.stageWidth, stage.stageHeight);
There isn’t much to test right now, but if you like you can publish the movie and see if any compiler errors pop up. If there are any errors, take care of them now. You’ll know that the errors somehow relate to the code you just typed, so start there.
Step 10: Set the Background Color
Another property that will get used later will be the background color of the entire “flow.” Apple makes theirs black, but there’s no reason to stick with that, as it will be rather simple to change it. To make it happen, though, we’ll need a Shape object that sits at the bottom of the CoverFlow object’s display stack, and we’ll need to programmatically draw a rectangle of the chosen color into that Shape.
First, add two properties to CoverFlow, one to hold the Shape instance and one to store the background color:
private var _backgroundColor:uint = 0;
private var _background:Shape;
Notice that we’re giving _backgroundColor a default value, so that if it’s never set by the user of this class, we’ll have a black background anyway. The number 0 is the color code for black.
Next, write in the setter and getter for backgroundColor (we don’t need the Shape to be accessible outside of this class, just the color):
public function set backgroundColor(val:uint):void {
_backgroundColor = val;
drawBackground();
}
public function get backgroundColor():uint {
return _backgroundColor;
}
You’ll notice that we’re calling an as-of-yet nonexistent method called drawBackground. This will do what it says on the label. Let’s write it now:
private function drawBackground():void {
_background.graphics.clear();
_background.graphics.beginFill(_backgroundColor, 1);
_background.graphics.drawRect(0, 0, _width, _height);
}
This just clears out any previous graphics drawing in the background shape, sets the fill color to the current value of the property, and then draws a rectangle.
Finally, we need to set up the Shape initially. In the constructor, add this at the end:
_background = new Shape();
addChildAt(_background, 0);
drawBackground();
And go ahead and test it! You should see a black background behind our red square.
If you like, you can resize the player window, and you’ll see that we do indeed have a black rectangle sitting on top of the white base of the movie.
For reference, here is the complete CoverFlow class at this point. Changes made in this step are highlighted.
package com.tutsplus.coverflow {
import flash.display.*;
import flash.geom.*;
import flash.events.*;
import flash.net.*;
import flash.text.*;
import flash.utils.*;
public class CoverFlow extends Sprite {
private var _coversContainer:Sprite;
private var _width:Number;
private var _height:Number;
private var _backgroundColor:uint = 0;
private var _background:Shape;
public function CoverFlow(w:Number, h:Number) {
_width = w;
_height = h;
_coversContainer = new Sprite();
addChild(_coversContainer);
var test:Cover = new Cover();
_coversContainer.addChild(test);
_background = new Shape();
addChildAt(_background, 0);
drawBackground();
}
override public function set width(num:Number):void {
_width = num;
}
override public function get width():Number {
return _width;
}
override public function set height(num:Number):void {
_height = num;
}
override public function get height():Number {
return _height;
}
public function set backgroundColor(val:uint):void {
_backgroundColor = val;
drawBackground();
}
public function get backgroundColor():uint {
return _backgroundColor;
}
private function drawBackground():void {
_background.graphics.clear();
_background.graphics.beginFill(_backgroundColor, 1);
_background.graphics.drawRect(0, 0, _width, _height);
}
}
}
Step 11: Create the Mask
We may have created a background shape that responds to the size of the CoverFlow, but anything else we add to the object – like individual Covers – may not respect the intended size. What we need is a mask for the entire CoverFlow display object that gets set to the same size.
We could use a regular ol’ mask for this task, but because we are expecting a rectangular mask, we have an even easier approach. The scrollRect property of DisplayObjects provides functionality similar to that of masks, although there are differences. One advantage we have with scrollRect is a performance optimization. I don’t know specifics, but utilizing scrollRect tells Flash to render only the pixels contained within the rectangle, as opposed to regular masks, which still renders all pixels involved in the masked content.
Setting it up is as simple as this, in the CoverFlow constructor:
public function CoverFlow(w:Number, h:Number) {
// ...
drawBackground();
scrollRect = new Rectangle(0, 0, _width, _height);
// ...
There’s not much to test right now, but you can compile to make sure you didn’t make any typos.
Step 12: Adjust the Width and Height
Now, we need to implement our own sizing logic. In the width and height setters of CoverFlow, add these lines:
override public function set width(num:Number):void {
_width = num;
_background.width = _width;
scrollRect = new Rectangle(0, 0, _width, _height);
}
override public function get width():Number {
return _width;
}
override public function set height(num:Number):void {
_height = num;
_background.height = _height;
scrollRect = new Rectangle(0, 0, _width, _height);
}
override public function get height():Number {
return _height;
}
We can test this to a degree by adding a size change to the coverFlow object in CoverFlowTest:
public function CoverFlowTest() {
coverFlow = new CoverFlow(stage.stageWidth, stage.stageHeight);
addChild(coverFlow);
coverFlow.width = stage.stageWidth / 2;
coverFlow.height = stage.stageHeight / 3;
}
You should see what you’ve been seeing, only masked.
It’s hard to tell that the scrollRect is working at the moment, but at least you have expected results for now. Remove the two lines you just added; we’ll want a full-size CoverFlow in order to continue development.
Step 13: Add Properties to Cover
We’ll come back to CoverFlow.as in the near future, but for now we’re going to focus on getting an individual Cover instance up to speed.
Let’s think about what the Cover will need to do. It will need to load and display an image. It will need to display a caption. It will need to be positioned. It will also need to display a reflection beneath the image. When we get to XML data, we’ll have each Cover store the XML node related to that instance, so that we can store extra related information with the associated Cover. And it will need to dispatch a few events, for load progress, load complete, select (for when the cover comes into the center position), and click. The Cover could certainly do more, but for now, these capabilities pretty closely match what iTunes implementation of Cover Flow does, and will help keep our tutorial to a reasonable scope. For the code, this feature set means:
Load Image We’ll need a Loader to load the image, along with specifying the URL of the image to load.
Display Image We’ll need to add the Loader to the display list.
Display Caption We’ll need to be able to set the caption, put it into a TextField, and display the TextField. Note that this opens up the can of worms that is text styling, and the question of how much control of the style to open up outside of the class. For our purposes, we’ll stick with a standard styling. If you’d like an implementation that allows user-definable styles, that’s an exercise for later.
However, note that in the reference implementation of Cover Flow, the caption is not attached to the cover image, it’s a fixed area in the center bottom of the whole display area. What we’ll need is not a TextField for each Cover object, but a single TextField for the entire CoverFlow system. All the Cover object needs to do is store its caption. We’ll have CoverFlow then pull that information out of each Cover as it’s focused and handle its display. So all we really need right now is a storage mechanism for a caption.
Display Image Reflection This will require a Bitmap object and some BitmapData fanciness, but it’s not hard. However, it does require that we know the general background color of the entire Cover Flow display, because the easiest way to handle the transparency of the reflections is to not actually be transparent (if they were, we’d have overlaying reflections show through each other). So, we’ll require that the background color be passed in to our constructor from CoverFlow.
Also, we’ll want to hang onto the Bitmap, but the BitmapData can be a one-time object used to create the reflection in the first place.
Positioning Since we’re subclassing Sprite, anything we display within that Sprite is automatically positioned as a unit by the positional properties of Sprite. We won’t have to do anything to gain this functionality, other than make sure that we add the appropriate display objects as children of the Cover instance itself.
XML Data We’ll just need a property to store an arbitrary XML node and a way to get that back out of the object.
Events Again, since we’re a subclass of Sprite, we also automatically have the capability to dispatch events. In fact, the click event is already defined by the Sprite. Load progress and complete will really just be forwarded events from the LoaderInfo of the Loader we use to load the image. And select will actually be handled by CoverFlow, since it knows how to manage a collection of Covers. So, we’re done with this one, too!
Let’s add the properties we need, along with setters and getters where appropriate. We’ll follow the convention of making actual properties private, and providing public access through setters and getters.
In Cover.as, add some properties to the class file. I like to keep them grouped together, at the very top of the class definition:
private var _src:String;
private var _caption:String;
private var _data:XML;
private var _loader:Loader;
private var _reflection:Bitmap;
private var _backgroundColor:uint;
Write the setters and getters:
public function get caption():String {
return _caption;
}
public function get data():XML {
return _data;
}
public function set backgroundColor(num:Number):void {
_backgroundColor = num;
}
public function get backgroundColor():Number {
return _backgroundColor;
}
Why only have these? Well, other objects won’t really need access to the Bitmap or the Loader, and for the caption and data, we’ll operate on the assumption that once those values are set, they won’t need to change. We’ll deal with that in the next step.
Go ahead and test this out. There won’t be any changes to take note of; you should still just see a red square. But by testing the movie we run things through the compiler, which helps us find errors should any be introduced. If all went well, the movie will run and you’ll see the red square. Here is the complete Cover class as of now:
package com.tutsplus.coverflow {
import flash.display.*;
import flash.geom.*;
import flash.events.*;
import flash.net.*;
import flash.utils.*;
public class Cover extends Sprite {
private var _src:String;
private var _caption:String;
private var _data:XML;
private var _loader:Loader;
private var _reflection:Bitmap;
private var _backgroundColor:uint;
public function Cover() {
graphics.beginFill(0xff0000);
graphics.drawRect(0, 0, 200, 200);
}
public function get caption():String {
return _caption;
}
public function get data():XML {
return _data;
}
public function set backgroundColor(num:Number):void {
_backgroundColor = num;
}
public function get backgroundColor():Number {
return _backgroundColor;
}
}
}
Step 14: Set the Properties
As mentioned, we’ll set the properties like caption, data, and background color through the constructor. Modify the constructor of Cover.as so it takes those three values, and then transfers those values to the appropriate properties. Changes to the constructor below are highlighted:
public function Cover(caption:String, data:XML, backgroundColor:Number) {
_caption = caption;
_data = data;
_backgroundColor = backgroundColor;
graphics.beginFill(0xff0000);
graphics.drawRect(0, 0, 200, 200);
}
Now, back in CoverFlow.as, we need to supply values when we create our test Cover or else we’ll get errors. In the constructor:
public function CoverFlow(w:Number, h:Number) {
_width = w;
_height = h;
_coversContainer = new Sprite();
addChild(_coversContainer);
var test:Cover = new Cover("I am a caption", <data />, _backgroundColor);
_coversContainer.addChild(test);
_background = new Shape();
addChildAt(_background, 0);
drawBackground();
scrollRect = new Rectangle(0, 0, _width, _height);
}
We’re obviously using dummy data right now, but this should safely compile. Again, we won’t see any changes, but test the movie to make sure you haven’t introduced errors. However, we can write a quick test of what we wrote by tracing the values of the getters. Still in the CoverFlow constructor:
public function CoverFlow(w:Number, h:Number) {
_width = w;
_height = h;
_coversContainer = new Sprite();
addChild(_coversContainer);
var test:Cover = new Cover("I am a caption", <data />, _backgroundColor);
_coversContainer.addChild(test);
_background = new Shape();
addChildAt(_background, 0);
drawBackground();
scrollRect = new Rectangle(0, 0, _width, _height);
trace(test.caption);
trace(test.data.toXMLString());
trace(test.backgroundColor);
}
You should see the following in your Output panel:
This verifies that we are properly setting and getting at least the caption, data XML, and backgroundColor properties.
Step 15: Load an Image
For this step, we’ll need an image to load. There are several in the download package for this tutorial, already cropped and sized as squares. Let’s just pick one to load. I’ll use “best.jpg.”
First, put the images folder in the same project folder you’ve been using. It should be at the same location as your CoverFlowTest.swf. Either drop the images folder from the download here, or create your own images folder here and put the images you want to load into that folder.
Next, in the constructor of Cover.as, remove the lines that draw the red square.
public function Cover(caption:String, data:XML, backgroundColor:Number) {
_caption = caption;
_data = data;
_backgroundColor = backgroundColor;
//graphics.beginFill(0xff0000);
//graphics.drawRect(0, 0, 200, 200);
}
Now, create a public method called load. This will receive a string URL as a parameter, store it in the _src property, and then load the image from that URL.
public function load(src:String):void {
_src = src;
_loader = new Loader();
_loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onLoadProgress);
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadComplete);
_loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onLoadError);
addChild(_loader);
_loader.load(new URLRequest(_src));
}
This is standard Loader stuff. It will ultimately be up to another object (such as CoverFlow) to feed this value to the Cover.
We’ve added three event listeners, all standard fare for loading. Let’s write out some stub listener functions so we can test. Add this code to you class. These are new methods, not code within another method:
private function onLoadProgress(e:ProgressEvent):void {
trace("progress: " + e.bytesLoaded + " of " + e.bytesTotal);
}
private function onLoadComplete(e:Event):void {
trace("loaded");
}
private function onLoadError(e:IOErrorEvent):void {
trace("error: " + e.text)
}
We’ll end up doing something more useful with these, but for now we’ll fire off a trace just to make sure the functions get called in response to events. For reference, the entire class should look something like this (additions from this step are highlighted):
package com.tutsplus.coverflow {
import flash.display.*;
import flash.geom.*;
import flash.events.*;
import flash.net.*;
import flash.utils.*;
public class Cover extends Sprite {
private var _src:String;
private var _caption:String;
private var _data:XML;
private var _loader:Loader;
private var _reflection:Bitmap;
private var _backgroundColor:uint;
public function Cover(caption:String, data:XML, backgroundColor:Number) {
_caption = caption;
_data = data;
_backgroundColor = backgroundColor;
}
public function get caption():String {
return _caption;
}
public function get data():XML {
return _data;
}
public function set backgroundColor(num:Number):void {
_backgroundColor = num;
}
public function get backgroundColor():Number {
return _backgroundColor;
}
public function load(src:String):void {
_src = src;
_loader = new Loader();
_loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onLoadProgress);
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadComplete);
_loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onLoadError);
addChild(_loader);
_loader.load(new URLRequest(_src));
}
private function onLoadProgress(e:ProgressEvent):void {
trace("progress: " + e.bytesLoaded + " of " + e.bytesTotal);
}
private function onLoadComplete(e:Event):void {
trace("loaded");
}
private function onLoadError(e:IOErrorEvent):void {
trace("error: " + e.text)
}
}
}
Now, to test this, we need to hop back over to CoverFlow.as and at some point in the constructor, call the load method and pass in a valid path to an image:
public function CoverFlow(w:Number, h:Number) {
_width = w;
_height = h;
_coversContainer = new Sprite();
addChild(_coversContainer);
var test:Cover = new Cover("I am a caption", <data />, _backgroundColor);
_coversContainer.addChild(test);
_background = new Shape();
addChildAt(_background, 0);
drawBackground();
scrollRect = new Rectangle(0, 0, _width, _height);
trace(test.caption);
trace(test.data.toXMLString());
trace(test.backgroundColor);
test.load("images/best.jpg");
}
If you test the movie now, not only should you see an image show up in place of the red square:
…but you should also see some traces in the Output panel confirming that the progress and complete events were firing (your actual progress events may vary):
Obviously, the load completed because the image appeared, but it’s good to make sure we hooked up the event correctly. If you want to test the error event, just change the path value passed into the Cover constructor to something that won’t work, and you should see a different trace.
Step 16: Center the Image
Movement within the “flow” has two requirements. First, items need to rotate about a vertical axis that is centered horizontally on the image. Second, the bottom of the image needs to be aligned to a “ground” so that images of varying heights are all “sitting” on the same plane.
To make the vertical rotation easy, we can center the image horizontally in relation to the containing Sprite. Similarly, to make the bottom alignment easy, we can position the image so that its bottom edge is at the x-axis of the containing Sprite. To pull this off, we need know the size of the image that we just loaded. In order to determine that, we need to make sure the image is loaded before attempting to work with its size. So, all of our centering code needs to be in the complete handler.
Add this to the onLoadComplete method of Cover.as (and remove the trace that is currently there):
private function onLoadComplete(e:Event):void {
_loader.x = -Math.round(_loader.width / 2);
_loader.y = -_loader.height;
}
If you test this now, you probably won’t see an image at all, because the Cover sprite is being positioned at (0, 0) on the stage, but all of its visible content is above the registration point of the Cover sprite. So, before testing, add a few lines of code to position the Cover object in CoverFlow.as, just after creating the test Cover object:
test.x = _width / 2;
test.y = _height / 2;
Test it now, and you should see the image somewhere in the middle of the stage.
If you like, you can go back and re-test the setting of the width and height of the CoverFlow (see Step 12) to see if the scrollRect works to mask out the contents of CoverFlow. You should see a partial Cover object.
Step 17: Reflect the Image
Now we get into some more challenging stuff. We’re going to take the image we just loaded and create a copy of it that is flipped vertically (that is, it was rotated around the bottom edge). We’ll use BitmapData to clone the appearance of the image. Like before, because we need the actual image before we can do this, we’ll initiate the drawing of the reflection in the onLoadComplete method:
private function onLoadComplete(e:Event):void {
_loader.x = -Math.round(_loader.width / 2);
_loader.y = -_loader.height;
drawReflection();
}
private function drawReflection():void {
var clone:BitmapData = new BitmapData(_loader.width, _loader.height, false, 0x000000);
var flip:Matrix = new Matrix();
flip.scale(1, -1);
flip.translate(0, _loader.height);
clone.draw(_loader, flip);
_reflection = new Bitmap(clone);
addChild(_reflection);
_reflection.x = _loader.x;
}
That’s a lot of code that may be unfamiliar to you, depending on how much you’ve worked with BitmapData.
BitmapData, first of all, is a class that lets you work with the pixels of a bitmap. The first line creates one, specifying a width and height, transparency, and a default fill color.
The next thing we’ll do is usually a straight forward operation, where we draw the graphics of another display object into a rendered bitmap representation. However, we don’t want a straight clone, we want to flip the image. We can do that by passing in a Matrix object into the second parameter of the draw method. A Matrix object represents a geometric, two-dimensional transformation, including scale, rotation, and translation (or position). So, before we do the draw operation, we create a new Matrix object. Then we use the scale method on the Matrix to flip it vertically (the two arguments are horizontal scale and vertical scale; 1 being no change and -1 being an inversion). Next, because the scale operation performs similarly to how display objects work, we actually scaled the image so it’s “pointing” the other direction. So we need to reposition it to get it back onto the bitmap canvas. The translate method does this, repositioning the scaled image by the image’s height.
With the flipped image represented in a BitmapData object, we need to actually display it in a Bitmap object. BitmapData is a pure data representation and is not, itself, displayable. However, the Bitmap object is displayable, and handily enough takes a BitmapData object as the parameter to its constructor, so we create a Bitmap, add it to the display list, and finally position it horizontally to it’s aligned with the original image.
Try this out, and you should be seeing double.
The BitmapData operations can be confusing, so if they’re not clear to you at this point I encourage you to pursue further information on it. BitmapData opens up some very interesting possibilities, so it’s worth learning more about.
Step 18: Fade the Reflection
Now, to make the reflection fade, we need to fade to that background color, and keep the reflection opaque. It will give the appearance of being transparent, but if we keep it opaque, one reflection can be layered on top of another without the lower one showing through. Go ahead and look at the preview again if you need to visualize this:
We’ll add a bunch of drawing code to drawReflection (in Cover.as). Here’s the whole method, with the changes highlighted:
private function drawReflection():void {
var clone:BitmapData = new BitmapData(_loader.width, _loader.height, false, 0x000000);
var flip:Matrix = new Matrix();
flip.scale(1, -1);
flip.translate(0, _loader.height);
clone.draw(_loader, flip);
_reflection = new Bitmap(clone);
addChild(_reflection);
_reflection.x = _loader.x;
var gradient:Shape = new Shape();
var gradientMatrix:Matrix = new Matrix();
gradientMatrix.createGradientBox(_reflection.width, _reflection.height, Math.PI / 2);
var gradientFill:GraphicsGradientFill = new GraphicsGradientFill(GradientType.LINEAR, [_backgroundColor, _backgroundColor], [.5, 1], [0, 255], gradientMatrix);
var gradientRect:GraphicsPath = new GraphicsPath();
gradientRect.moveTo(0, 0);
gradientRect.lineTo(_reflection.width, 0);
gradientRect.lineTo(_reflection.width, _reflection.height);
gradientRect.lineTo(0, _reflection.height);
gradientRect.lineTo(0, 0);
var graphicsData:Vector.<IGraphicsData> = new Vector.<IGraphicsData>();
graphicsData.push(gradientFill, gradientRect);
gradient.graphics.drawGraphicsData(graphicsData);
_reflection.bitmapData.draw(gradient);
}
Yup, that’s quite a lot of code to chew on. In summary, it creates another Shape object, in which we draw a linear gradient. The gradient is set to be same color as the main background, with alpha changes going from half transparent to fully opaque, top to bottom. This gradient then gets merged into the BitmapData already containing the flipped reflection of the image, so that the final effect is a reflection that fades out to the background color.
Go ahead and try this out, you should feel good about obtaining these results:
However, if you test this further and try setting up the coverFlow instance in CoverFlowTest with a background color other than black, you’ll see some unpredictable results:
We’ll address this next.
Step 19: Keep Track of the Cover Instances
We are currently using the CoverFlow instance as a place to test a single Cover instance. And even though we’ll eventually get rid of that test instance, we now need to store it in an official list of all instances. We’ll create an Array of Cover instances, and every one that gets creates will get stashed in the Array. Actually, since we’re targeting Flash 10, we can make it a Vector, which will offer a small performance increase.
First, in CoverFlow.as, declare the Vector, alongside the rest of the properties:
private var _covers:Vector.<Cover>;
Then, instantiate that Vector almost immediately. In the constructor, put this line right after you set the _width and _height:
_covers = new Vector.<Cover>();
And after the “test” Cover object has been created (still in the constructor), add it to the Vector:
_covers.push(test);
The top part of your CoverFlow class should look like this (additions highlighted):
public class CoverFlow extends Sprite {
private var _coversContainer:Sprite;
private var _width:Number;
private var _height:Number;
private var _backgroundColor:uint = 0;
private var _background:Shape;
private var _covers:Vector.<Cover>;
public function CoverFlow(w:Number, h:Number) {
_width = w;
_height = h;
_covers = new Vector.<Cover>();
_coversContainer = new Sprite();
addChild(_coversContainer);
var test:Cover = new Cover("I am a caption", <data />, _backgroundColor);
_coversContainer.addChild(test);
test.x = _width / 2;
test.y = _height / 2;
_covers.push(test);
trace(test.caption);
trace(test.data.toXMLString());
trace(test.backgroundColor);
test.load("images/best.jpg");
_background = new Shape();
addChildAt(_background, 0);
drawBackground();
}
// ...
Step 20: Set the Background Color of the Covers
Now, in the backgroundColor setter, we not only need to draw the main background, but we need to inform all of our Cover instances that the background color has changed. The entire method will look like this (new code is highlighted):
public function set backgroundColor(val:uint):void {
_backgroundColor = val;
drawBackground();
for each (var cover:Cover in _covers) {
cover.backgroundColor = val;
}
}
Then, in the Cover class, update its backgroundColor setter so that it redraws the reflection:
public function set backgroundColor(num:Number):void {
_backgroundColor = num;
drawReflection();
}
Lastly, we need to do some error checking. In the test case that we have set up right now, the backgroundColor gets set before the image loads (and this is a reasonable action; typically you’ll set up the CoverFlow and give it a backgroundColor right away, as the images load). Because of this, the Loader has a width and height of 0, which makes the first line of drawReflection produce an Error. If you set the backgroundColor of the CoverFlow object right now and test the movie, you’ll see this:
This is easy enough to handle. If the Loader has a width and/or height of 0, we can safely assume that the loader hasn’t finished loading yet. So, the very first lines of drawReflection can check for this:
private function drawReflection():void {
if (_loader.width == 0 || _loader.height == 0) {
return;
}
var clone:BitmapData = new BitmapData(_loader.width, _loader.height, false, 0x000000);
var flip:Matrix = new Matrix();
// ...
Simply exit the method, and everything will be fine. Don’t worry, we also call drawReflection from onLoadComplete, so at that point, the _backgroundColor property will be set with the correct value, and the Loader will be loaded, so we can draw. In the event that we want to change the background color after the images have loaded, this still works, because the Loader will have non-zero dimensions, and drawReflection will run from the backgroundColor setter.
Try it out: go back to CoverFlowTest and set the CoverFlow instance’s background color:
public function CoverFlowTest() {
coverFlow = new CoverFlow(stage.stageWidth, stage.stageHeight);
addChild(coverFlow);
coverFlow.backgroundColor = 0xC14216;
}
And you’ll have a glorious orange thing going on:
Feel free to remove that line after you’re satisfied that the background color and the reflection works (what, you don’t like orange?).
Step 21: Write an XML Data Source
We’ll move on to providing a real set of data to drive this piece. Our test image can go away, and we’ll start displaying a set of images.
We’ll assume that in order to provide data to the CoverFlow object, it will most likely be provided as an external XML file. This makes for easier changes to live content, but also allows us to load more than one XML file to reuse the same CoverFlow module with different content in the same movie.
Before we write the ActionScript to handle the XML, let’s write our XML file. Create a new text file called coverFlowImages.xml in the same folder as your CoverFlow.fla file. There will be a root node, of course, and inside of that will simply be a list of image nodes, one for each item to appear in the flow. The general format for an image node will look like this:
<image src="path/to/image.jpg" title="A Titillating Title">
whatever data we want to associate with the image
</image>
It’s assumed that the image will have an image path, and probably a title. However, we may want to associate more data with each image, which might just be simple text, or we could even provide a nested XML structure with complex data within, for example:
<image src="people/DruKepple.jpg" title="Dru Kepple, ActionScript Implementor">
<name>
<first>Dru</first>
<last>Kepple</last>
</name>
<employment>
<company name="Summit Projects" url="http://www.summitprojects.com" />
<company name="Art Institute of Portland" url="http://www.aidepartments.com" />
</employment>
<websites>
<site url="summitprojectsflashblog.wordpress.com" />
<site url="www.thekeppleeffect.com" />
<site url="active.tutsplus.com/author/dru-kepple" />
<site url="www.linkedin.com/drukepple" />
</websites>
</image>
The point here is that inside of the image node, we can put whatever we want (from lengthy and complex XML data to nothing at all). This data will be available through the CoverFlow class, as the XML node that it is.
Here’s our final full document (I used other images and links during the build), a list of images and data culled from active.tutsplus.com:
<coverflow>
<image src="images/megaphone.jpg" title="HTML5, Flash and RIAs: 18 Industry Experts Have Their Say">
<link>http://active.tutsplus.com/articles/roundups/html5-and-flash-17-industry-experts-have-their-say/</link>
</image>
<image src="images/magnifyer.jpg" title="Create an Impressive Magnifying Effect with ActionScript 3.0">
<link>http://active.tutsplus.com/tutorials/effects/create-an-impressive-magnifying-effect-with-actionscript-30/</link>
</image>
<image src="images/as3101.jpg" title="AS3 101: Five Reasons to use Setters and Getters">
<link>http://active.tutsplus.com/tutorials/actionscript/as3-101-five-reasons-to-use-setters-and-getters/</link>
</image>
<image src="images/montypython.jpg" title="10 Flash Things You Can’t Do With HTML5">
<link>http://active.tutsplus.com/articles/roundups/10-flash-things-you-can’t-do-with-html5/</link>
</image>
<image src="images/bad.jpg" title="Blog Action Day: Clean up With a Beautiful Watery Game">
<link>http://active.tutsplus.com/tutorials/games/blog-action-day-clean-up-with-a-beautiful-watery-game/</link>
</image>
<image src="images/hype.jpg" title="Create a Mesmeric Music Visualizer with HYPE">
<link>http://active.tutsplus.com/tutorials/effects/create-a-mesmeric-music-visualizer-with-hype/</link>
</image>
<image src="images/max.jpg" title="Smart AS3 Video Loading with GreenSock LoaderMax – Free Active Premium!">
<link>http://active.tutsplus.com/tutorials/actionscript/smart-as3-video-loading-with-greensock-loadermax-free-active-premium/</link>
</image>
<image src="images/50twitterers.jpg" title="50 More Flash Twitterers Worth Following">
<link>http://active.tutsplus.com/articles/roundups/50-more-flash-twitterers-worth-following/</link>
</image>
<image src="images/open_mic_prefixes.jpg" title="Open Mike: Prefixes">
<link>http://active.tutsplus.com/articles/open-mike/open-mike-prefixes/</link>
</image>
<image src="images/fullscreen_website.jpg" title="Create a Full Screen, Scalable Flash Website: Part 1">
<link>http://active.tutsplus.com/tutorials/web-design/create-a-full-screen-scalable-flash-website-part-1/</link>
</image>
</coverflow>
It looks like a lot, but it’s really just a list of image nodes with two attributes each, the src and title, and a <link> node nested inside of the <image> node, which houses the URL of the article associated with the image.
Step 22: Load an XML File
To load XML, we’ll need a property to store the XML, and a property for a URLLoader to load the XML. We’ll need a public method to initiate a load with a String URL, some internal event handlers for the URLLoader to handle the XML load events. The elements of this step are pretty standard fare for loading XML, so I’ll just pile it all in to one step and not spend too much time explaining things.
Start by adding two properties, one for the urlLoader and one for the xml, at the top of the CoverFlow class, with the rest of the properties.
private var _urlLoader:URLLoader;
private var _xml:XML;
In CoverFlow’s constructor, create and set up the URLLoader (it doesn’t really matter where in the constructor, but I’m opting for at the end):
_urlLoader = new URLLoader();
_urlLoader.addEventListener(Event.COMPLETE, onXMLLoad);
_urlLoader.addEventListener(IOErrorEvent.IO_ERROR, onXMLLoadError);
Write the URLLoader event handling functions, somewhere in the main body of your class:
private function onXMLLoad(e:Event):void {
_xml = new XML(_urlLoader.data);
trace("XML Loaded:\n" + _xml);
}
private function onXMLLoadError(e:IOErrorEvent):void {
trace("There was an error loading the XML document: " + e.text);
}
Right now we’re just tracing things; we’re making sure we convert the URLLoader’s data to XML, then spitting it out as-is. We’re also handling an error in case we get a bad URL to load. We could do something fancier here, but for now we’re really just preventing the error from stopping everything else, while still tracing a message.
We need a public load method, to initiate the XML load. We can assume that if there is already something loaded, we should clear it out first, then start the new load. To that end, we’ll not only start the load on the URLLoader, but also call a method called clearContents to remove anything previously created in the CoverFlow. We’ll fill that in later, but we’ll plan for it and call it, and create an empty method to house it.
public function load(url:String):void {
clearContents();
_urlLoader.load(new URLRequest(url));
}
private function clearContents():void {
}
Lastly, we need to upgrade our tests. We need to remove the lines that create a test Cover from CoverFlow’s constructor (I’ve commented them out here so you can identify them, but go ahead and remove them. The next code snippet of this function will have them removed):
public function CoverFlow(w:Number, h:Number) {
_width = w;
_height = h;
_covers = new Vector.<Cover>();
_coversContainer = new Sprite();
addChild(_coversContainer);
//var test:Cover = new Cover("I am a caption", <data />, _backgroundColor);
//_coversContainer.addChild(test);
//test.x = _width / 2;
//test.y = _height / 2;
//_covers.push(test);
//trace(test.caption);
//trace(test.data.toXMLString());
//trace(test.backgroundColor);
//test.load("images/best.jpg");
_background = new Shape();
addChildAt(_background, 0);
drawBackground();
scrollRect = new Rectangle(0, 0, _width, _height);
_urlLoader = new URLLoader();
_urlLoader.addEventListener(Event.COMPLETE, onXMLLoad);
_urlLoader.addEventListener(IOErrorEvent.IO_ERROR, onXMLLoadError);
}
And then we need to go back to CoverFlowTest.as and add a call to load. Pass in the coverFlowImages.xml file we created in the last step.
public function CoverFlowTest() {
coverFlow = new CoverFlow(stage.stageWidth, stage.stageHeight);
addChild(coverFlow);
coverFlow.backgroundColor = 0x000000;
coverFlow.load("coverFlowImages.xml");
}
You should see our XML document traced to the Output panel.
Step 23: Parse the XML
Next we need to parse the XML and eventually do something with the data. We’ll parse it in this step, and start doing something with it in the next step.
In the onXMLLoad method of CoverFlow, remove the trace and replace it with some basic XML looping. For now, we’ll trace out values to make sure we’re parsing them correctly.
private function onXMLLoad(e:Event):void {
_xml = new XML(_urlLoader.data);
var imageList:XMLList = _xml.image;
var iLen:uint = imageList.length();
var imageNode:XML;
for (var i:uint = 0; i < iLen; i++) {
imageNode = imageList[i];
var src:String = imageNode.@src;
var title:String = imageNode.@title;
trace(src);
trace(title);
trace("");
}
}
There isn’t anything too special going on. We’re just selecting all image nodes, loop over them, and then extracting the attributes from them. Now, we’ll do something with them.
Step 24: Creating Cover Objects
We will have the potential to load quite a few images. It will be better to control the load by loading one at a time. This will maximize bandwidth for each image, letting the first image show up as soon as possible, so that there is something to see on screen before too long. Also, most browsers tend to throttle the number of simultaneous requests anyway, so rather than letting the browser control that, we may as well control it in Flash.
To work on this, we’ll need to actually load some images into multiple Cover objects, so we’ll start by creating the Cover objects and starting the load. We’ll finesse the process over the next few steps.
In CoverFlow‘s onXMLLoad method, we’ll remove the traces and instead create Cover objects:
private function onXMLLoad(e:Event):void {
_xml = new XML(_urlLoader.data);
var imageList:XMLList = _xml.image;
var iLen:uint = imageList.length();
var imageNode:XML;
var cover:Cover;
for (var i:uint = 0; i < iLen; i++) {
imageNode = imageList[i];
var src:String = imageNode.@src;
var title:String = imageNode.@title;
cover = new Cover(title, imageNode, _backgroundColor);
_coversContainer.addChild(cover);
cover.x = i * 200 + 100;
cover.y = 250;
cover.load(src);
_covers.push(cover);
}
}
You’ll notice that we’re doing probably what you’d expect: first, we create a new Cover object, passing in the data culled from the XML. Then we add it to the display list. Next we position it; this is temporary, but will allow us to see results for now. The x value is based on the number of iterations, so that we get a left-to-right placement. Again, we’ll revisit the layout logic, this is just to see something right now.
Then we tell the Cover to load with the image source found in the XML, and finally store the Cover object in our _covers Vector.
This call to load is also temporary; right now we’re just making sure that we’re successfully creating Cover objects from the XML data. We’ll move on to loading images sequentially next.
If you publish now, you should see something at least a little interesting:
No 3D yet, but that’s coming. Be patient!
Step 25: Loading Images in Sequence
We’re going to switch the logic from loading every Cover right away to loading them progressively. This will involve keeping track of a counter that points to the Cover that is currently loading, and a function that loads the next Cover. We have a few stops along the way, so follow along.
First, in Cover, we want to make sure we re-dispatch the COMPLETE event once the image loads. In onLoadComplete, add this line at the very end:
private function onLoadComplete(e:Event):void {
_loader.x = -Math.round(_loader.width / 2);
_loader.y = -_loader.height;
drawReflection();
dispatchEvent(e);
}
The rest of our changes will happen in CoverFlow. First, add a property to track the currently loading Cover by index:
private var _loadCounter:uint;
Then, in onXMLLoad, we’ll remove the var src:String =… and cover.load(src) lines, and set the _loadCounter property to 0, as well as call a method that we haven’t written yet:
private function onXMLLoad(e:Event):void {
_xml = new XML(_urlLoader.data);
var imageList:XMLList = _xml.image;
var iLen:uint = imageList.length();
var imageNode:XML;
var cover:Cover;
for (var i:uint = 0; i < iLen; i++) {
imageNode = imageList[i];
//var src:String = imageNode.@src;
var title:String = imageNode.@title;
cover = new Cover(title, imageNode, _backgroundColor);
_coversContainer.addChild(cover);
cover.x = i * 200 + 100;
cover.y = 250;
//cover.load(src);
_covers.push(cover);
}
_loadCounter = 0;
loadNextCover();
}
Now let’s write that loadNextCover method. The idea is to take the current value of _loadCounter and use it to target a Cover and a source image.
private function loadNextCover():void {
var cover:Cover = _covers[_loadCounter];
var src:String = _xml.image[_loadCounter].@src;
cover.load(src);
cover.addEventListener(Event.COMPLETE, onCoverLoad);
}
First, we get the previously created Cover object from the _covers Vector. Then we get the matching image URL by going back to the XML data and finding the image node using the same value of _loadCounter. Then we simply ask the Cover to load that URL. Finally, we add a COMPLETE listener, which we need to write next:
private function onCoverLoad(e:Event):void {
e.target.removeEventListener(Event.COMPLETE, onCoverLoad);
_loadCounter++;
if (_loadCounter < _covers.length) {
loadNextCover();
} else {
dispatchEvent(new Event(Event.COMPLETE));
}
}
Each time a Cover finishes loading, let’s first clean up after ourselves and remove the COMPLETE event listener. Then it will increment the _loadCounter and then check to see if we can still have Covers left in the _covers Vector. If we do, then we call loadNextCover() again, which starts the process over again with a different Cover and image. If not, then we must be at the end, so we can dispatch a COMPLETE event.
To test this event, hop back over to CoverFlowTest and add the following code:
public function CoverFlowTest() {
coverFlow = new CoverFlow(stage.stageWidth, stage.stageHeight);
addChild(coverFlow);
coverFlow.backgroundColor = 0x000000;
coverFlow.load("coverFlowImages.xml");
coverFlow.addEventListener(Event.COMPLETE, onCoverFlowLoaded);
}
private function onCoverFlowLoaded(e:Event):void {
trace("Coverflow loaded and ready to go.");
}
This should be straightforward: we’re just adding a listener to that COMPLETE event that just traces. Go ahead and run the movie now. You should see the images appear sequentially, and, once the images are all loaded, you should see the “Coverflow loaded and ready to go.” message in the Output panel.
Step 26: Determining Progress
To be able to dispatch PROGRESS events as the images load, we’re going to fake things a bit. We’re going to assume that the first image to load is, on average, representative of all of the images. There will certainly be cases where this is not true, but for for most applications we’ll be dealing with images of similar dimension, quality, and content, and therefore most images will fall around a similar file size.
First, we need to change the onLoadProgress method in Cover so that we get rid of the trace and redispatch the PROGRESS event:
private function onLoadProgress(e:ProgressEvent):void {
dispatchEvent(e);
}
Then we’ll need two more properties in CoverFlow to help track the overall progress:
private var _bytesPerImage:int;
private var _bytesTotal:int;
Now, the next thing to do is get the size of the first image once it starts loading. We need to make sure we’re adding a PROGRESS event listener when we start the load. In CoverFlow’s loadNextCover method:
private function loadNextCover():void {
var cover:Cover = _covers[_loadCounter];
var src:String = _xml.image[_loadCounter].@src;
cover.load(src);
cover.addEventListener(Event.COMPLETE, onCoverLoad);
cover.addEventListener(ProgressEvent.PROGRESS, onCoverProgress);
}
And add the onCoverProgress method:
private function onCoverProgress(e:ProgressEvent):void {
if (_bytesPerImage == 0) {
_bytesPerImage = e.bytesTotal;
_bytesTotal = _bytesPerImage * _covers.length;
}
var adjustedBytesLoaded:uint = e.bytesLoaded * (_bytesPerImage / e.bytesTotal);
var cumulativeBytesLoaded:uint = (_loadCounter * _bytesPerImage) + adjustedBytesLoaded;
dispatchEvent(new ProgressEvent(ProgressEvent.PROGRESS, false, false, cumulativeBytesLoaded, _bytesTotal));
}
Now, to test it, go back to CoverFlowTest and add a listener for the PROGRESS event:
public function CoverFlowTest() {
coverFlow = new CoverFlow(stage.stageWidth, stage.stageHeight);
addChild(coverFlow);
coverFlow.backgroundColor = 0x000000;
coverFlow.load("coverFlowImages.xml");
coverFlow.addEventListener(Event.COMPLETE, onCoverFlowLoaded);
coverFlow.addEventListener(ProgressEvent.PROGRESS, onCoverFlowProgress);
}
private function onCoverFlowProgress(e:ProgressEvent):void {
trace("Coverflow progress: " + e.bytesLoaded + " / " + e.bytesTotal);
}
And test the movie. You should see a long string of progress traces, terminating in the “loaded” message, something like the following:
Of course, you’ll want to display something informative on the stage, not trace out numbers. This particular task, however, isn’t really up to CoverFlow; it’s enough that it’s dispatching the appropriate events. I won’t belabor the creation of a progress bar, and instead, I’ll turn to the more interesting work of displaying Covers in 3D.
Step 27: Refactor the Logic
We’ll look at that loop that parses the XML, creates the Cover objects, and lays them out. Let’s offload the layout logic to another method. Remove the lines in the loop that position the Cover object (you might want to copy them), and add a call to a yet-to-be-written method after the loop.
private function onXMLLoad(e:Event):void {
_xml = new XML(_urlLoader.data);
var imageList:XMLList = _xml.image;
var iLen:uint = imageList.length();
var imageNode:XML;
var cover:Cover;
for (var i:uint = 0; i < iLen; i++) {
imageNode = imageList[i];
var src:String = imageNode.@src;
var title:String = imageNode.@title;
cover = new Cover(title, imageNode, _backgroundColor);
_coversContainer.addChild(cover);
//cover.x = i * 200 + 100;
//cover.y = 250;
_covers.push(cover);
}
layout();
_loadCounter = 0;
loadNextCover();
}
Next, write that layout method. It’s another loop, this one over the _covers Vector, and internally it does the same positioning logic:
private function layout():void {
var len:uint = _covers.length;
var cover:Cover;
for (var i:uint = 0; i < len; i++) {
cover = _covers[i];
cover.x = i * 200 + 100;
cover.y = 250;
}
}
Go ahead and test it now; you should see absolutely no change. The only difference is purely behind-the-scenes logic. The advantage we’ve added is that we’ll be able to call layout() at any time, independent of onXMLLoad().
Step 28: Initial Layout
Let’s go for a big pay off right now. We’ll rewrite the layout logic so that thing start to happen in 3D. Remove the cover.x = … line and add the highlighted lines below (still in CoverFlow):
private function layout():void {
var len:uint = _covers.length;
var cover:Cover;
for (var i:uint = 0; i < len; i++) {
cover = _covers[i];
if (i == 0) {
cover.rotationY = 0;
cover.x = _background.width / 2;
cover.z = 0;
} else {
cover.rotationY = 45;
cover.x = ((_background.width / 2) + 60) + (i * 30);
cover.z = 150;
}
cover.y = 250;
}
}
This logic needs a lot of love, but go ahead and run it now, and you should see…something not quite right.
You should see the potential there, but obviously we need to manage depth. This is a drawback to using Flash’s built-in 3D capabilities: it renders each DisplayObject properly, but not a “scene” of multiple DisplayObjects. Normal 2D depth stacking rules apply, even if the “z” of a given object should place it otherwise.
This bit of logic, though, gives you a glimpse of what we’re going to do: First, determine where in the “flow” a given Cover is – centered, on the right or (eventually) on the left. Then set up the Cover’s x, z, and rotationY properties appropriately. The math involved in the right-side x position is a mouthful, but can be read like this:
Start at the center (_background.width / 2), move 60 pixels to the right to give some space around the centered item ( … + 60), then, depending on where we are in the loop, move the Cover further to the right (… + (i + 30)).
Step 29: Managing Depth
Let’s next address the depth problem. Here’s what needs to happen: the centered item needs to be front most. After that, items on either side need to be decrease in depth index the further they are from the center. This is, fortunately, relatively simple to accomplish. Adjust the logic in CoverFlow’s layout method:
private function layout():void {
var len:uint = _covers.length;
var cover:Cover;
for (var i:uint = 0; i < len; i++) {
cover = _covers[i];
if (i == 0) {
cover.rotationY = 0;
cover.x = _background.width / 2;
cover.z = 0;
_coversContainer.setChildIndex(cover, _coversContainer.numChildren-1);
} else {
cover.rotationY = 45;
cover.x = ((_background.width / 2) + 60) + (i * 30);
cover.z = 150;
_coversContainer.setChildIndex(cover, _coversContainer.numChildren - (i + 1));
}
cover.y = 250;
}
}
In the first if block, we’re on the centered cover, so we set the index of the Cover to the highest index available. In the else block, the higher i is, the lower the index number we get. That works relative to other Covers on the right side, but we need to take the index down by one more to accommodate the center (highest) Cover.
Try it out now…you should see some promising visuals!
Step 30: The Left Side
OK, so far we’ve been making assumptions that make it very hard to lay things out for real. The big assumption is that we’re centering the first Cover (index 0). If you tried to center, say, the fourth Cover, you’d get results that aren’t quite expected:
It doesn’t look bad at first glance, but think about it. If we’re centering the fourth Cover, we’d expect to see three Covers on the left, the fourth one in the center, and the rest on the right. Let’s make that happen.
First, let’s create a new property (still in CoverFlow) that will hold our current index value. Let’s call it _selectedIndex.
private var _selectedIndex:uint;
And, for testing purposes only, we’ll set that value to 4 at the top of the layout method. This will get removed in the next step. Then, we’ll rework the logic within the loop of layout to be a little more dynamic.
private function layout():void {
_selectedIndex = 4;
var len:uint = _covers.length;
var cover:Cover;
var distanceFromCenter:uint;
for (var i:uint = 0; i < len; i++) {
cover = _covers[i];
if (i == _selectedIndex) {
cover.rotationY = 0;
cover.x = _background.width / 2;
cover.z = 0;
_coversContainer.setChildIndex(cover, _coversContainer.numChildren-1);
} else if (i < _selectedIndex) {
distanceFromCenter = _selectedIndex - i;
cover.rotationY = -45;
cover.x = ((_background.width / 2) - 60) - (distanceFromCenter * 30);
cover.z = 150;
_coversContainer.setChildIndex(cover, _coversContainer.numChildren - (distanceFromCenter + 1));
} else if (i > _selectedIndex) {
distanceFromCenter = i - _selectedIndex;
cover.rotationY = 45;
cover.x = ((_background.width / 2) + 60) + (distanceFromCenter * 30);
cover.z = 150;
_coversContainer.setChildIndex(cover, _coversContainer.numChildren - (distanceFromCenter + 1));
}
cover.y = 250;
}
}
That’s a lot of logic and math, but it’s actually rather repetitive. The new block is in the middle, but it’s nearly identical to the other else if block, only a few things are reversed. But go ahead and test the movie, it should look something like this:
The big change was the move away from i as a direct factor in the placement of Covers, but instead determining the distance that i is from the current index. The further away it is, the the further away the x has to be from the center, and also the further back in depth it has to be. The math is just a translation from what we were doing before to a more dynamic approach. If you like, go ahead and try setting _selectedIndex to other values, and ensure that you get the results you expect.
Step 31: Customizing the Appearance
You may feel that the distribution of Covers is a little cramped (I know I do, but I have to work within the 600 pixel wide limit that Activetuts+ places on me). In fact, there are quite a few positioning parameters that could be tweaked to adjust the overall look. We’ll go ahead and create a bunch of properties, along with associated setters and getters, to handle this customization. And we’ll of course use those properties instead of hard-coded Numbers in our layout method.
This will be a lengthy step, but fear not, it’s fairly basic.
First, the properties:
private var _centerMargin:Number;
private var _horizontalSpacing:Number;
private var _backRowDepth:Number;
private var _backRowAngle:Number;
private var _verticalOffset:Number;
These properties will control the following:
- centerMargin controls the amount of space on either side of the center Cover and the first Covers to the side. It should be a positive value.
- horizontalSpacing controls the amount of space between Covers in the “back.” That is, all of the Cover on the left and right (but not counting the center) will have the same amount of space in between adjacent Covers. It should be a positive value.
- backRowDepth controls how far back the back row is. This will be in the form of an offset, so as to prevent the back row from being in front of the center Cover. It should be a positive value.
- backRowAngle controls the angle at which Covers in the back row will turn. This is sort of an absolute value, and the value is “mirrored” for the other side. It should be constrained between 0 and 90.
- verticalOffset controls the amount by which to move the whole set of Covers up or down, offset from the automatically determined y value. This can be any Number. We’ll come back to this bit of logic, but we may as well write the property, setter, and getter while we’re doing the other four.
We’ll set up constants to contain the default values of each of these properties. These can go with the rest of your properties:
private static const DEFAULT_CENTER_MARGIN:Number = 60;
private static const DEFAULT_HORIZONTAL_SPACING:Number = 30;
private static const DEFAULT_BACK_ROW_DEPTH:Number = 150;
private static const DEFAULT_BACK_ROW_ANGLE:Number = 45;
private static const DEFAULT_VERTICAL_OFFSET:Number = 0;
In the constructor, set each of the properties to these default values (if you don’t like the default values, you can change them, that’s part of the reason for putting them together in an easy to find spot). This way we’ll be sure that each of these variables is set with a suitable value even if the user never specified one.
public function CoverFlow(w:Number, h:Number) {
_width = w;
_height = h;
_covers = new Vector.<Cover>();
_centerMargin = DEFAULT_CENTER_MARGIN;
_horizontalSpacing = DEFAULT_HORIZONTAL_SPACING;
_backRowDepth = DEFAULT_BACK_ROW_DEPTH;
_backRowAngle = DEFAULT_BACK_ROW_ANGLE;
_verticalOffset = DEFAULT_VERTICAL_OFFSET;
_coversContainer = new Sprite();
addChild(_coversContainer);
_background = new Shape();
addChildAt(_background, 0);
drawBackground();
scrollRect = new Rectangle(0, 0, _width, _height);
_urlLoader = new URLLoader();
_urlLoader.addEventListener(Event.COMPLETE, onXMLLoad);
_urlLoader.addEventListener(IOErrorEvent.IO_ERROR, onXMLLoadError);
}
And, with the valid values in mind, write the setters and getters (I’m going to put these right after our current setters and getters, around line 89):
public function set centerMargin(num:Number):void {
if (isNaN(num)) num = DEFAULT_CENTER_MARGIN;
_centerMargin = Math.max(0, num);
}
public function get centerMargin():Number {
return _centerMargin;
}
public function set horizontalSpacing(num:Number):void {
if (isNaN(num)) num = DEFAULT_HORIZONTAL_SPACING;
_horizontalSpacing = Math.max(0, num);
}
public function get horizontalSpacing():Number {
return _horizontalSpacing;
}
public function set backRowDepth(num:Number):void {
if (isNaN(num)) num = DEFAULT_BACK_ROW_DEPTH;
_backRowDepth = Math.max(0, num);
}
public function get backRowDepth():Number {
return _backRowDepth;
}
public function set backRowAngle(num:Number):void {
if (isNaN(num)) num = DEFAULT_BACK_ROW_ANGLE;
_backRowAngle = Math.min(90, Math.abs(num));
}
public function get backRowAngle():Number {
return _backRowAngle;
}
public function set verticalOffset(num:Number):void {
if (isNaN(num)) num = DEFAULT_VERTICAL_OFFSET;
_verticalOffset = num;
}
public function get verticalOffset():Number {
return _verticalOffset;
}
And lastly we need to replace numbers embedded in our layout logic with these properties. In layout:
for (var i:uint = 0; i < len; i++) {
cover = _covers[i];
if (i == _selectedIndex) {
cover.rotationY = 0;
cover.x = _background.width / 2;
cover.z = 0;
_coversContainer.setChildIndex(cover, _coversContainer.numChildren-1);
} else if (i < _selectedIndex) {
distanceFromCenter = _selectedIndex - i;
cover.rotationY = -_backRowAngle;
cover.x = ((_background.width / 2) - _centerMargin) - (distanceFromCenter * _horizontalSpacing);
cover.z = _backRowDepth;
_coversContainer.setChildIndex(cover, _coversContainer.numChildren - (distanceFromCenter + 1));
} else if (i > _selectedIndex) {
distanceFromCenter = i - _selectedIndex;
cover.rotationY = _backRowAngle;
cover.x = ((_background.width / 2) + _centerMargin) + (distanceFromCenter * _horizontalSpacing);
cover.z = _backRowDepth;
_coversContainer.setChildIndex(cover, _coversContainer.numChildren - (distanceFromCenter + 1));
}
cover.y = 250;
}
You can test the movie as is, and things should function exactly as they have before. However, you can also test these properties by setting them from CoverFlowTest. Set them however you like (in fact, be sure to test the illegal values, like -200 for the centerMargin), for example:
public function CoverFlowTest() {
coverFlow = new CoverFlow(stage.stageWidth, stage.stageHeight);
addChild(coverFlow);
coverFlow.backgroundColor = 0x000000;
coverFlow.horizontalSpacing = 60;
coverFlow.centerMargin = 100;
coverFlow.load("coverFlowImages.xml");
coverFlow.addEventListener(Event.COMPLETE, onCoverFlowLoaded);
coverFlow.addEventListener(ProgressEvent.PROGRESS, onCoverFlowProgress);
}
Step 32: Efficient Layout
Right now, our CoverFlow works and is somewhat customizable, but only if we set the values before the XML file loads. As it is now, setting the properties at any point after that will result in no change.
This could be as easy as simply calling layout() from each of the setters. However, this is prone to inefficient use of CPU cycles. If you needed to set all five properties in one fell swoop, you’d end up executing the layout logic 5 times in row, the first 4 being pointless since you weren’t done setting the values to what you needed to.
Because Flash operates on frame model of rendering, wherein code executes in between each frame, and then the display is updated, we need a way to only run that layout method when the stage is about to be rendered for the next frame. This could let us set properties as much as we like, but still only redraw the CoverFlow once per frame.
There’s an easy way to do this, fortunately, but it does take some wherewithal. We need to utilize the RENDER event. The RENDER event will get dispatched by a DisplayObject when the stage is about to get rendered, but before the render happens. As a bonus, the event doesn’t dispatch when the Flash Player is minimized, meaning we shouldn’t be wasting cycles if you can’t even see the movie.
Implementing this is a three step process: first, we need to listen for the event. In the constructor of CoverFlow, add this line:
this.addEventListener(Event.RENDER, onRender);
Next, add the listener method:
private function onRender(e:Event):void {
layout();
}
Yup, that’s it…we’ll just call layout each time we get the event.
Lastly, we need to call invalidate on the stage each time we want the RENDER event come our way. This means that in each of the setters, we need to add this line at the very end:
if (stage) stage.invalidate();
If there is no stage, we don’t want to call a method and cause a null object reference error. Anyway, if there is no stage, then the CoverFlow object isn’t on the display list anyway, so there’s not point in asking for the render event.
The call to invalidate, however, is how we get the RENDER event to fire. Without that call, we won’t get the event, even with an event listener. So, we need this in each setter:
public function set centerMargin(num:Number):void {
if (isNaN(num)) num = DEFAULT_CENTER_MARGIN;
_centerMargin = Math.max(0, num);
if (stage) stage.invalidate();
}
public function get centerMargin():Number {
return _centerMargin;
}
public function set horizontalSpacing(num:Number):void {
if (isNaN(num)) num = DEFAULT_HORIZONTAL_SPACING;
_horizontalSpacing = Math.max(0, num);
if (stage) stage.invalidate();
}
public function get horizontalSpacing():Number {
return _horizontalSpacing;
}
public function set backRowDepth(num:Number):void {
if (isNaN(num)) num = DEFAULT_BACK_ROW_DEPTH;
_backRowDepth = Math.max(0, num);
if (stage) stage.invalidate();
}
public function get backRowDepth():Number {
return _backRowDepth;
}
public function set backRowAngle(num:Number):void {
if (isNaN(num)) num = DEFAULT_BACK_ROW_ANGLE;
_backRowAngle = Math.min(90, Math.abs(num));
if (stage) stage.invalidate();
}
public function get backRowAngle():Number {
return _backRowAngle;
}
public function set verticalOffset(num:Number):void {
if (isNaN(num)) num = DEFAULT_VERTICAL_OFFSET;
_verticalOffset = num;
if (stage) stage.invalidate();
}
public function get verticalOffset():Number {
return _verticalOffset;
}
So now, if we set all 5 properties at the same time, we may call invalidate on the stage more than once, but that’s fine, that’s not going to cause problems. We should get a single RENDER event as a result, meaning we lay out the CoverFlow only once per frame.
To test this, we can put some traces into our methods, and then set these properties after the XML has loaded. First, add a trace message to onRender:
private function onRender(e:Event):void {
trace("render")
layout();
}
Then, in CoverFlowTest, set all 5 properties in onCoverFlowLoaded:
private function onCoverFlowLoaded(e:Event):void {
trace("Coverflow loaded and ready to go.");
coverFlow.horizontalSpacing = 100;
coverFlow.centerMargin = 75;
coverFlow.backRowDepth = 300;
coverFlow.backRowAngle = 75;
coverFlow.verticalOffset = 50;
}
You should see the movie load images as before, however, this time, the images should jump to a slightly different layout once all of the images have loaded. This proves that things work visually, but more importantly, check the Output panel. You should see a single “render” message. We called stage.invalidate from the 5 setters, but that resulted in only a single RENDER event, which is what we’re after.
Feel free to remove the trace and the layout code we just added.
Step 33: Regroup
It’s been a while since I’ve listed the full class code. Our work has been mainly in CoverFlow. Here is the current state of things with that class:
package com.tutsplus.coverflow {
import flash.display.*;
import flash.geom.*;
import flash.events.*;
import flash.net.*;
import flash.text.*;
import flash.utils.*;
public class CoverFlow extends Sprite {
private var _coversContainer:Sprite;
private var _width:Number;
private var _height:Number;
private var _backgroundColor:uint = 0;
private var _background:Shape;
private var _covers:Vector.<Cover>;
private var _urlLoader:URLLoader;
private var _xml:XML;
private var _loadCounter:uint;
private var _bytesPerImage:int;
private var _bytesTotal:int;
private var _selectedIndex:uint;
private var _centerMargin:Number;
private var _horizontalSpacing:Number;
private var _backRowDepth:Number;
private var _backRowAngle:Number;
private var _verticalOffset:Number;
private static const DEFAULT_CENTER_MARGIN:Number = 60;
private static const DEFAULT_HORIZONTAL_SPACING:Number = 30;
private static const DEFAULT_BACK_ROW_DEPTH:Number = 150;
private static const DEFAULT_BACK_ROW_ANGLE:Number = 45;
private static const DEFAULT_VERTICAL_OFFSET:Number = 0;
public function CoverFlow(w:Number, h:Number) {
_width = w;
_height = h;
_covers = new Vector.<Cover>();
_centerMargin = DEFAULT_CENTER_MARGIN;
_horizontalSpacing = DEFAULT_HORIZONTAL_SPACING;
_backRowDepth = DEFAULT_BACK_ROW_DEPTH;
_backRowAngle = DEFAULT_BACK_ROW_ANGLE;
_verticalOffset = DEFAULT_VERTICAL_OFFSET;
_coversContainer = new Sprite();
addChild(_coversContainer);
_background = new Shape();
addChildAt(_background, 0);
drawBackground();
scrollRect = new Rectangle(0, 0, _width, _height);
_urlLoader = new URLLoader();
_urlLoader.addEventListener(Event.COMPLETE, onXMLLoad);
_urlLoader.addEventListener(IOErrorEvent.IO_ERROR, onXMLLoadError);
this.addEventListener(Event.RENDER, onRender);
}
override public function set width(num:Number):void {
_width = num;
_background.width = _width;
scrollRect = new Rectangle(0, 0, _width, _height);
}
override public function get width():Number {
return _width;
}
override public function set height(num:Number):void {
_height = num;
_background.height = _height;
scrollRect = new Rectangle(0, 0, _width, _height);
}
override public function get height():Number {
return _height;
}
public function set backgroundColor(val:uint):void {
_backgroundColor = val;
drawBackground();
for each (var cover:Cover in _covers) {
cover.backgroundColor = val;
}
}
public function get backgroundColor():uint {
return _backgroundColor;
}
public function set centerMargin(num:Number):void {
if (isNaN(num)) num = DEFAULT_CENTER_MARGIN;
_centerMargin = Math.max(0, num);
if (stage) stage.invalidate();
}
public function get centerMargin():Number {
return _centerMargin;
}
public function set horizontalSpacing(num:Number):void {
if (isNaN(num)) num = DEFAULT_HORIZONTAL_SPACING;
_horizontalSpacing = Math.max(0, num);
if (stage) stage.invalidate();
}
public function get horizontalSpacing():Number {
return _horizontalSpacing;
}
public function set backRowDepth(num:Number):void {
if (isNaN(num)) num = DEFAULT_BACK_ROW_DEPTH;
_backRowDepth = Math.max(0, num);
if (stage) stage.invalidate();
}
public function get backRowDepth():Number {
return _backRowDepth;
}
public function set backRowAngle(num:Number):void {
if (isNaN(num)) num = DEFAULT_BACK_ROW_ANGLE;
_backRowAngle = Math.min(90, Math.abs(num));
if (stage) stage.invalidate();
}
public function get backRowAngle():Number {
return _backRowAngle;
}
public function set verticalOffset(num:Number):void {
if (isNaN(num)) num = DEFAULT_VERTICAL_OFFSET;
_verticalOffset = num;
if (stage) stage.invalidate();
}
public function get verticalOffset():Number {
return _verticalOffset;
}
private function drawBackground():void {
_background.graphics.clear();
_background.graphics.beginFill(_backgroundColor, 1);
_background.graphics.drawRect(0, 0, _width, _height);
}
private function layout():void {
_selectedIndex = 4;
var len:uint = _covers.length;
var cover:Cover;
var distanceFromCenter:uint;
for (var i:uint = 0; i < len; i++) {
cover = _covers[i];
if (i == _selectedIndex) {
cover.rotationY = 0;
cover.x = _background.width / 2;
cover.z = 0;
_coversContainer.setChildIndex(cover, _coversContainer.numChildren-1);
} else if (i < _selectedIndex) {
distanceFromCenter = _selectedIndex - i;
cover.rotationY = -_backRowAngle;
cover.x = ((_background.width / 2) - _centerMargin) - (distanceFromCenter * _horizontalSpacing);
cover.z = _backRowDepth;
_coversContainer.setChildIndex(cover, _coversContainer.numChildren - (distanceFromCenter + 1));
} else if (i > _selectedIndex) {
distanceFromCenter = i - _selectedIndex;
cover.rotationY = _backRowAngle;
cover.x = ((_background.width / 2) + _centerMargin) + (distanceFromCenter * _horizontalSpacing);
cover.z = _backRowDepth;
_coversContainer.setChildIndex(cover, _coversContainer.numChildren - (distanceFromCenter + 1));
}
cover.y = 250;
}
}
private function onXMLLoad(e:Event):void {
_xml = new XML(_urlLoader.data);
var imageList:XMLList = _xml.image;
var iLen:uint = imageList.length();
var imageNode:XML;
var cover:Cover;
for (var i:uint = 0; i < iLen; i++) {
imageNode = imageList[i];
var title:String = imageNode.@title;
cover = new Cover(title, imageNode, _backgroundColor);
_coversContainer.addChild(cover);
_covers.push(cover);
}
layout();
_loadCounter = 0;
loadNextCover();
}
private function onXMLLoadError(e:IOErrorEvent):void {
trace("There was an error loading the XML document: " + e.text);
}
public function load(url:String):void {
clearContents();
_urlLoader.load(new URLRequest(url));
}
private function clearContents():void {
}
private function loadNextCover():void {
var cover:Cover = _covers[_loadCounter];
var src:String = _xml.image[_loadCounter].@src;
cover.load(src);
cover.addEventListener(Event.COMPLETE, onCoverLoad);
cover.addEventListener(ProgressEvent.PROGRESS, onCoverProgress);
}
private function onCoverLoad(e:Event):void {
e.target.removeEventListener(Event.COMPLETE, onCoverLoad);
_loadCounter++;
if (_loadCounter < _covers.length) {
loadNextCover();
} else {
dispatchEvent(new Event(Event.COMPLETE));
}
}
private function onCoverProgress(e:ProgressEvent):void {
if (_bytesPerImage == 0) {
_bytesPerImage = e.bytesTotal;
_bytesTotal = _bytesPerImage * _covers.length;
}
var adjustedBytesLoaded:uint = e.bytesLoaded * (_bytesPerImage / e.bytesTotal);
var cumulativeBytesLoaded:uint = (_loadCounter * _bytesPerImage) + adjustedBytesLoaded;
dispatchEvent(new ProgressEvent(ProgressEvent.PROGRESS, false, false, cumulativeBytesLoaded, _bytesTotal));
}
private function onRender(e:Event):void {
layout();
}
}
}
Step 34: Caption
We have a few more things to tidy up before we get to animation and fun interactivity. We’ll take on the label. To get this rolling, we just need a text field. We’ll set up some default styling, and open the styles up for customization in the next step.
First, create a TextField, and add it to the CoverFlow. In CoverFlow, alongside the rest of your properties, create a TextField property:
private var _captionField:TextField;
Then set it up in the constructor (anywhere is fine, but I’m putting it after everything else in the constructor):
_captionField = new TextField;
addChild(_captionField);
_captionField.width = 200;
_captionField.height = 50;
_captionField.x = (_width - _captionField.width) / 2;
_captionField.y = _height - 80;
_captionField.multiline = true;
_captionField.wordWrap = true;
var fontName:String;
var fonts:Array = Font.enumerateFonts(true);
for each (var font:Font in fonts) {
trace(font.fontName);
if (font.fontName.search(/lucida.*grande/i) > -1) {
fontName = font.fontName;
break;
}
}
if (!fontName) fontName = "Verdana";
var format:TextFormat = new TextFormat(fontName, 12, 0xFFFFFF);
format.align = TextFormatAlign.CENTER;
_captionField.defaultTextFormat = format;
Finally, in layout, add in a line to set the text of the TextField:
private function layout():void {
_selectedIndex = 4;
var len:uint = _covers.length;
var cover:Cover;
var distanceFromCenter:uint
for (var i:uint = 0; i < len; i++) {
cover = _covers[i];
if (i == _selectedIndex) {
cover.rotationY = 0;
cover.x = _background.width / 2;
cover.z = 0;
_coversContainer.setChildIndex(cover, _coversContainer.numChildren-1);
_captionField.text = cover.caption;
// ...
The TextField creation in the constructor is possibly a bit daunting. For the most part, though, it’s fairly standard TextField setup, all done through code. If you’ve never done that before, you may be surprised at the number of lines necessary to set up a TextField. This is typical; the default TextField in pretty bland, and we need to make sure that the size is set, that it’s a multiline textfield, and that it has a basic format.
Even if you’ve written programmatic TextFields before, the “fontName” business might still be a surprise. The general idea is that we’re setting up a default style, based on Apple’s use of the font Lucida Grande as their system font. But we can’t be confident that users will have that font (most, if not all, Macs running OS X should, but we can’t be 100% sure and PC’s are another story). So we get an Array of system fonts, using Font.enumerateFont(true). The “true” tells enumerateFont to enumerate the system fonts; otherwise, it enumerates the fonts emebedded into the SWF. This returns an Array of Font objects. We loop over that Array, looking for a font with a name similar to “Lucida Grande.” That’s a regular expression in the “search” call, which just gives us some flexibility in case the font name is slightly different on one system as opposed to another. If we find a match, grab the font name and break the loop. If we make it through the loop without a match, just use “Verdana.” This gives us Lucida Grande if the user has it, and a fallback sans serif font if they don’t.
Go ahead and try it out; you should see your label show up below the centered item.
Also, you may notice a bunch of extra traces showing up in the Output panel. This is from the font loop in the constructor. We don’t need this long term, but I thought it would be useful to see these fonts being enumerated. Your output will be different, naturally, depending on the fonts installed on your system.
After you’ve had your fill of examining the font names, you can delete the trace(font.fontName); line from the constructor (line 74 in the listing above).
Step 35: Enable Text Styling
Now, what if you want to customize the caption field a bit? That’s a reasonable request, and we have a few options. One is that we could write setters and getters for the kinds of things we want to expose for external control. This might include things like enabling multiline, adjust the width, setting the text color, setting the align type, setting the font, and setting the font size. The good part of this approach is that it keeps things encapsulated and will probably make things easier for the programmer who is using this CoverFlow object. If all you need to do is write “coverFlow.fontSize = 16″ to make that one minor adjustment, then that’s about as easy as it gets. The downside is that we need to pick and choose what is exposed, and the more control we offer the more code we have to write in CoverFlow to accommodate that.
Another approach is to simply expose the TextField as a (read-only) property of CoverFlow. This has basically the opposite pro/con thing as the first option. It’s easy for us to implement right now, and affords total control to the end user; if you can do it to a TextField, you can do it the CoverFlow caption. However, relinquishing too much control might have disastrous effects. Most people wouldn’t bother really touching it, but accidents happen. Worse, though (in my opinion) is that in order to set the font size of the caption, you end up with a rather verbose (and entirely hypothetical, mind you):
var format:TextFormat = coverFlow.captionField.defaultTextFormat;
format.fontSize = 16;
coverFlow.captionField.defaultTextFormat = format;
Not to mention that there’s a difference between defaultTextFormat at setTextFormat(), and you’d better be familiar with which one to use in this scenario.
So which one is better? In an ideal world, I’d have to vote for the encapsulation method where pretty much every possible option is accounted for. However, for the purposes of this tutorial, that’s a lot of repetitive code. So, in the interest of trying to demonstrate this technique, yet still allow extensive customization, I’ll implement three properties for text styling, along with simply exposing the TextField for more detailed styling, which, as it happens, is option number three.
If you like the idea of encapsulation and want to eschew the revealing of the TextField to external objects, then the following will act as a guide for how to write more setters.
We will add properties to set and get the font name, the font size, and the font color. Also, we’ll add a getter (no setter) for the captionField. The styling properties will require a rendering deferment like the layout properties did, as well as attention paid to how to apply TextFormat objects. To start things off, declare a property to hold the TextFormat object:
private var _captionFormat:TextFormat;
Next, we’ll create that object in the constructor when we set up the TextField:
[first-line: 73; highlight: [81,82,83]">
// ...
for each (var font:Font in fonts) {
trace(font.fontName);
if (font.fontName.search(/lucida.*grande/i) > -1) {
fontName = font.fontName;
break;
}
}
if (!fontName) fontName = "Verdana";
_captionFormat = new TextFormat(fontName, 12, 0xFFFFFF);
_captionFormat.align = TextFormatAlign.CENTER;
_captionField.defaultTextFormat = _captionFormat;
// ...
The above simply replaces the temporary “format” variable from before with this property.
Next we can add the setters and getters (I will put these after all of the other setters and getters we’ve added so far):
public function set fontName(name:String):void {
_captionFormat.font = name;
_captionField.defaultTextFormat = _captionFormat;
if (stage) stage.invalidate();
}
public function get fontName():String {
return _captionFormat.font;
}
public function set fontSize(size:Number):void {
_captionFormat.size = size;
_captionField.defaultTextFormat = _captionFormat;
if (stage) stage.invalidate();
}
public function get fontSize():Number {
return _captionFormat.size as Number;
}
public function set fontColor(color:uint):void {
_captionFormat.color = color;
_captionField.defaultTextFormat = _captionFormat;
if (stage) stage.invalidate();
}
public function get fontColor():uint {
return _captionFormat.color as uint;
}
They are all similar to each other, the only difference being the data types and the actual TextFormat properties we affect. Notice that we set the value on the TextFormat object, then reapply that object as the default format for the caption TextField. We do this because setting the defaultTextFormat makes a copy of the format object, so even though we’re changing our reference to this object, we lose the reference to the one that actually sets the styles. Long story short, we need to reset the defaultTextFormat whenever that changes.
However, this only sets the style for new text coming into the text field. To update the styles on the text already present in the field, we need to use setTextFormat(). This, though, presents a similar rendering issue as before. If we were to set all three of the styling properties at once, we don’t necessarily want to reapply the format three times in a row. So, instead, we call stage.invalidate(), which, as you recall, will ultimately fire off the RENDER event so we can change the display.
Now, here’s why we wanted a separate onRender method hooked up to the RENDER event, instead of just hooking up the layout method directly to it. The layout method will update the caption, however, since we’ve set a default text format, there’s no need to apply a text format each time layout is called. We only want to apply a text format to existing text, so we can keep it out of layout and put it in onRender:
private function onRender(e:Event):void {
layout();
_captionField.setTextFormat(_captionFormat);
}
Lastly, we need to expose the text field itself. Write one last getter:
public function get captionField():TextField {
return _captionField;
}
And to test all of this, we can update CoverFlowTest’s onCoverFlowLoaded method:
private function onCoverFlowLoaded(e:Event):void {
trace("Coverflow loaded and ready to go.");
coverFlow.horizontalSpacing = 100;
coverFlow.centerMargin = 75;
coverFlow.backRowDepth = 300;
coverFlow.backRowAngle = 75;
coverFlow.verticalOffset = 50;
coverFlow.fontName = "Courier";
coverFlow.fontSize = 24;
coverFlow.fontColor = 0xff0000;
}
Run it, and once the images all load and the layout changes, you’ll see the caption style change, as well. Feel free to remove these lines at this point.
Step 36: Vertical Position
You’ll have noticed that the caption doesn’t move with the Covers when they adjust their vertical offset.
As you know, we added a verticalOffset property a few steps back, and we added it to the default value of 250 when positioning our Cover objects. Where does that 250 come from? I pulled that number out of the air as something that works for now.
We can now apply a little logic the vertical positioning of the row. We can just lock it to the bottom with a predefined margin. So, in layout, take out the line that reads cover.y = 250; and replace it with:
cover.y = _background.height - 90 + _verticalOffset;
In the Apple CoverFlow, the bottom of the row of Covers is similarly locked to the bottom edge of the view, but they also resize the covers based on how tall the view is. We’ll skip that bit of logic, but it would be an interesting exercise if you have a fever that can only be cured by more CoverFlow once this tutorial is over.
However, we’re still not done with our logic. We’ll apply a text pixel margin between the bottom edge of the flow and the caption. So it stands to reason that we’ll want to move the caption field when running layout, in case the height has changed. Add this line after the loop in layout:
_captionField.y = _background.height - 80 + _verticalOffset;
For reference the whole method should look like this:
private function layout():void {
_selectedIndex = 4;
var len:uint = _covers.length;
var cover:Cover;
var distanceFromCenter:uint
for (var i:uint = 0; i < len; i++) {
cover = _covers[i];
if (i == _selectedIndex) {
cover.rotationY = 0;
cover.x = _background.width / 2;
cover.z = 0;
_coversContainer.setChildIndex(cover, _coversContainer.numChildren-1);
_captionField.text = cover.caption;
} else if (i < _selectedIndex) {
distanceFromCenter = _selectedIndex - i;
cover.rotationY = -_backRowAngle;
cover.x = ((_background.width / 2) - _centerMargin) - (distanceFromCenter * _horizontalSpacing);
cover.z = _backRowDepth;
_coversContainer.setChildIndex(cover, _coversContainer.numChildren - (distanceFromCenter + 1));
} else if (i > _selectedIndex) {
distanceFromCenter = i - _selectedIndex;
cover.rotationY = _backRowAngle;
cover.x = ((_background.width / 2) + _centerMargin) + (distanceFromCenter * _horizontalSpacing);
cover.z = _backRowDepth;
_coversContainer.setChildIndex(cover, _coversContainer.numChildren - (distanceFromCenter + 1));
}
cover.y = _background.height - 90 + _verticalOffset;
}
_captionField.y = _background.height - 80 + _verticalOffset;
}
But there is one remaining task. If the width or height get changed, we should call layout again. This will be as simple as making another call to stage.invalidate in the width and height setters.
override public function set width(num:Number):void {
_width = num;
_background.width = _width;
scrollRect = new Rectangle(0, 0, _width, _height);
if (stage) stage.invalidate();
}
override public function get width():Number {
return _width;
}
override public function set height(num:Number):void {
_height = num;
_background.height = _height;
scrollRect = new Rectangle(0, 0, _width, _height);
if (stage) stage.invalidate();
}
override public function get height():Number {
return _height;
}
To test this, go ahead and remove any other test code in onCoverFlowLoaded and add this line instead, in CoverFlowTest:
coverFlow.height -= 50;
This is important: if you don’t remove at least the coverFlow.verticalOffset = 50 line, you’ll actually negate the effects of the height change. To more easily see the height change, I’d suggest just removing the previous layout properties and caption styling, if you haven’t done so already.
Test the movie, and you should see the covers and caption draw as before, and in addition the entire view becomes shorter, whilst preserving the relative layout.
Step 37: Add Drop Off
For a more authentic CoverFlow look, we’ll add a bit of zazz to Cover to make it “drop off” the further it is from the center. It has the effect of an opacity change, but, as with the reflections, we can’t actually adjust the alpha, even though that’s easier. We’ll achieve the effect through a fairly simple technique, though: we’ll just use a color transform to “tint” the item to the background color.
Tinting with pure ActionScript involves a bit of math trickery. It’s a bit much to fully explain here, but here’s the code. Add a set dropOff method in Cover:
public function set dropOff(value:Number):void {
value = Math.max(0, Math.min(1, value));
var r:uint = _backgroundColor >> 16;
var g:uint = _backgroundColor >> 8 & 0xFF;
var b:uint = _backgroundColor & 0xFF;
var multiplier:Number = 1 - value;
var color:ColorTransform = new ColorTransform(multiplier, multiplier, multiplier, 1, r * value, g * value, b * value, 0);
this.transform.colorTransform = color;
}
In a nutshell, this code takes a numeric value from 0 to 1, and will turn that into an amount by which to apply the tint: 0 means no tint at all, 1 means a full solid color tint.
To do that, we’ll take the background color and break it into component values of red, green and blue. This uses bitwise operators, and if they’re foreign to you, then it’s your assignment to go read up about them. You can start with Wikipedia for a general overview, and move on to Colin Moock’s site and Adobe’s devnet article for ActionScript-specific discussions.
Creating the ColorTransform is another moderately complex topic that I will leave as a research project if you need it. These are the values required to create a tint effect to the chosen color at the desired strength. A nice discussion of this technique can be found at flashandmath.com. It’s worth noting that another option (also discussed in the flashandmath article) is to import the fl.motion.Color class, which extends ColorTransform, and use that instead of a ColorTransform object. The Color class affords a tinting convenience with a setTint method, which basically does for us the math we’re doing longhand here. I opted to show the nuts and bolts version, which therefore doesn’t require the components classes, which I consider a bonus (you won’t have fl.motion.Color available in a Flex project).
To test this, add a few lines (highlighted) to our layout method in CoverFlow:
private function layout():void {
_selectedIndex = 4;
var len:uint = _covers.length;
var cover:Cover;
var distanceFromCenter:uint
for (var i:uint = 0; i < len; i++) {
cover = _covers[i];
if (i == _selectedIndex) {
cover.rotationY = 0;
cover.x = _background.width / 2;
cover.z = 0;
_coversContainer.setChildIndex(cover, _coversContainer.numChildren-1);
_captionField.text = cover.caption;
} else if (i < _selectedIndex) {
distanceFromCenter = _selectedIndex - i;
cover.rotationY = -_backRowAngle;
cover.x = ((_background.width / 2) - _centerMargin) - (distanceFromCenter * _horizontalSpacing);
cover.z = _backRowDepth;
_coversContainer.setChildIndex(cover, _coversContainer.numChildren - (distanceFromCenter + 1));
cover.dropOff = distanceFromCenter / 10;
} else if (i > _selectedIndex) {
distanceFromCenter = i - _selectedIndex;
cover.rotationY = _backRowAngle;
cover.x = ((_background.width / 2) + _centerMargin) + (distanceFromCenter * _horizontalSpacing);
cover.z = _backRowDepth;
_coversContainer.setChildIndex(cover, _coversContainer.numChildren - (distanceFromCenter + 1));
cover.dropOff = distanceFromCenter / 10;
}
cover.y = _background.height - 90 + _verticalOffset;
}
_captionField.y = _background.height - 80 + _verticalOffset;
}
These two additional lines are same, and make sure that if a Cover is not the centered one, then it gets a tint applied. The further away from the center, the fuller the tint. Over the course of 10 Covers, they get progressively more tinted (darker, in the case of a black background), until the 10th one away is invisible, being fully tinted to the color of the background.
Go ahead and test, and you should see something like this:
Compare that to this image from before dropOff was applied:
I won’t go into details here, as I believe you should be able to work them out yourself by now, but the number 10 in the above drop off equation would be a good candidate for a property for customization. Treat it like the distanceFromCenter property and you’ll be set.
Step 38: Set the Current Index
We’ll start working towards an interactive piece that animates. To get that to work, we’ll need the ability to set the current index. This should be a public method, as another representation of the list might be present, and the two can work together to have synchronized selection. Think of how iTunes works, where selecting a song in the list below also focuses the appropriate item in the CoverFlow above.
First, in layout (of CoverFlow), remove the line that set the _selectedIndex for us. If you recall, that was just a temporary test.
private function layout():void {
//_selectedIndex = 4;
var len:uint = _covers.length;
var cover:Cover;
var distanceFromCenter:uint
for (var i:uint = 0; i < len; i++) {
// ...
While we already have a private property for _selectedIndex, we should add a setter and getter. Add the following to CoverFlow:
public function set selectedIndex(index:uint):void {
if (_covers.length == 0) {
_selectedIndex = index;
return;
}
_selectedIndex = Math.max(0, Math.min(index, _covers.length - 1));
if (stage) stage.invalidate();
}
public function get selectedIndex():uint {
return _selectedIndex;
}
The getter is typical, but the setter has some extra input-cleansing logic. First, if there is nothing in the _covers Vector, then we probably haven’t loaded our XML document yet, so just stash the value and stop here. Otherwise, we can make sure that the value isn’t out of range before storing it in _selectedIndex. And then we can ask the display to redraw with a stage.invalidate().
We can test by going to CoverFlowTest and setting the property after coverFlow is created.
public function CoverFlowTest() {
coverFlow = new CoverFlow(stage.stageWidth, stage.stageHeight);
addChild(coverFlow);
coverFlow.backgroundColor = 0x000000;
coverFlow.horizontalSpacing = 60;
coverFlow.centerMargin = 100;
coverFlow.load("coverFlowImages.xml");
coverFlow.addEventListener(Event.COMPLETE, onCoverFlowLoaded);
coverFlow.addEventListener(ProgressEvent.PROGRESS, onCoverFlowProgress);
coverFlow.selectedIndex = 8;
}
And you’ll see that we select that Cover.
Step 39: Click to Select
With the ability to select an Cover in place, we can easily add the expected click functionality. If you click on a Cover that’s on the side, it becomes the focused Cover.
We need to add an event listener to each Cover as we create them. Still in CoverFlow, add this line to the loop in onXMLLoad:
private function onXMLLoad(e:Event):void {
_xml = new XML(_urlLoader.data);
var imageList:XMLList = _xml.image;
var iLen:uint = imageList.length();
var imageNode:XML;
var cover:Cover;
for (var i:uint = 0; i < iLen; i++) {
imageNode = imageList[i];
var src:String = imageNode.@src;
var title:String = imageNode.@title;
cover = new Cover(title, imageNode, _backgroundColor);
cover.addEventListener(MouseEvent.CLICK, onCoverClick);
_coversContainer.addChild(cover);
_covers.push(cover);
}
layout();
_loadCounter = 0;
loadNextCover();
}
And then add the onCoverClick method.
private function onCoverClick(e:MouseEvent):void {
this.selectedIndex = _covers.indexOf(e.currentTarget);
}
It’s that simple. We know the index we want to select because we know the Cover that was clicked (through currentTarget). Vectors (and Arrays) provide the handy indexOf method so we can get the index of a given object in the Vector. We just need to feed that to our selectedIndex property, and now we have some rudimentary interactivity going.
Interact with this milestone SWF to test it out.

Click to view the milestone demo.
Step 40: Add a Tween: The CoverFlow Object
But to make the CoverFlow really, well, flow, we need to tween the Covers from one position to another. This is, of course, the pièce de résistance and possibly why you’re here in the first place. Getting this together will mean some significant updates to our code, but they’ll be worth it.
You might think we’ll be best off using a third-party tweening package. And while it would be easier in some respects, we have a lot of custom things to update as our Covers animate. We’ll actually roll our own tweens, which isn’t as bad as you probably think it is.
This is, however, going to be a marathon of a step, so hang in there.
First, in CoverFlow, we need to add a few more properties. At the top of the class, along with the rest of the properties, declare the following:
private var _tweenDuration:int = 1200;
private var _startTime:int;
private var _elapsed:int;
private var _coversLength:uint;
private var _iteration:uint
private var _iterationCover:Cover;
private var _sortedCovers:Vector.<Cover>;
private var _unitsFromCenter:uint;
private var _distanceA:Number;
private var _distanceB:Number;
Yes, that’s quite a few. Here’s a quick description of what they’ll do:
_tweenDuration: How long, in milliseconds, the animation should last.
_startTime: Each time the animation starts, we’ll store the result of getTimer() in this property.
_elapsed: Each time we update the animation, we’ll store the time that has elapsed since the start of the tween here.
_coversLength: The number of items in the _covers Vector.
_iteration: The “i” variable in our loops.
_iterationCover: A property to store an individual Cover object as we iterate over _covers.
_sortedCovers: A duplicated and then sorted version of the _covers Vector. We’ll use it to sort depths.
_unitsFromCenter: How far, in number-of-covers, a given Cover object is from the center position.
_distanceA and _distanceB: Used in the depth sorting function, holds the distance from center (in pixels) of any two given Cover objects.
Note that in most cases, we’re only declaring a property for optimization purposes. We’re about to write a bunch of methods that get called repeatedly, several times a frame, so we’re trying to minimize the overhead of variable declaration by declaring them once for the object, then reusing the slot each time we need the variable.
Next, we’ll modify the set selectedIndex method to remove the stage.invalidate() line, and add in the following lines that kick off the animation:
public function set selectedIndex(index:uint):void {
if (_covers.length == 0) {
_selectedIndex = index;
return;
}
_selectedIndex = Math.max(0, Math.min(index, _covers.length - 1));
// if (stage) stage.invalidate();
_startTime = getTimer();
determineLayout(_selectedIndex);
removeEventListener(Event.ENTER_FRAME, animate);
addEventListener(Event.ENTER_FRAME, animate);
}
Here we set the _startTime property using getTimer(), which returns the number of milliseconds since the Flash movie started playing. We call a new layout function, using the _selectedIndex, and finally set up an ENTER_FRAME listener. Notice we also remove the event listener before adding it, in case an animation is still in effect when another one needs to start.
We’ll write that determineLayout method next; it can go anywhere in the class that makes sense.
private function determineLayout(destinationIndex:uint):void {
_coversLength = _covers.length;
for (var i:uint = 0; i < _coversLength; i++) {
_iterationCover = _covers[i];
if (i == destinationIndex) {
_iterationCover.endRotationY = 0;
_iterationCover.endX = _background.width / 2;
_iterationCover.endZ = 0;
_captionField.text = _iterationCover.caption;
} else if (i < destinationIndex) {
_unitsFromCenter = destinationIndex - i;
_iterationCover.endRotationY = -_backRowAngle;
_iterationCover.endX = ((_background.width / 2) - _centerMargin) - (_unitsFromCenter * _horizontalSpacing);
_iterationCover.endZ = _backRowDepth;
} else if (i > destinationIndex) {
_unitsFromCenter = i - destinationIndex;
_iterationCover.endRotationY = _backRowAngle;
_iterationCover.endX = ((_background.width / 2) + _centerMargin) + (_unitsFromCenter * _horizontalSpacing);
_iterationCover.endZ = _backRowDepth;
}
}
}
Notice that this is very similar to our layout() method, only we seem to be setting properties on the Cover objects that don’t exist…yet. What we’re trying to do is figure out our destination values based on the new selection. We’ll then use that to interpolate our position as the tween progresses. Other than that, and the fact that we’ve stripped out a few things like dropOff and _captionField positioning, it’s the same logic as layout().
Now let’s write the animate method, the ENTER_FRAME listener.
private function animate(e:Event):void {
_elapsed = getTimer() - _startTime;
if (_elapsed > _tweenDuration) {
removeEventListener(Event.ENTER_FRAME, animate);
return;
}
for (_iteration = 0; _iteration < _coversLength; _iteration++) {
_iterationCover = _covers[_iteration];
_iterationCover.updateTween(_elapsed, _tweenDuration);
}
_sortedCovers = _covers.concat();
_sortedCovers = _sortedCovers.sort(depthSort);
for (_iteration = 0; _iteration < _coversLength; _iteration++) {
_iterationCover = _sortedCovers[_iteration];
_coversContainer.setChildIndex(_iterationCover, _coversContainer.numChildren-(_iteration+1));
}
}
Here we get into some of the nuts and bolts of programmatic tweens. First, we find the time that has elapsed since the tween began. If that’s longer than the tween duration, then we need to stop the tween (by removing the event listener). Otherwise, we continue on, and loop over the Cover objects. On each one, we call a (as of yet to be written) method that will actually perform the visual updates based on our progression through the tween.
The second half of the method is given to depth sorting. This gets a bit trickier than it does in plain old layout(), as we can’t rely on covers being in any position at any time. Instead, we’ll sort the Vector of Covers, using the sort method provided by Vectors (and Arrays). The parameter passed into this method is a function reference, so depthSort is something we need to write yet. Note also that we need to copy the Vector, otherwise we end up messing with the order of Covers from left to right, and that’s not good.
Once the Vector is sorted, though, we can loop over it and set the depths of the Covers rather easily.
Next, we’ll write the depthSort sorting function:
private function depthSort(a:Cover, b:Cover):Number {
var _distanceA:Number = Math.abs(a.x - _background.width/2);
var _distanceB:Number = Math.abs(b.x - _background.width/2);
if (_distanceA < _distanceB) { return -1;}
if (_distanceA > _distanceB) { return 1; }
return 0;
}
The idea behind sorting methods is that they receive two objects from the Vector being sorted, and need to return a value that tells the Vector how to sort those two items. If the return value is negative, then the object passed into the first parameter goes first. If the return is positive, then the second parameter goes first. If the return is 0, then no change is made.
Our sorting logic involves comparing the absolute distance from the center. Basically, the further away from the center, the further back we want it to set.
That’s it for changes to CoverFlow, but we have some work to do in Cover now. As such, don’t bother testing the movie now as you will get compiler errors.
Step 41: Add a Tween: The Cover Objects
In the Cover class, lets start by declaring a bunch of properties.
private var _startX:Number;
private var _endX:Number;
private var _startRotationY:Number;
private var _endRotationY:Number;
private var _startZ:Number;
private var _endZ:Number;
private var _coverFlowParent:CoverFlow;
private var _centerMargin:Number;
private var _distanceFromCenter:Number;
Here’s what these will do:
_startX, _startRotationY, _startZ: Stores the current values of x, rotationY, and z at the time a tween starts.
_endX, _endRotationY, _endZ: Stores the calculated ending values of x, rotationY, and z when the tween ends.
_coverFlowParent: Stores a reference to the CoverFlow that contains this Cover.
_centerMargin: Stores the value of CoverFlow.centerMargin.
_distanceFromCenter: The calculated distance from the center of the CoverFlow.
Next, we’ll write the setters for endX, endRotationY, and endZ.
internal function set endX(n:Number):void {
_startX = this.x;
_endX = n;
}
internal function set endRotationY(n:Number):void {
_startRotationY = this.rotationY;
_endRotationY = n;
}
internal function set endZ(n:Number):void {
_startZ = this.z;
_endZ = n;
}
These are typical setters, except that they also store the current value of the related property. We’ll need that value to update the property as we tween, so we may as well store it whenever we get an instruction also store our calculated ending value. They are also unusual in that they aren’t public, they’re internal. This just restricts access to objects from the same package, so it’s a little more protected than public, but still let’s the CoverFlow object set them. I also didn’t bother writing corresponding getters. We don’t need them, but there is no harm in doing so if you like.
We need to write that updateTween method next. This will be where we actually update the position and rotation:
internal function updateTween(elapsedTime:Number, duration:Number):void {
this.x = ExponentialEaseOut(elapsedTime, _startX, _endX - _startX, duration);
this.rotationY = ExponentialEaseOut(elapsedTime, _startRotationY, _endRotationY - _startRotationY, duration);
this.z = ExponentialEaseOut(elapsedTime, _startZ, _endZ - _startZ, duration);
if (!_coverFlowParent) _coverFlowParent = this.parent.parent as CoverFlow;
_distanceFromCenter = Math.abs(this.x - (_coverFlowParent.width / 2));
_centerMargin = _coverFlowParent.centerMargin;
if (_distanceFromCenter < _centerMargin) {
this.dropOff = .1 * _distanceFromCenter / _centerMargin;
} else {
this.dropOff = .1 + ((_distanceFromCenter - _centerMargin) / _coverFlowParent.horizontalSpacing) * .1;
}
}
The first three lines rely on a the easing equation we still need to write. Let’s pop that in now:
private static function ExponentialEaseOut(t:Number, b:Number, c:Number, d:Number):Number {
return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
}
I got this from Penner’s easing equations, which are released under a BSD license. As such, we need to make sure to also include the copyright notice:
/*
TERMS OF USE - EASING EQUATIONS
Open source under the BSD License.
Copyright © 2001 Robert Penner
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of the author nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
You can find out more about these equations on Robert Penner’s site.
So, in combination, what does this do? The easing equations are all set up to take four arguments: the elapsed time of the tween, the start value of the property being tweened, the distance to be traveled over the course of the entire tween, and finally the duration of the entire tween. They return a number: the interpolated value of based on the input values and the underlying equation. Beyond that, I’d be hard pressed to tell you how they work. Just be thankful Penner released these equations as open source.
Why not use the easing classes as they are? Well, this way, we don’t have to worry about distributing a third-party class with the CoverFlow package. Everything is self contained. It’ll be that much tidier.
To sum up, we set the current x, rotationY, and z based on the time through the tween and this equation.
After that, it’s all about setting the drop off. We first make sure we have a reference to the CoverFlow parent. Then we figure out how far we are from the center. Then we figure out what the dropOff should be based on that value. This math gets a little hairy, but essentially we’re interpolating the value based on the fact that if a Cover is at a final destination, it’s going to have a drop off of 10% or 30% or 80%, or some multiple of 10 percent. The idea is to figure out how close we are to one of those positions.
Step 42: Resizing on the Fly
We have something we need to, but the need for it isn’t quite apparent. By adding a fullscreen type of resizing, we can both test the ability to resize the CoverFlow on the fly, and reveal a bit of strange behavior that needs addressed.
This all happens in CoverFlowTest.as. In the constructor, add these lines at the end:
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
stage.addEventListener(Event.RESIZE, onResize)
And then add the onResize event listener:
private function onResize(e:Event):void {
coverFlow.width = stage.stageWidth;
coverFlow.height = stage.stageHeight;
}
These few lines are pretty standard fare for creating a SWF that resizes fluidly with the resizing of the Player. Within Apple’s products, we see a CoverFlow view within a larger window, but it can be resized, e.g. by resizing the window or by dragging the bottom edge of the CoverFlow to resize it within the window. Basically, we’re simulating this ability.
You’ll probably notice that Apple’s CoverFlow resizes the images as you resize the CoverFlow view. This is something that we won’t be recreating, but feel free to have a go yourself.
Step 43: Correcting the Perspective
As you resize the window and move the covers around, you may notice something else rather strange that definitely needs to be taken care of. If you stretch the window rather wide, you should see that the images line up correctly, but they appear to be skewed rather stangely. This is that “not quite apparent” thing we needed to take care of.
Why does this happen? Well, by default, Flash 10′s 3D rendering happens through a single “camera,” and that camera is in a fixed location, at the center of the stage. However, that camera doesn’t move if you resize the stage. So while you expect the vanishing point to remain in the center of your CoverFlow rectangle, no matter how big, Flash set up the vanishing point to a certain point based on the original rectangle of the stage, and then leaves it there.
Fortunately we can work it out. There is something call a PerspectiveProjection object on the root display object of any Flash Movie. You can think of this as the virtual camera through which we view the 3D rendering. And naturally, we can move it around (If you’re coming from a Papervision3D or Away3D mode of thinking, this isn’t a camera is the sense you have cameras in those packages. Don’t get too excited; it’s rather limited).
But if we start moving it around, we may be affecting the 3D projection of other 3D elements in the Flash Movie, not just our CoverFlow. Well, fortunately, every DisplayObject has a PerspectiveProjection object, which is off by default. But if we turn it on, then that DisplayObject’s child objects will render according to that PerspectiveProjection, not the root one. Thus, we can set up an independent vanishing point for our CoverFlow without worrying about how it will affect other 3D rendering in the movie.
To do this, go back to CoverFlow and find a spot in the constructor to set it up. I’ve added some lines right after setting up the scrollRect:
// ...
_background = new Shape();
addChildAt(_background, 0);
drawBackground();
scrollRect = new Rectangle(0, 0, _width, _height);
this.transform.perspectiveProjection = new PerspectiveProjection()
this.transform.perspectiveProjection.projectionCenter = new Point(_width/2, _height-190);
_urlLoader = new URLLoader();
_urlLoader.addEventListener(Event.COMPLETE, onXMLLoad);
// ...
First we have to create the PerspectiveProjection object on the CoverFlow display object. Then we set up the projectionCenter property to a new Point. The key is that the we set this property to a Point. We can’t set the x and y of the Point directly, for some reason. So we create a Point and the x is set to half of the width of our CoverFlow.
So that sets it up correctly the first time (which, by the way, would help if the CoverFlow weren’t as wide as the stage to begin with). Next, we need to revisit the width and height setters and update the projectionCenter with new values:
override public function set width(num:Number):void {
_width = num;
_background.width = _width;
scrollRect = new Rectangle(0, 0, _width, _height);
this.transform.perspectiveProjection.projectionCenter = new Point(_width/2, _height-190);
stage.invalidate();
}
override public function set height(num:Number):void {
_height = num;
_background.height = _height;
scrollRect = new Rectangle(0, 0, _width, _height);
this.transform.perspectiveProjection.projectionCenter = new Point(_width/2, _height-190);
stage.invalidate();
}
Now, whenever the dimensions of the CoverFlow instance are changed, so is the vanishing point. Go ahead and try it; if you run the movie and resize the stage, you should see good behavior from the 3D rendering, no matter how you size it.
Step 44: Center the Caption
Things are looking pretty sweet, but you’ll probably have noticed that – as you resize the stage – the caption moves vertically with the covers, but not horizontally. This is, fortunately, a rather easy fix. In CoverFlow‘s layout method, we need to update the _captionField‘s x property.
private function layout():void {
var len:uint = _covers.length;
var cover:Cover;
var distanceFromCenter:uint
for (var i:uint = 0; i < len; i++) {
// ...
}
_captionField.x = (_background.width - _captionField.width) / 2;
_captionField.y = _background.height - 80 + _verticalOffset;
}
This just makes sure the TextField is centered within the CoverFlow object.
Step 45: Enable Double Clicks on the Cover
Almost done. We now would like to enable the ability to click on the frontmost cover and dispatch an event. Also, we’d like to be able to retrieve a given Cover’s data XML, as supplied by the original XML document.
We’ll start with the cover. First, we enable double-click action in Cover, in the constructor:
public function Cover(caption:String, data:XML, backgroundColor:Number) {
_caption = caption;
_data = data;
_backgroundColor = backgroundColor;
this.doubleClickEnabled = true;
this.mouseChildren = false;
}
These two new lines simply enable the ability to receive double-clicks from the user. The mouseChildren line doesn’t necessarily enable double-clicks, but it is necessary in our case, otherwise the Loader will sort of intercept the double-clicks.
Step 46: Do Something With Double Clicks in the Test Class
To listen for double-clicks, head back to CoverFlowTest and listen for the DOUBLE_CLICK event. Due to event bubbling, an event dispatched by a Cover object will be listenable from CoverFlowTest:
public function CoverFlowTest() {
coverFlow = new CoverFlow(stage.stageWidth, stage.stageHeight);
addChild(coverFlow);
coverFlow.backgroundColor = 0x000000;
coverFlow.horizontalSpacing = 60;
coverFlow.centerMargin = 100;
coverFlow.load("coverFlowImages.xml");
coverFlow.addEventListener(Event.COMPLETE, onCoverFlowLoaded);
coverFlow.addEventListener(ProgressEvent.PROGRESS, onCoverFlowProgress);
coverFlow.addEventListener(MouseEvent.DOUBLE_CLICK, onCoverFlowDoubleClick);
coverFlow.selectedIndex = 8;
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
stage.addEventListener(Event.RESIZE, onResize)
}
After adding the event listener, we need to write it:
private function onCoverFlowDoubleClick(e:MouseEvent):void {
trace("onCoverFlowDoubleClick: " + e.target.data);
}
Note that e.target will be the Cover object that was double-clicked. This gives us easy access to the data that is stored within the Cover object in question. In this particular case, we have a nested <link> node (remember, data is just the XML node for that Cover object – and we can put anything we want inside that node). So if you run the movie as it stands now, you’ll see the entire XML node in the Output panel. If we want to do something more meaningful, we can do this:
private function onCoverFlowDoubleClick(e:MouseEvent):void {
navigateToURL(new URLRequest(e.target.data.link));
}
Remember that you can store any information you want in the XML, and access it on a node-by-node basis through the data property of the individual Cover. There’s more information on that in my XML tutorial.
Step 47: One Last Thing…
You may have forgotten, but I haven’t. We stubbed in a clearContents() method a while back, but never filled it in. Well, now that we’re all but done, we can fill it in. The purpose of this method is just to preserve the CoverFlow instance and its layout and style settings, and to remove the Covers and any associated data. This would also be a place to ensure that we’ve cleaned up any stray event listeners. Then the CoverFlow object could load a different XML file and start again with new data. Locate that empty clearContents() method in CoverFlow and add the following:
private function clearContents():void {
for each (var cover:Cover in _covers) {
cover.removeEventListener(Event.COMPLETE, onCoverLoad);
cover.removeEventListener(ProgressEvent.PROGRESS, onCoverProgress);
cover.addEventListener(MouseEvent.CLICK, onCoverClick);
this.removeChild(cover);
}
_covers = new Vector.<Cover>();
this.removeEventListener(Event.ENTER_FRAME, animate);
}
I’m being a bit overly cautious, but I just want to make sure that any event that was ever hooked up is cleared away. At the end of the function, though, individual Cover objects are cleaned up, removed from the display, and ultimately deleted, along with the ENTER_FRAME handler, in case we happened to call this in the middle of an animation. Let’s test it out, by adding some code to CoverFlowTest:
private function onCoverFlowLoaded(e:Event):void {
trace("Coverflow loaded and ready to go.");
setTimeout(coverFlow.load, 1000, "coverFlowImages.xml");
}
This is a rather pointless test, but an easy one to execute. It just waits one second after the CoverFlow loads, then loads the XML file again. This actually enters an endless sequence, but it should show that the clearContents() method does the trick.
Quittin’ Time
This was not a small project. Depending on your experience with Flash and ActionScript, you probably learned a thing or two, aside from how to recreate the CoverFlow view in Flash. Some of the more advanced topics included BitmapData, manual tweening, 3D depth sorting and 3D perspective management.
Thanks for sticking with me until the end. I hope I’ve shown you that with a little elbow grease, you can create compelling 3D content in Flash 10 without the need for a 3rd party package to handle the 3D rendering. Flash 10 native 3D isn’t suitable for everything, but for certain projects, it’s often much easier to work with, not to mention much smaller in terms of file size of the SWF.



View full post on Activetuts+
Jun 29, 2012
Posted on Jun 29, 2012 in Hints and Tips | 10 comments
In this tutorial, I’ll introduce you to Dart and how to start using it. In the course of the article we’ll build a simple JavaScript-based image marquee without writing a single line of JavaScript – just Dart.
Note: This tutorial was originally published in March 2012, as a freebie for our Facebook fans.
Project Preview
We will be building the following simple marquee, a screenshot of which is shown below. Click on the image to launch a working example of the project.
Step 1: Install the Dart Editor
Let’s get started building out little marquee. From here on out, we’ll be much more hands-on, and I’ll take the time explain the new stuff along the way.
First things first; we can write Dart in any old text editor, really, but the most convenient way to get started and to immediately run your project in a browser (via JavaScript compilation) is to install the Dart Editor.
Head to http://www.dartlang.org/docs/getting-started/editor/, which should automatically detect your OS and present you with the appropriate download link. It’s not a small download, around 65 MB at this writing, so get it started before continuing to read.
The Dart Editor is rather bare-bones. It’s built on Eclipse, and I hope that eventually it will be offered as an Eclipse plug-in for those with an existing Eclipse installation. But for now, it’s a self-contained Eclipse modification that does Dart and not much else.
It offers a few of the features that Eclipse workspaces typically offer, such as language-aware completion. The big advantage it brings, though, is a fairly simple way to start and run a Dart project.
Once the download completes, extract the ZIP file and you’ll have a dart folder. You can place this wherever you like; I’ve moved mine to my Applications folder.
Step 2: Create a Dart Project
Let’s open up the Dart Editor application. You’ll find it just inside that dart folder you just unzipped.
Once it launches, you’ll be presented with a “Welcome” page, which provides a jumping-off point to some sample projects. These are certainly worth taking a look, but we’ll skip past them for now and first get a little more familiar with the language.
Go to the File menu and choose New Application… or click on the top-left icon in the toolbar:
In the resulting window, enter a name for the project (I’m using DartMarquee). It will want to store the project in a folder named dart in your home directory, but you can change that by clicking on the Browse… button. Note that whichever folder you choose, Dart Editor will create a new folder in the selected folder, using the name you’ve given for the project. Inside of that there will be a few files created for you, also using the name of the project you supplied.
Also be sure the “Web Application” is selected, not “Server Application.”
Step 3: Run the Hello World Example
The default project created for you is a simple Hello World example. You may as well see what happens before we start building our (slightly) more complicated project. Run the application by either choosing Tools > Run from the menu, pressing Command-R (Mac) or Control-R (PC), or by clicking on the green “play” button in the tool bar:
You may expect this open up in your default browser, but – surprise! – Google’s Chromium browser will open (not to be confused with Chrome; Chromium has a blue-ish monochrome icon, not Chrome’s colorful icon). Chromium has built-in support the the Dart language.
This is not the process I mentioned earlier where Dart files are compiled into JavaScript; this is the Dart VM running regular Dart code, which is cool, but not terribly useful for those of us currently building JavaScript applications. We’ll make the project compile to JavaScript next.
Step 4: Add a JavaScript Launch
If you change the run settings, then we can get Dart to compile to JavaScript. To change these settings, choose the Tools > Manage Launches… menu, press Command-Shift-M (Mac) or Control-Shift-M (PC), or click and hold the downward arrow next to the Run tool bar button, and choose Manage Launches… from the pop-up menu.
In the window that appears, you’ll see the default launch created for you, which has the Chromium icon. To create a new launch, click on the new document icon, which will display a pop-up menu.
Choose Dart Web Launch from the menu. In the top field at the right, give it a meaningful name, like DartMarquee JS or something to designate that we’re going for a JavaScript rendition in another browser.
Under Launch Target, click Browse… next to HTML file:. A window will open that presents all (one) HTML files present in your project. Click on DartMarquee.html and then click OK.
Under Browser you can choose to leave the default checked, or uncheck that option and then specify a browser with the Select… button. The browser choice shouldn’t matter too much, although I will be using some CSS3 tricks so a modern browser would be ideal.
Click Apply and then Close.
Now run the project again, but this time be sure to do it by clicking and holding on the Run tool bar button, and then selecting your new launch target. You should now get the same Hello World application in the browser of your choosing, which will be using JavaScript compiled from Dart. In fact, you’ll see a new file show up in your file list: DartMarquee.dart.js. This is the compiled JavaScript file.
Now that you’ve run the new launch once, future Runs will remember this decision and launch the JavaScript version.
But we’re not done yet. The HTML file is set up to include the Dart file, along with another JavaScript file that interprets Dart files in the browser (which is super-cool, but not the best for production applications). We need to edit the HTML file to use the compiled JavaScript file, not the Dart files.
Step 5: The HTML
Your new project should open with DartMaquee.dart in the main editor area. We’ll get to that soon enough, but let’s get our HTML page set up. Double-click on DartMarquee.html in the file list on the left, and it will open in a new tab in the editor.
Dart Editor is really only aware of the Dart language, which is too bad. You’ll notice that the HTML file opens without any syntax coloring or intelligence about the language. It’s good enough for our purposes now, but feel free to open this file (and any other non-Dart file) in the text editor of your choosing. We won’t be spending too much time in non-Dart files, so I’ll just be editing them in Dart Editor for this tutorial.
The body markup is not what we want, but first let’s update those <script> tags as mentioned in the last step. You can delete the first <script> tag altogether; that’s the once that includes the Dart file directly. Delete this line:
<script src="http://dart.googlecode.com/svn/branches/bleeding_edge/dart/client/dart.js"></script>
(Hint: line numbers aren’t enabled by default, but that’s one of the few options available under Preferences).
The script is the in-browser runtime for Dart; one pretty nifty feature is that you can write Dart without compiling it to JavaScript, and have browsers run it anyway. You just need to include dart.js. Of course, this makes for some extra overhead and impacts performance. Pretty cool trick, though.
Now let’s change the remaining <script> tag to load our compiled JavaScript file. Change this:
<script type="application/dart" src="DartMarquee.dart"></script>
To this:
<script src="DartMarquee.dart.js"></script>
If you like, run the project again, and use the developer tool to ensure that the JavaScript file is loading, and the other two are not.
Now, change that <h2> tag into a <div>, and give it an id of marquee.
<div id="marquee"></div>
You can leave the <h1> if you like; sometimes it’s nice to have page identification.
Finally, we need to link to a CSS file (which we’ll create in the next step). In the <head> add a <link> tag:
<link rel="stylesheet" href="DartMarquee.css">
The application will not work, because we’ve removed the <h2> that was targeted by the Dart code, not to mention that we still need a CSS file. Let’s do that next.
Step 6: The CSS
We’ve linked to a non-existent CSS file, so let’s address that. In the Files area of Dart Editor, right-click, and choose New File: from the menu (you can also find New File… in the File menu).
In the resulting window, you may need to ensure that the DartMarquee project is selected in the middle area. Then enter DartMarquee.css for the file name, and click on Finish.
This file will be ready to edit in the main editor area, but as with HTML files, CSS files aren’t intelligently supported with syntax by Dart Editor. Feel free to do your CSS editing in your preferred text editor. Or, since we’re really not here to delve into the CSS, just copy and paste form below into Dart Editor:
#marquee {
width: 600px;
height: 400px;
background-color: #111;
}
.mainImage {
height: 300px;
background-color: #666;
position: relative;
}
.mainImage img {
display: block;
position:absolute;
left: 0px;
top: 0px;
-webkit-transition: opacity 0.6s ease-out;
-moz-transition: opacity 0.6s ease-out;
-ms-transition: opacity 0.6s ease-out;
-o-transition: opacity 0.6s ease-out;
transition: opacity 0.6s ease-out;
}
.mainImage img.fade_away {
opacity: 0;
}
.thumbContainer {
height: 100px;
background-color: #DDD;
}
.button {
width: 100px;
height: 100px;
background-color: #eee;
position: relative;
float: left;
}
.button .border {
width: 90px;
height: 90px;
position: absolute;
opacity: 0;
border: 5px solid orange;
-webkit-transition: opacity 0.3s ease-out;
-moz-transition: opacity 0.3s ease-out;
-ms-transition: opacity 0.3s ease-out;
-o-transition: opacity 0.3s ease-out;
transition: opacity 0.3s ease-out;
cursor: pointer;
}
.button:hover .border {
opacity: .5;
}
.button.selected .border {
opacity: 1;
}
Again, we’re not here to discuss CSS. I’ll point out that I’m using CSS3 transitions for the button hovers and the main image changes. Otherwise, it should be fairly straightforward.
Run the project one more time, or simply reload from the browser; at this point there won’t be any JavaScript to re-compile. If you run from Dart Editor, be sure to switch back to the HTML or Dart file; Dart Editor doesn’t know what to do when you “Run” from a CSS file.
You should see a large dark rectangle. Doesn’t look like much yet, but you’re on the right tack.
Step 7: Preparing the Images
One more housekeeping task, and that’s to make our images readily accessible, so that we can see them when we’re ready to write that code.
In the download package, you’ll find a folder named images. Copy or move this folder from the download archive to your project folder, so that’s sitting at the same level as your other files. You’ll probably need to use the Finder/Explorer for this task, as Dart Editor doesn’t (yet) support importing or drag-and-drop of existing files. They’ll show up in your file list once you get them in place, though.
Now we can get into some Dart code. That’s next!
Step 8: The main() Function
Open up the DartMarquee.dart file in the editor. You’ll see three main blocks of code:
The third block is the main function, and this is a required part of your Dart project. Dart will look for this function as an entry point to execution. Contrast this with JavaScript where scripts are simply executed from top to bottom. You can certainly replicate this methodology in JavaScript, but the key difference is that you don’t have to, and if you do you have to call main() yourself; in Dart, it’s expected that you have the main function, as it will be called for you once Dart in ready to begin execution of your application.
This won’t be a foreign concept to you if you’ve programmed in C or Java, or even in ActionScript 3 and used the Document class. The nice thing about it is that there is a standardized, expected place to begin the execution of your code.
Step 9: Classes
Dart brings with it proper classes, which you may end up preferring to JavaScript’s class-ish-ness prototype system. Take a look at the second block of code in DartMarquee.dart. This is the meat of the program right now, and is a class with two methods declared. We’ll be ditching a large part of this code. We’ll get into the syntax as we go, but for now, hollow out this class so that it looks like this:
class DartMarquee {
DartMarquee() {
}
}
What this leaves is the class declaration and the constructor. The class declaration begins with class, which is followed by the name of the class. That this class is named DartMarquee is purely a function of the template used in the application creation process in DartEditor. It’s important to know that just because this file is named “DartMarquee.dart” does not mean that there has to be a class name DartMarquee inside. We’re not going to change it, because it makes sense, but Dart is like PHP or Ruby in that you can put as many class definitions as you like in a single file, and the naming doesn’t need to match the file name (as it does in ActionScript).
The class definition is then contained between the curly braces. Inside of that, we have a constructor. This is a function that is run when a new object is instantiated from this class. Typically one puts set-up code in a constructor. Note that the name of the constructor needs to match the name of the class, otherwise it’s not a constructor, and is a regular method instead.
Everything else you add to a class should go in between the two curly braces denoting the class.
You’ll notice that back in the main function, a DartMarquee object is instantiate with this line:
new DartMarquee().run();
This should look like object-oriented JavaScript. The .run() then calls the run method on the newly-created object. We just removed that method, so go ahead and change that line to this:
new DartMarquee();
Step 10: Imports
Something I’m pretty excited about with Dart, as someone coming from JavaScript, is the ability to easily import and use other code into your project. The first block of our default code uses a single import statement:
#import('dart:html');
This imports a built-in Dart library, one that deals specifically with HTML pages and giving us access to DOM manipulation functionality. We’ll be importing other libraries as we need them, including one that we’ll write ourselves.
When our Dart project is compiled to JavaScript, all of the disparate Dart code is converted and concatenated into a single JavaScript file. It’s smart enough to not include the same library twice, so you can import libraries from other files and not worry about them conflicting with or duplicating code in the final product.
Our DartMarquee.dart file should look something like this now:
#import('dart:html');
class DartMarquee {
DartMarquee() {
}
}
function main() {
new DartMarquee();
}
Step 11: Add a Property to the Class
Let’s finally write code. We’re going to add a target property to the DartMarquee class, so that the main HTML element that we’re referencing is handy within the class.
Just after the class declaration, and before the constructor, add a property like so:
class DartMarquee {
Element _target;
DartMarquee() {
}
}
Notice the syntax here: instead of var, we use a datatype to both declare a variable and give it a datatype all at once. This syntax is reminiscent of C and Java. The name of our property is _target, and the line ends with a semi-colon. You’ll find Dart much less forgiving about missing semi-colons.
An interesting thing about Dart type system is that it’s optional. If you specify a type, Dart will do what it can to adhere to typing rules. But we could also opt to leave typing off by writing that property like this:
var _target;
Dart will then not attempt to keep your types safe; you’ll have a dynamically-typed variable just like in JavaScript. What’s even more interesting than the fact that it’s optional is that you can mix strong and dynamic typing in the same code.
Personally, strong typing is one of the things that draws me to Dart, as it’s helpful to have that kind of accountability. This will be the last time I mention dynamic typing in Dart.
We’re not done with that property yet. This is an important property, so let’s set it in the constructor.
class DartMarquee {
Element _target;
DartMarquee(this._target) {
}
}
This may look a little unexpected. This is a Dart idiom; it’s so common for a constructor to receive arguments, and then simply use the constructor’s body to stash those values into properties, that Google created a shortcut.
Normally, a method parameter looks like you’d expect it to: any variable name will do, but not something that looks like a property on another object. These parameters are normal parameters like you’re used to; they’re available by name within the body of the method.
This new syntax, however, will go ahead and assign the value passed in to this parameter to the property designated by the parameter name. In other words, the code above is identical to this code:
DartMarquee(target) {
this._target = target;
}
Only we don’t have to write that boilerplate of a line.
Note that this shortcut is only available in constructors.
Step 12: DOM Queries
Now that we have a target property set up, we need to give it a value. Back in the main function, we need to select the marquee <div> and pass it in to the constructor.
Dart provides a method to find HTML elements by CSS selection, much like jQuery or any of the popular JavaScript libraries do. This is provided by that dart:html library imported at the top of the file, which also provides a top-level document variable which gives us global access to the HTML document.
Update the main function to look like this:
void main() {
new DartMarquee(document.query('#marquee'));
}
It’s that simple: if you’ve used jQuery (or another library), this should be rather familiar. Simply call document.query and pass in the selector. Dart does the rest.
Step 13: Console Logging
If you’ve developed with JavaScript, chances are you’ve made heavy use of console.log to test and verify your code. Dart provides a print function that, when compiled to JavaScript, turns in to a call to console.log. Let’s try it out, and test our project so far at the same time.
In the DartMarquee constructor, let’s print the _target property to make sure it’s being set.
DartMarquee(this._target) {
print(this._target);
}
And hit Run. In your browser, open up your console and you should see something like this:
Note that at the time of this writing, there is a bug with the Dart Editor that generates a warning stating that “print” is not a method. This is being tracked by Google and will probably be fixed soon, if not by the time you read this. But if you’re seeing that warning, just ignore it; it still compiles fine. This is an example of the bleeding edge on which Dart stands; the print warning was not happening when I started writing this tutorial, it’s only happened with the most recent build of the Editor (build 5104).
Step 14: DOM Manipulation
We’re going to create the needed HTML elements programmatically, and place them within our target <div>. Dart provides a very clean API for this kind of task.
First, let’s create a few more properties to hold some of the elements. Add these right below the first property you added:
class DartMarquee {
Element _target;
DivElement _mainImage;
DivElement _thumbContainer;
DartMarquee(this._target) {
Notice how we’re using underscores as a prefix? Not only this a common convention when naming private properties, it’s actually idiomatic Dart. An underscore prefix makes the property (or method, or class even) private. Otherwise, it’s public.
Also notice how we’ve typed them as DivElement? Another nice feature of Dart (as least for the web) is that it provides classes for the individual HTML elements, unlike the more generic approach usually taken in JavaScript. The upshot is that individual element types have the appropriate properties so it’s easy to manipulate them with Dart. For example, ImageElements have a src property that can be safely and easily accessed directly with Dart to modify the image’s source.
Now let’s create those elements. In the constructor:
DartMarquee(this._target) {
_mainImage = new Element.tag('div');
_mainImage.classes = ["mainImage"];
_thumbContainer = new Element.tag('div');
_thumbContainer.classes = ["thumbContainer"];
target.nodes.add(_mainImage);
target.nodes.add(_thumbContainer);
}
There’s a lot going on here; let’s break it down.
First we create a new DivElement. But notice that we don’t write new DivElement as you might expect (and believe me, I expected that, and continued to expect that for quite a while before I discovered the proper technique). Even though DivElement is a class, it doesn’t have a constructor that you can access. Instead, you use a named constructor on the Element class to create an element of a specific type.
Named constructors are just different constructors (kind of like method overloading, but it’s not really that) that can provide a different interface to the construction. In this case, we can specify by string the type of element. You can also write new Element.html('<div>...</div>'); to write out the HTML in string format. Two rather different approaches, so we have two constructors.
Once we have our _mainImage DivElement, we set its class. Element provides a classes property which lets us access the various classes that may applied. In this case, it’s a brand new element, so that property is empty. We set it to a single class name, "mainImage".
You might expect classes to be an Array (or List, in Dart parlance), but it’s actually a Set. A Set is similar to an Array in that it’s a collection of independent values, but the key difference is that the collection is unordered; there is no guarantee that the order of the contained values will be anything in particular, or even the same each time. This has a slight ramification in how we work with the classes property, but for now it’s a simple assignment to what looks like an Array containing a single String.
The next two lines are repeated almost verbatim, except that we’re assigning the _thumbContainer property, and assigning a different class.
The final two lines add these new Elements to the DOM, specifically, to the target div. As you can see, there is a nodes property on the Element, which as you’d expect is a List of child elements. Being a List (or Array), we can simply add (similar to JavaScript’s push) an Element into it. And at this point, the elements are in the DOM.
Go ahead and run the project again; because we’ve added classes to the new <div>s, and we have our CSS file ready to go, you should see a slight change to the page:
Step 15: Loading JSON
We need some content, not just grey boxes at which to look. We’ll drive our little marquee with a JSON file, so let’s look at how we make an HTTP request in Dart.
First, let’s create the JSON file. It’ll be pretty simple, and shouldn’t need any explaining in and of itself. Create a new file in your Dart project (File > New File…) and name it marquee.json. Add the following content:
{
"images":[
"scottwills_machinery3.jpg",
"scottwills_machinery4.jpg",
"scottwills_machinery5.jpg",
"scottwills_machinery6.jpg",
"scottwills_machinery7.jpg",
"scottwills_machinery8.jpg"
]
}
Save, and turn back to DartMarquee.dart. We’ll add the code to load this file in the constructor, after we’ve created our extra Elements.
XMLHttpRequest request = new XMLHttpRequest();
String url = 'marquee.json';
request.open("GET", url, true);
request.on.load.add(onJSONLoad);
request.send();
And that’s how you do that.
Oh, all right, a little explanation. First, we create an XMLHttpRequest object. That will handle the loading of the data (and would also handle the sending of data if we were doing that sort of thing). The next line is a bit superfluous, but I wanted to show another variable being created. Notice that String types can be created with the quote literal, just like in JavaScript (and just about every other language). In Dart, there is no difference between single- and double-quotes, unlike PHP or Ruby.
Next we start working with the XMLHttpRequest object. First we open the connection, passing in the method ("GET"), the url we just created, and finally that we’re interested in an asynchronous request (true). That means that we need to add an event listener to know when the load completes. That brings us to the most interesting line:
request.on.load.add(onJSONLoad);
This is Dart’s event model. Objects that dispatch events have an on property which acts as “event central”, where you can go to plan your next party. There will also be properties on the on object that correspond to the various events dispatched by the object in question; in this case, load is one of the events. Each of these event properties is actually a collection of listeners, to which we can add a new listener (onJSONLoad in this case; this hasn’t been written yet in case you were wondering).
This syntax took a little getting used to, but now I really like it. It’s safer and cleaner than request.addEventListener('load', onJSONLoad), wouldn’t you agree?
The last line of our previous code block simply sets the request in motion; send it off to get our data.
For this to work, we need an onJSONLoad function. Let’s start doing that next.
Step 16: Methods and Event Listeners
Now we get to write a new method. This method also happens to be an event listener (for the XMLHttpRequest we set up in the last step), but regardless the syntax is the same. Find a spot in the DartMarquee class that’s after the close of the constructor but before the close of the class – it should be between two closing braces. Add the following:
void onJSONLoad(Event e) {
print("onJSONLoad");
}
The syntax should be fairly obvious. It follows the property/variable syntax, in that we’ve replaced JavaScript’s function keyword with a datatype. The datatype is the type of the value returned by the function. In this case, void is actually the lack of type, as the function doesn’t return anything. And similar to properties, you can optionally leave the method untyped and use the function keyword instead of a type.
Now we can try out the application. Run it again, and check the console. You should get the message that our function has run, meaning the JSON file has loaded.
Step 17: Properly Bound “this”
Let’s pause in the action for a moment to talk theory. Don’t worry, you’ll learn something important along the way.
In the code that we just wrote to add an event listener, our event listener is properly bound to the scope of the object it belongs to. In JavaScript, this be bound to the object that dispatched the event. That is, if you write this in JavaScript:
myElement.addEventListener('click', onClick);
function onClick() { console.log(this); }
Then this refers to myElement, the object doing the event dispatching. In Dart, however, this will refer to the object to which the listener belongs. Try it out; change the print to this:
void onJSONLoad(Event e) {
print(this);
}
And run it again. You should see this:
OK, that doesn’t exactly prove things very well. [object Object] could be anything. Let’s take a quick look at a useful trick for making your classes describe themselves.
Add a method to DartMarquee called toString. This method should return a String and take no arguments.
String toString() {
return "DartMarquee";
}
Run it one more time and now you end up with this:
This should illustrate that “this” refers to the DartMarquee object. JavaScript does not behave this way without workarounds. This means that you don’t have to worry about binding functions to their scope when adding event listeners, such as with jQuery’s bind method and other similar solutions.
Step 18: Generics
Let’s move on and parse our JSON now that the JSON file is loaded. We’re going to parse it and stuff those URLs into a property, so first let’s trot back to the top of the class and add a _urls property:
Element _target;
DivElement _mainImage;
DivElement _thumbContainer;
List<String> _urls;
This syntax will look odd if you’re not coming from Java. The variable name is _urls, and the datatype is List<String>. We could just write List _urls, and that would work, but we can also take advantage of something that Dart provides. Back towards the beginning, I described reified generics, and the <String> part of the datatype is the generic. That is, the elements within the List are typed as Strings. The point of this step is pretty much to introduce this syntax. We’ll see it again soon.
If you’ve programmed ActionScript 3, you’ll find the syntax similar to Vectors, and in fact Dart Lists and AS3 Vectors are essentially the same thing.
Step 19: Parsing JSON
Now let’s get to parsing. Remove the print statement from onJSONLoad and add this:
void onJSONLoad(Event e) {
XMLHttpRequest request = e.target;
Map<String, Object> result = JSON.parse(request.responseText);
print("JSON: " + result);
int i = 0;
_urls = result['images'];
_urls.forEach((url) {
print("url $i: $url");
i++;
});
}
This code really isn’t so bad. Here’s how it breaks down.
Line 2: This is just casting the source of the event (found in e.target) to an XMLHttpRequest so we can more safely work with properties on it.
Line 3: This one gets a little gnarly. Skip to the second half of the line. We’re getting responseText out of the XMLHttpRequest object, which gives us the raw text found in our file. And we pass that into the parse method of the JSON class. That’s all there is to parsing JSON; it’s essentially built-in! Now, to make sure we can work with the data, we need to store it in a variable. This variable is result. Because I’m advocating strong typing, it also has a type. This type is Map<String, Object>, which might be a little frightening.
A Map is basically what we call an Object in JavaScript; it’s a collection, and stores its values by a String key.
Because Map is a collection, it can be generified (see last step), but because there are technically two things we can specify (the key and the value), we supply two types. Somewhat oddly, you can’t use anything other than String for the key type, so I’m not sure why it needs specified. It may be possible that Dart eventually allows the use of any type as the key. But for now, it’s a String key. Because our JSON data is an Object at it’s outermost, we specify Object as the value type. We have a little flexibility, depending on the JSON structure.
Line 4: Now that we have our JSON parsed, let’s just print it out to verify the result.
Line 5: Initialize a counter. Note that Dart supports an int type.
Line 6: Get the images property out of the main JSON object, which should be an Array/List, and store that in our _urls property that we set up in the last step.
Line 7: Loop over that List, using forEach and an anonymous function. Note the syntax for anonymous functions: (url) {...}. If there is no return type, we can leave it off completely and just start with the parameter list. It feels a little odd at first, but ultimately leads to less code written, which is kind of nice.
Line 8: Now we can print out the URL along with its index. Here we can see that Dart has String interpolation, which lets you expand variables within a String, and avoid breaking out of a String in order to include the value of a variable. The use of the dollar sign indicates that what follows is actually a variable, and Dart should interpolate it. Again, this is less code written and leads to much more readable code than String concatenation.
Line 9: Hopefully this line of code doesn’t need explanation.
Run the application, and…uh oh. That console doesn’t look pretty.
Read on for the fix.
Step 20: Importing More Libraries
The fix is, thankfully, rather simple. Dart is structured into libraries, and it turns out that JSON capability isn’t part of the HTML library. We simply need to add the following line at the very top of the file:
#import('dart:json');
Run the project again, and you should get a console full of output:
What I find odd is that this seems like something the JavaScript compiler catches, but it’s only a warning. The compiler recognizes that you’re using a class called JSON but doesn’t know where to find that class…that seems like an important thing to catch. The lesson here, aside from where the JSON library is, is to check the Problems panel in Dart Editor. It got kind of buried amidst the false print warnings, but it was there:
Also, when you run the project, the Console panel takes over in that space, so you may have missed the warnings altogether. Just something to be on the look out for. This kind of thing will probably improve with time.
Step 21: Writing External Classes
As we continue to explore Dart’s capabilities, we’re going to write a new class to handle a single thumbnail image. We’ll ultimately instantiate a number of these, one for each thumbnail.
While it’s possible to insert a second class definition into the same file, let’s see what happens when we decide to write an external class. In Dart Editor, create a new file for our project and name it MarqueeButton.dart. You’ll be presented with the following template:
class MarqueeButton {
}
Again, there is no requirement that we name the class after the file, or vice versa, but it does make sense, so we’ll leave well enough alone and just start filling in the details.
For now, let’s just get this functional by providing a simple constructor that prints a message so we can see it working. Add a constructor to the class:
class MarqueeButton {
MarqueeButton(index, image) {
print("$index: $image");
}
}
Nothing we haven’t been over already; this is a simple constructor that uses String interpolation.
But to use it, we need to make sure the DartMarquee class is aware of the MarqueeButton class. At the top of DartMarqee, where there are two #import statement, add a third line to include our new class:
#import('dart:html');
#import('dart:json');
#source('MarqueeButton.dart');
You were expecting another #import, weren’t you? #source is a bit simpler than #import. #import is for libraries, which need to be declared as such and can link to other files. #source simply includes the targeted file. One thing to note is the #sourced files cannot, themselves, link to other files. Even #importing the built-in libraries will cause a compiler error. As such, this is a simple way to collect a few files into another script, but for more complex structures you may want to consider creating a library.
Now that we’re linking to our new class, let’s use it. Down in onJSONLoad, we’ll replace the existing print with some instantiation:
void onJSONLoad(Event e) {
XMLHttpRequest request = e.target;
Map<String, Object> result = JSON.parse(request.responseText);
print("JSON: " + result);
int i = 0;
_urls = result['images'];
_urls.forEach((url) {
MarqueeButton btn = new MarqueeButton(i, "images/thumbs/" + url);
i++;
});
}
If you run the project again, you’ll get more or less the same thing, only now it’s logging from within the MarqueeButton class.
At this point, we can fill in most of the MarqueeButton class without running into much that’s new. I’ll present almost the full body of the class here, and discuss it briefly below.
class MarqueeButton {
DivElement _target;
String _image;
int _index;
Function _onClick;
MarqueeButton(this._index, this._image) {
_target = new Element.tag('div');
_target.classes = ["button"];
DivElement border = new Element.tag('div');
border.classes = ["border"];
_target.nodes.add(border);
_target.style.backgroundImage = 'url("'+_image+'")';
_target.on.click.add(onClick);
}
void onClick(Event e) {
_target.classes.add('selected');
_onClick(this);
}
}
We start the class off with a handful of properties, all private and typed. It may be interesting to note the Function type. We’ll get to this in a moment, but this illustrates that functions are fully-fledged objects in Dart, and can be passed around by reference rather easily.
The constructor is mostly about building up the HTML elements for the button. We start from scratch; the only things passed in to the constructor are the index of the button and the image URL. We’ve seen this before, creating and adding new elements. Line 15, however, present something new, although I’d imagine you can figure out what it does. Elements have a style property which lets you set CSS styles rather easily. The properties available to the style object follow the CSS style names, only removing the hyphen and turning the name camel-case. Note that the value might be a String or in the case of numeric values, it can just be a number.
The last line of the constructor adds a click event listener to the button, following the convention we saw with the XMLHttpRequest events.
Then we have our onClick method, the listener for that click event. For style purposes we’ll add the .selected class to the element, then we call the _onClick function. This, you’ll recall, is the property we declared earlier. This is a poor man’s event dispatching, and what happens is that DartMarquee will set this property to a function of its own, so that MarqueeButton can call it. We’ll get to the setting in a moment, and we haven’t written the relevant DartMarquee code. But because functions are first-class citizens of the Dart world, it’s easy to pass that function around, and execute it somewhat arbitrarily.
Step 23: Setters and Getters
We’ll finish off the class with some getters and a setter. For the uninitiated, setters and getters are special functions that simply return a value (getters), or receive a value (setters). They’re common enough, and most object-oriented languages provide some method for creating implicit setters and getters, which are functions that are called as if they were properties.
Dart has this, as well, and throws some syntactic sugar on top of it, to boot. Add this to the end of the class (before the closing curly brace, but after the onClick method):
DivElement get target() => _target;
int get index() => _index;
Function get click() => _onClick;
void set click(Function fn) {
_onClick = fn;
}
You can see the sugar in the three getters. Each one follows this pattern:
Type get name() => expression;
The type is nothing new; it’s the return type of the function. The get keyword signifies that this is an implicit getter function. name() is just the name of the method. Next is the => operator, which basically says “return the value that is expressed on my right.” In the case of _target, we’re simply accessing the value stored in the _target property and returning that. In other words, a basic getter method, written with a little less code than normal.
The expression can actually get a little more complicated than that, such as a boolean check or some simple one-liner math. If it’s going to require more than one line of code, it needs to be written as a regular getter, which is just like a regular method except for the get keyword:
DivElement get target() {
return _target;
}
We’re done with the MarqueeButton class now, so we’ll turn back to the DartMarquee class and start using it.
Step 24: Displaying Thumbnails
To display the buttons, we need to go back to the DartMarquee class and revisit the onJSONLoad method. Specifically, we need to add to that loop.
_urls.forEach((url) {
MarqueeButton btn = new MarqueeButton(i, "images/thumbs/" + url);
_thumbContainer.nodes.add(btn.target);
btn.click = onThumbClick;
i++;
});
Another nodes.add(), this time on the _thumbContainer div and adding the target of the MarqueeButton object.
Then we set the click property to a method we have yet to write, but will do so now:
void onThumbClick(MarqueeButton btn) {
print("onThumbClick");
}
We’ll work on this next, but for now we should be able to run the application, see the thumbnails, and click on them to see the log message.
We’re almost there. We’ll work on getting that click to mean something in the next two steps.
Step 25: Handling the Click
The logic involved in displaying a larger image isn’t terribly complex, and at this point we’ve had a pretty extensive tour of the Dart language. I’ll start listing the method here, and then discuss what’s going on.
First we need two properties declared. At the top of the class, with the other properties, add these lines:
MarqueeButton _currentButton;
ImageElement _currentImage;
Then update onThumbClick:
void onThumbClick(MarqueeButton btn) {
if (_currentButton != null) {
_currentButton.target.classes.remove('selected');
}
_currentButton = btn;
ImageElement image = new Element.tag('img');
image.width = 600;
image.height = 300;
image.src = "images/" + _urls[btn.index];
_mainImage.nodes.add(image);
}
The first thing to notice is that we’re checking for the existence of a value in _currentButton. If it does, then we remove the .selected class. Then we set the _currentButton property to the button that was clicked, for next time.
It’s worth nothing that Dart handles Booleans a little differently than you may be used to. Seth Ladd has a write-up on Booleans in Dart, in which we explains:
Dart has a true boolean type named bool, with only two values: true and false (and, I suppose, null). Due to Dart’s boolean conversion rules, all values except true are converted to false. Dart’s boolean expressions return the actual boolean result, not the last encountered value.
Therefore, when checking for the existence of a value within a variable, it’s wise to write if (variable != null) as opposed to the shorthand if (variable), as that could actually report false even through the variable has a valid value stored in it.
Next we create an image element, set its size, the src, and then add it as a child.
You should be able to try this out now. We won’t get a nice fade between the images, but you should now be able to use the marquee to switch images.
Step 26: Working with the Transition
Let’s work on that fade. Add the highlighted code below to the onThumbClick method. Note that Line 11 is a change from how it was before (it uses insertAdjacentElement), and the lines after that are new.
void onThumbClick(MarqueeButton e) {
if (_currentButton != null) {
_currentButton.target.classes.remove('selected');
print(_currentButton.target.classes);
}
_currentButton = e;
ImageElement image = new Element.tag('img');
image.width = 600;
image.height = 300;
image.src = "images/" + _urls[e.index];
_mainImage.insertAdjacentElement('afterBegin', image);
if (_currentImage != null) _currentImage.classes.add('fade_away');
_currentImage = image;
image.on.transitionEnd.add((evt) {
ImageElement img = evt.target;
img.remove();
});
}
The change to line 53 introduces another way to add children elements. Element.nodes.add() is fine for appending at the end, but if we want to insert in a specific place, in this case at the beginning, then nodes doesn’t give us enough options. insertAdjacentElement does provide options, although its interface isn’t as clean as it could be. In fact, it’s lifted from the Windows Internet Explorer API. I try not to get too opinionated in a tutorial, but this is an odd decision.
Regardless, it’s the API we have if we want to do more than append to the child elements. We want to add our new image to the beginning, so we pass in "afterBegin" to insertAdjacentElement, which does exactly that. This method is documented at MSDN if you’d like a description of the various valid arguments to that parameter.
The rest of the code involves itself with the CSS3 transition; by adding a .fade_away class to the old image (after checking to be sure it’s not null) we set it’s opacity to 0, invoking the transition. Then _currentImage is set to the new image, to get set for the next transition.
Finally, another event listener is added to the current image so that when the transition happens, and is finished, we can run a bit of code. All we do is get the event target and cast it as an ImageElement (not strictly necessary, but it’s something that I find useful to do in general). Then by calling remove() on the ImageElement, we remove it from the DOM. In other words, once it fade away completely, we can remove it altogether to keep our DOM tidy.
Note also that we’re using another anonymous function as the event listener in this case. Either way would work, but since this is practically a one-line function, making it anonymous is rather convenient.
Run the application, click on one thumb to load an image, then another thumb and watch it in silent awe.
Step 27: The Final Touch
Our Dart application is rather functional now, but you’ve probably noticed that it has one minor flaw: there is not image loaded up right away. This is a simple fix.
In Marquee.dart, find the onJSONLoad method and add the highlighted line of code toward the bottom:
void onJSONLoad(Event e) {
XMLHttpRequest request = e.target;
Map<String, Object> result = JSON.parse(request.responseText);
print("JSON: " + result);
int i = 0;
_urls = result['images'];
_urls.forEach((url) {
MarqueeButton btn = new MarqueeButton(i, "images/thumbs/" + url);
_thumbContainer.nodes.add(btn.target);
btn.click = onThumbClick;
if (i == 0) btn.onClick(null);
i++;
});
}
In effect, if we’re on the first iteration, take that MarqueeButton and call its onClick method. You’ll remember that as the event listener for the click event within the MarqueeButton. We’ll just call it directly, to sort of simulate a click on the first button, so as to trigger the setting of the styles and putting content in the right place. Since the method expects an event parameter, but isn’t really used, we can supply null to the method call to satisfy the compiler.
Run it once more, and you should now have the first image selected and ready in the main area.
Step 28: Where To Go From Here
We’ve just scratched the surface of Dart, but the cool thing is that if you know JavaScript, you already know Dart in one sense. You’re already familiar with what you can do with an HTML page, and generally how to do it. Dart for the web doesn’t really add any capabilities or fancy frameworks, it’s just another language in the same problem domain. If you want to learn more, you can do worse than to simply write applications in Dart. Maybe dig out a smallish/simple bit of JavaScript you’ve done and port it over to Dart.
If you like scouring the web for more resources, Google is certainly your friend, although the name “Dart” can lead to many unrelated hits that are about the game of darts, rather than the language. Many times I’ve had to specify “dart language” in my searches or get a little more specific than just “dart events”. There is quite a bit of information floating around.
First, the official Dart website is at dartlang.org. You’ll find a small tutorial there that goes into some of the unique language features, along with the nifty Dartboard widget that lets your write and execute dart code in the browser you can even use the widget on your own site).
If you think you know what you need to do, just don’t know the right method name or class, the API documentation is good place to start, at api.dartlang.org. Sometimes the docs are a little bare or even wrong, but you should probably begin any quest for an answer here.
I’ve already mentioned the mailing list, located at groups.google.com/a/dartlang.org/group/misc/topics. It’s very active and I had a few questions answered in a matter of minutes there. The Google engineers are very involved on the list, as well.
The Dart site also has a pretty nice JavaScript-to-Dart comparison chart, located at synonym.dartlang.org, which takes common JavaScript code snippets and shows the equivalent Dart code right beside it.
Moving away from Google’s own resources, there are a few Dart-centric blogs that kept coming up in searches. One of the most prolific is Japh(r) by Chris Strom, at japhr.blogspot.com/search/label/dartlang, who is also writing a book on Dart.
The Dartosphere (dartosphere.org aggregates several different blogs about Dart, and can be a gold mine of information.
Seth Ladd works at Google, and his blog at blog.sethladd.com has been recently devoted to Dart.
DartWatch, at dartwatch.com, is another Dart-centric blog that has plenty of content to keep you busy.
One problem, however, is that Dart is a bit of a moving target currently, and some of the older posts on blogs might be out-of-date by the time you get to them. Just keep that in mind. The mailing list is the best place to go if you can’t find a solution through a web search.
One last resource: if this tutorial sparks some interest amongst Tuts+ readers, then we’ll probably find a few more tutorials to write that delve deeper into the world of Dart.
Step 29: Regarding Events
In this tutorial, we learned how to attach event listeners to object, for example:
someElement.on.click.add(myClickListener);
someHTTPRequest.on.load.add(myLoadListener);
You may have noticed that we did not leverage this model when we needed to have the MarqueeButton object communicate to the DartMarquee object. We went for a more lo-fi event listener, where we simply pass a Function in to the object, and then call that Function from within the object. You may ask yourself, why did we do that? Why didn’t we use the on property to dispatch an event? Where does that highway lead to?
The answer is that Dart doesn’t provide this event mechanism outside of its own objects. Not only that, that event system is only available to objects in the HTML libraries. This feels like an area where Google might be able to open up. It sure would be nice to have our own classes become event dispatchers by simply extending an EventDispatcher class or similar, and with a little bit of code getting that mechanism for free.
It’s possible to build your own system that mimics the built-in mechanism, but for the purposes of this tutorial, I went the lo-fi route. There may be some future Dart tutorials that go deeper.
Conclusion
Is Dart the future? Some say yes, some say no. I say, “I don’t know”. I’m certainly intrigued by the possibilities, and as long as it compiles to usable JavaScript today, then maybe it doesn’t matter if Dart isn’t interpreted natively by all of the browsers.
For now, I would say that if CoffeeScript is something that’s been catching on, then the Dart-to-JavaScript technique certainly has the same opportunity. Unlike CoffeeScript, though, you end up with some overhead JavaScript, which may not be appropriate for a vast majority of JavaScript-enabled web pages today. For instance, our DartMarquee project compiles into a JavaScript that’s over 100 KB. That’s a bit much for such a simple marquee. One should be able to write that in regular JavaScript, aided by jQuery or a similar library, for well under that weight limit. And the niceties provided by Dart, with classes, typing, and imports, aren’t enough for this small application to really justify the size.
But for larger applications, like Google Docs, 280 Slides, or Mockingbird, then you can very easily justify the overhead. You’ll have hundreds of KB of JavaScript anyway, so a little extra for the compilation process in exchange for a more structured set of classes will definitely appeal to some programmers.
That’s all for this introduction to Dart. Thanks for reading. I hope it was enlightening for you!



View full post on Activetuts+