You are on page 1of 18

Sprite Programming Mastery

by Adam Khoury
Copyright 2014
Published: August 2014

All rights reserved. Redistribution or reproduction of this book in whole or in part by any means is forbidden
without the express written permission of the author.
While every measure has been taken to assure that the information in this book is correct, there are no guarantees
that the information is accurate or complete. The author assumes no responsibility for damages that may result
from using the information in this book.

Preface
Mastery :: knowledge and skill that allows you to do or understand something very well
This book will assist the reader in understanding how to program dynamic interactive sprite graphics and
animations. It presents practical examples and informative dialogue that will spark creative thinking and
enhance skill sets. The book covers the basics as well as advanced sprite sheet programming concepts.

Technology Overview
The development technologies used in this book to demonstrate sprite sheet rigging are listed below. It is
helpful for the reader to have some prior basic experience working with these 3 technologies.
HTML5
CSS3
JavaScript
Web development technologies are ever changing beasts that receive updates every decade or less. For
instance HTML5, CSS3 and some JavaScript APIs are brand new as standards here in 2014. They are just now
standardizing within this year so this is a great time to learn these concepts because they are fresh new
standards for animation programmers and artists to work with.
The code examples are meant to convey underlying logic, and should not be viewed as syntax law. They are
written in such a way to clearly express concepts without over complicating the exercises. Most of the time
when programming things, functionality can be achieved using more than one approach. Since the book
covers various approaches to sprite programming, it is up to each individual developer to decide which style
of programming to adopt depending on the task and the deployment environment.

Files Included in the Download
There are sprite sheets and demo files included in your download package that this book will refer you to.
Under most code examples and images in the book a note is written expressing the external file name. You
may find it helpful to view the sprite sheets directly or edit them in your graphics editing software.
Some of the code examples in the book do not have corresponding files in the download package. The PDF
format of the book will allow you to copy and paste code examples directly out of the book.

Your Testing Environment
Popular browser software is where we render and view our work. But since Google Chrome browser still
requires the -webkit- prefix on the CSS3 animation property and @keyframes rule, you should test all code
examples in this book using either Internet Explorer or Firefox. Make sure the browser you test with is the
most modern version. Do not render tests and run experiments using outdated browser software.
To test the examples in the Chrome or Safari browser, you must apply the -webkit- prefix to your CSS3
animation property and keyframes for now. However, it should not be very much longer that Google Chrome
requires the -webkit- prefix and will soon support the standardized syntax as all other browsers do.
Table of Contents
^ Preface
1 Introduction to Sprite Animation Programming
1.1 What Is a Sprite?
1.2 What Is a Sprite Sheet?
1.3 Key Frame Animations and Keyframing Explained
2 Rigging CSS Sprite Animations
2.1 CSS background-position Property
2.2 CSS animation Property
2.3 CSS @keyframes Rule
2.4 Simple Bouncing Ball
2.5 Character Walk Cycle
2.6 Sprite Positioning Animations
2.7 Sprite Rotation Animations
2.8 Animate Backgrounds Behind Sprites
2.9 Delay Key Frame Animations
2.10 Sequential Key Frame Animations
2.11 Target Specific Sprite Sheet Sequences
2.12 Reverse a Key Frame Animation
2.13 Back and Forth Sequencing
2.14 Steps Relative to Key Frames
2.15 Using Grid Sprite Sheets
2.16 Sequence a Grid into a Single Animation
3 Interactive CSS Sprites with JavaScript
3.1 Introduction to Dynamic Animation
3.2 Window Load Event
3.3 Create HTML Elements with JavaScript
3.4 CSS Properties with JavaScript
3.5 CSS Key Frame Animations with JavaScript
3.6 CSS Transition Animations with JavaScript
3.7 JavaScript Event List
3.8 Animation Event Usage
3.9 Mouse Event Usage
3.10 Keyboard Event Usage
3.11 Change Event Usage
3.12 Timers and Sprites
3.13 requestAnimationFrame Method
3.14 Collision Detection
3.15 Detect Collisions Over Object Arrays
3.16 Hit Detect Touch and Mouse
3.17 Randomize Animation Values
3.18 Sound Effects
4 JavaScript Key Frame Programming
4.1 Scripted Key Frames Using JavaScript
4.2 Sprite Object Constructor
4.3 Handling Multiple Sprite Objects
4.4 JavaScript Sprite Object Loops
4.5 Event Listeners and Controls
5 Canvas Sprite Programming
5.1 The HTML5 Canvas
5.2 drawImage Method
5.3 Animating the Canvas
5.4 Canvas Bouncing Ball Animation
5.5 Clipping Grid Sprite Sheet Frames
5.6 Canvas Related Training
6 Sprite Sheet Design
6.1 A Simple Workflow
6.2 3D Model Sprite Sheets
6.3 Borrowing Sprite Sheets
7 Example Projects
7.1 Ajax Loader Animations
7.2 Building a 360 3D Model Viewer
7.3 Application Component Skinning
7.4 Video Game Production
Chapter 1
Introduction to Sprite Animation Programming
1.1 What is a Sprite?
A sprite is an independent element, graphic or animation in a scene. Since they exist independent of the
larger scene, computers do not have to rewrite the entire screen bitmap data every time something has to
move on the screen. It works the same way in cartoon production. Cartoon artists are not usually redrawing
the entire scene every frame just to make a character walk by or to make a single star twinkle.
In the illustration above, flying Santa Claus is a sprite because he must move across the scene while the rest
of the scenery remains mostly still. Many sprites can exist together in a scene doing their own thing.
Sprite graphics and animations are rendered from image files called "Sprite Sheets". The majority of this
book will focus on the animation aspects and web development aspects of working with sprite sheets.
Sprite Animations VS Animated GIFs
Sprite animations provide a much greater level of control and complexity than Animated GIFs can. Animated
GIFs are immutable animated frames while sprite animations can be interacted with and controlled. The
viewer interactions, CSS animation rigging, or your program event handling can determine how a sprite
animation sequence changes. Animated GIFs cannot work that way because they are unchanging static
animations. This is why sprite animations are used in video game development instead of GIF images.
1.2 What is a Sprite Sheet?
Sprite Sheets for Key Frame Animations
A sprite sheet for key frame animations is a single image file that contains a sequence of graphics that make
up an animation or multiple animations. The animation sequence on the sprite sheet is made up of uniformly
sized frames which make it possible to step through the frames quickly as if it were a film reel.
The sprite sheet above is a horizontal strip that
contains a key frame animation sequence of a
character in a walk cycle walking to the right.
You can also create grid style sprite sheets that
have multiple key frame animation sequences
on them like this sprite sheet to the left. Your
program can access any sequence of frames
located anywhere on your sprite sheet.

Sprite Sheets for Web Design and Element Skinning
This type of sprite sheet does not have to contain animation sequences nor do the frames have to be evenly
sized in the sprite sheet. You can think of these sprite sheets as graphical skins for elements in your program
that will change appearance or appear from nowhere during runtime.
Never worry about preloading graphics in your web/app/software projects again. The entire sprite sheet will
be loaded when the program or site loads initially. From that point on in the user experience, all graphics that
the page or program may possibly render are fully preloaded and ready for display.
1.3 Key Frame Animations and Keyframing Explained
What is a Key Frame Animation Sequence?
A key frame animation sequence is comprised of a starting frame, an ending frame, and any number of
transitional frames in between. Using more transitional frames in between the key frames results in a
smoother looking animation at the cost of using extra memory.

What is Keyframing?
Keyframing is when an animator first draws the pivotal frames of motion, which are the key frames. Then the
animator draws in the transitional frames in between the key frames to make it a smooth transition. The
animator has full control over the graphics within all of the transitional frames in between key frames.
There is another key frame animation concept known as "tweening" in which the animator supplies a
computer with only two graphics and on its own the computer draws all of the transitional frames trying its
best to shape/color tween the first image smoothly into the second. Tweening produces a morphing effect in
the transitional frames. The computer has no idea what you actually intend. Regarding sprite animations,
controlled keyframing produces far better results than tweening.
There are 5 essential things that the computer program needs to know:
1. starting frame position on the sprite sheet
2. ending frame position on the sprite sheet
3. the total number of frames(steps) in the animation
4. the speed at which you want the animation to run
5. how many times you want it to run, you can make it loop infinitely or just play once
Your program will automatically know where the transitional frames are if your sprite sheet has uniform
frames. It will render the specified frames in sequence, according to the layout of your sprite sheet.
Chapter 2
Rigging CSS Sprite Animations
2.1 CSS background-position Property
For sprite graphics or animations in your web documents, the CSS background-position
property plays a critical role. It clips the larger image to just a single frame. It is what allows
you to position the viewable portion of the sprite sheet inside of the element. We will
demonstrate using this simple 4 frame sprite sheet on the left which is 100px square.
background-position: X-axis Y-axis ;
<style>
.sprite_group1{
background: url(../images/sprite_sheet_1.png);
border:#000 1px dashed;
float:left;
margin:30px;
width:50px;
height:50px;
}
#sprite1 { background-position: 0px 0px; }
#sprite2 { background-position: -50px 0px; }
#sprite3 { background-position: 0px -50px; }
#sprite4 { background-position: -50px -50px; }
</style>
<div id="sprite1" class="sprite_group1"></div>
<div id="sprite2" class="sprite_group1"></div>
<div id="sprite3" class="sprite_group1"></div>
<div id="sprite4" class="sprite_group1"></div>
^ CSS_Background-Position_Property.html ( included in download package )
Giving us the following result on the screen:
The code example above shows how we can access any frame on the sprite sheet to make that specific frame
render as the background of an HTML element. That sprite sheet could also be animated using the CSS
@keyframes rule.
2.2 CSS animation Property
The CSS shorthand animation property will be used in this book to assign @keyframes rules to sprites. Using
the shorthand syntax greatly reduces the amount of code in our programs. However, you can apply the
longhand versions which are listed below. In fact, there may be an occasion where you must use the longhand
version of an animation setting.
animation-delay: 3.0s;
Delay the start of an animation. If a negative value is used(-Ns) the animation will start immediately, but be
offset the amount of time specified.
animation-direction: normal || reverse || alternate || alternate-reverse;
Specify whether or not the animation should play in reverse on some or all cycles. Playing an animation in
reverse also reverses the timing functions and easing in/out of the animation.
animation-duration: 2.5s;
Specify the amount of time that an animation cycle takes to run through before the next iteration begins. It
directly affects the speed of your animation. We use whole numbers or decimal numbers followed by a
lowercase "s" which represents seconds.
animation-fill-mode: none || forwards || backwards || both;
Specify what values are applied by the animation outside the time it is running(before and after animation
runs). This allows us to specify how our animation should begin, end, and behave according to key frames we
establish.
animation-iteration-count: infinite || Whole_Number || Decimal_Number;
Specifies how many cycles an animation will run. To make it run as a loop we use "infinite", to specify the
cycle amount exactly we use a whole number. If you omit this property the animation will run one cycle by
default. If you use a decimal number the animation will be offset or chopped by the fraction specified.
animation-name: animation || animation, animation, animation;
Specifies which animations get applied to specific elements. An element can have one or more animations
applied to it simultaneously, which allows you to animate CSS properties at separate speeds and cycles. The
other CSS animation properties can have corresponding comma separated values designated to affect
specific animations in your comma separated animation name list.
animation-play-state: running || paused;
Pause and resume animations. We can use JavaScript to affect this and any other CSS properties while
animations are running. Setting a paused animation to "running" will resume the animation from the point it
was paused.
animation-timing-function: ease || linear || ease-in || ease-out || ease-in-out || steps(n) || cubic-bezier(n,
n, n, n) || initial || inherit;
Specify the transition effect of an animation. For instance whether it starts fast and slows to a stop, starts
slow and speeds to a stop, and other transition effects. Animations will "ease" by default if you omit this
property.
animation
Shorthand for establishing multiple animation properties in the same line. Each property is space separated.
If you wish to apply settings for multiple animations you can separate each set of properties by commas. The
examples throughout the book demonstrate how to use the shorthand property.

Note: All of these CSS properties are used outside of sprite sheet animation work. They are also used for
keyframe animating the CSS settings for any ordinary HTML elements in the document.
2.3 CSS @keyframes Rule
The CSS @keyframes rule is used for rigging key frame animations. Key frames in CSS mark the starting and
ending CSS property values of an animated effect. When working with a sprite sheet, it is used in conjunction
with the CSS animation property to step through keyframed animation sequences on the sheet.
You can rig a CSS @keyframes animation using the from - to syntax if you only have two key frames in your
animation. But if you want an animation to have more than two key frames, you can use percentage values
ranging from 0%(first key frame) to 100%(last key frame).
Animation with 2 Key Frames(starting and ending frames):
0% { property: start_value; }
100% { property: end_value; }
/* OR */
from { property: start_value; }
to { property: end_value; }
Animation with 3 Key Frames:
0% { property: start_value; }
50% { property: value; }
100% { property: end_value; }
Animation with 4 Key Frames:
0% { property: start_value; }
33% { property: value; }
66% { property: value; }
100% { property: end_value; }
Animation with 5 Key Frames:
0% { property: start_value; }
25% { property: value; }
50% { property: value; }
75% { property: value; }
100% { property: end_value; }
Make the first 2 key frames take up most of the animation duration time:
0% { property: start_value; }
80% { property: value; }
100% { property: end_value; }
The programming exercises in the following sections should get you comfortable rigging key frame
animations.

Browser Specific Prefixes
The animation aspects of CSS are relatively new. At the time of writing this book the Standard syntax works
in all modern versions of all browsers except for Chrome and Safari. So all we have to do is apply a version
of those CSS properties/rules with the -webkit- prefix to also make it work in webkit driven browsers like
Chrome and Safari. This is only a temporary measure, Chrome and Safari should use standard syntax soon and
we can avoid adding more code for specific browsers.
#player {
background: url( player_sprite_sheet.png );
width:100px;
height:100px;
-webkit-animation: run-left 1.0s steps(6) infinite;
animation: run-left 1.0s steps(6) infinite;
}
@-webkit-keyframes run-left {
from { background-position: 0px; }
to { background-position: -640px; }
}
@keyframes run-left {
from { background-position: 0px; }
to { background-position: -640px; }
}
2.4 Simple Bouncing Ball Animation
^ 300px wide | 50px high | Sprite Sheet ball_bounce.png ( included in download package )
1. Our ball_bounce.png sprite sheet has 6 frames as you can see above. It is 300px wide and 50px high.
2. That means it has 6 uniform 50px square frames ( 300px / 6 frames = 50px ) that must be stepped through.
3. We will now apply that information to our program to render the animation.
<style>
#ball {
background: url(../images/ball_bounce.png);
width: 50px;
height: 50px;
animation: ball-bounce 0.7s steps(6) infinite;
}
@keyframes ball-bounce {
from { background-position: 0px; }
to { background-position: -300px; }
}
</style>
<div id="ball"></div>
^ Bouncing_Ball_Sprite.html ( included in download package )
Note: from - to is equivalent to 0% - 100% syntax in the @keyframes rule.
animation settings explained:
animation-name - ball-bounce - name of the @keyframes rule
animation-duration - 0.7s - how long it takes to render all frames in an iteration( animation speed )
animation-timing-function - steps(6) - total frame count of the animation sequence
animation-iteration-count - infinite - how many times we want the animation sequence to run
Open Bouncing_Ball_Sprite.html in your download package code_examples folder to see the live demo.
2.5 Character Walk Cycle Animation
^ 960px wide | 180px high | Sprite Sheet adam_walk_right.png ( included in download package )
1. adam_walk_right.png sprite sheet has 8 frames as you can see. It is 960px wide and 180px high.
2. It has 8 uniform 120x180 px frames ( 960px / 8 frames = 120px ) that must be stepped through.
3. We will now apply that information to our program to render the animation.
<style>
#adam {
background: url(../images/adam_walk_right.png);
width: 120px;
height: 180px;
animation: walk-right 1.0s steps(8) infinite;
}
@keyframes walk-right {
0% { background-position: 0px; }
100% { background-position: -960px; }
}
</style>
<div id="adam"></div>
^ Character_Walk_Cycle_Sprite_Animation.html ( included in download package )
Note: from - to is equivalent to 0% - 100% syntax in the @keyframes rule.
Chapter 3
Interactive CSS Sprites with JavaScript
3.1 Introduction to Dynamic Animation
JavaScript can control virtually every aspect of the document in which your animations and programs run.
Every element in the document, the document itself, the window that contains it and more are all under the
direct control of JavaScript if you so choose. All of the concepts in the previous chapter can be made
dynamic using JavaScript. It is very important to keep that in mind if you are to achieve magical results.
If you already have a good deal of JavaScript programming experience, your productions will go much faster
than that of a beginner because you already know more of what the language can do.
JavaScript is capable of the following, but not limited to:
Creating elements(our sprites) out of thin air during runtime of the program
Removing elements dynamically during runtime
Applying the CSS animation property to elements dynamically at any time in the program flow
Changing the animation properties of an element dynamically during runtime
Adjusting things according to countdown timers, intervals or the requested frame rate of the browser
Making animations and your program react to all of the many JavaScript DOM events
With JavaScript in the mix, we get the level of dynamics we need to create smarter programs that react to the
display environment and the user in ways that are just not possible with CSS alone.
If you are developing a custom application or video game, some sprites would have to enter the scene from
nowhere dynamically during runtime of the program. And you would need to program in controls to allow the
user to interact with the program in some way, JavaScript does that more completely than CSS. All CSS has
is a few pseudo selectors like the hover selector, while JavaScript has access to all events in the DOM.
Using JavaScript opens up a lot more creative possibilities for an animator, game programmer or web
developer. The examples provided in this section aim to demonstrate the features of JavaScript that are
directly related to animation. We'll ease into it so that beginners can understand the basics enough to
hopefully grasp the more complex concepts well.
3.2 Window Load Event
We will use the load event of the window object in JavaScript to make sure that the entire document and all
elements are loaded before running some dynamic script that needs to target the document body or child
elements within it. If you try to script against an element on the page that has not loaded into the
DOM(Document Object Model) yet, the script will fail. We do this to keep all script in the head of the
document, otherwise the script would have to be placed right before the closing </body> tag.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script>
function doSomething(){
alert("We will establish dynamic sprites here through code");
}
window.addEventListener("load", doSomething);
</script>
</head>
<body>
</body>
</html>
3.3 Create HTML Elements with JavaScript
It is very important to understand how to dynamically create HTML elements using JavaScript. This way you
can add/remove/manipulate sprites at will during run time of the application. JavaScript can manipulate
everything in the document and create things out of thin air.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script>
var sprite1;
function loadSprites(){
// Create a new DIV element
sprite1 = document.createElement("div");
// Give it a unique ID
sprite1.id = "spr1";
// Adjust its innerHTML property
sprite1.innerHTML = "I have arrived on the page";
// Append it to the body container of the page
document.body.appendChild(sprite1);
}
// The window load event listener, fires loadSprites function
window.addEventListener("load", loadSprites);
</script>
</head>
<body>
</body>
</html>
You can use the appendChild() method to place the newly created dynamic element into any container on the
page, not just the body. If you have a game board DIV on the page you can write
"gameboard.appendChild(sprite1);".
3.4 CSS Properties with JavaScript
Using JavaScript we can apply and adjust CSS property values for HTML elements dynamically.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script>
// Initialize our sprite object variable name
var sprite1;
// This function fires off via the window load event
function loadSprites(){
// Create the new DIV element that our sprite will live in
sprite1 = document.createElement("div");
// Give it a unique ID
sprite1.id = "spr1";
// Adjust the HTML
sprite1.innerHTML = "I have arrived on the page";
// Specify CSS background color
sprite1.style.background = "turquoise";
// And 4 more CSS properties
sprite1.style.border = "#000 3px solid";
sprite1.style.padding = "20px";
sprite1.style.width = "100px";
sprite1.style.height = "100px";
// Append the element to the body container in the document
document.body.appendChild(sprite1);
}
window.addEventListener("load", loadSprites);
</script>
</head>
<body>
</body>
</html>
Note: In some special cases the CSS property name is not written in JavaScript the same way it is written in
CSS. Take the following examples:
z-index : CSS | zIndex : JavaScript
background-position : CSS | backgroundPosition : JavaScript
font-size : CSS | fontSize : JavaScript
Any CSS property names that have a hyphen( - ) in them are turned to camel case and the hyphen removed
when they are referenced using JavaScript.
Preview End

You might also like