Introduction to JavaScript Animation and Windows 8 Games

Unless you’re aiming for the next great text-only game, chances are something’s going to move in your game. From ships and planets to fireballs and monsters, what are some ways to get them going?

JavaScript-based games in Windows 8 can take advantage of many different options. Here are some of them:

Animate DOM elements with JavaScript and CSS

Animate DOM elements with new CSS3 features

Animate what’s drawn in SVG

Animate what’s drawn to a <canvas> element

Use the WinJS.UI.Animations library

Use one of many animation frameworks

We’ll take a look at each of these, but first it’s important to know game loop options.

The Game Loop

To get things going, you need code that handles input, updates game state, and draws/moves things.

You might think to start with a for loop, and move something across the screen. E.g.:

for (i = 0; i<10; i++){ smiley.x += 20; }

What happens logically:

What the user actuallysees:

You’ll probably just see the item popping instantaneously to the final location. Why? The interim positions will change more quickly than the screen will update. Not the best animation, is it?

Later, we’ll get to CSS features and animation frameworks that offer ways to chain animations with logical delays (“move this here, wait a bit, then move it there”), but in the meantime, let’s leave the for loop behind…

SetInterval & SetTimeout

Generally, game loops work by calling a function repeatedly, but with a delay between each call. You can use setTimeoutto do something like this:

function gameLoop() { // Update stuff… // Draw stuff…

setTimeout(gameLoop, 1000/60); // Target 60 frames per second }

Just point setTimeout to the function to call and how long (in milliseconds) to wait. Closely related, setIntervalalso waits then calls a function, but automatically keeps calling the function until canceled.

Using requestAnimationFrame

But there’s some trouble in setTimeout/setInterval paradise.

They work by setting a fixed amount of time between loops, but what if the system isn’t ready to draw an updated frame? Any drawing code executed is wasted because nobody will see the update.

Important: to benefit from requestAnimationFrame, you should separate your state-updating code from your visual rendering/drawing code. Update can continue use setTimeout to run consistently to keep the game going – process input, update state, communicate, etc. – but rendering will run only when necessary via requestAnimationFrame.

Like setTimeout, requestAnimationFrame needs to be used once per callback. With a separate render loop, you might have something like this:

That’s a basic introduction, but there’s more to game loops that you should look into: loop coordination techniques, integrating event-driven updates, and different ways to compute how much to change in each iteration of the game loop.

Basic DOM Element Animation

One way to create HTML games that generally work well across browsers and without plugins, is to use a bunch of DOM elements (<div>, <img>, etc.) and move them around. Through some combination of JavaScript and CSS, you could animate and move things around the browser.

Let’s take a look at how this applies to a Windows Store game.

Start Visual Studio 2012 and under JavaScript Windows Store templates, create a game with the “Blank App” template. Add any image to the game’s images folder, then and add it via an <img> tag to default.html:

DOM element animation is time-tested and still a perfectly viable option for many situations. However, more options have emerged since then, so, onward!

Animation with CSS3

The latest features in CSS3 (aka “CSS Module Level 3”) offer 2D and 3D ways to change and animate presentation styles defined for DOM elements. These approaches can be both concise and easy to maintain.

CSS3 Transitions

Transforms (both 2D and now in CSS3, 3D) can change appearance of an item – Transforms to rotate, scale, move (called “translate”), and skew (think stretch or italics and you won’t be far off), but they simply change from one state to another.

Our above DOM element example could be modified to apply a style with a transition over 4 seconds. Something like this:

left: 500px; top: 500px; transition:4s linear;

CSS3 Animations

Transitions are very useful, but support only a single timing function. Animationsintroduce keyframes, which allow multiple timing functions to control animations. Also, Animations are explicitly called (vs. Transitions, which trigger implicitly.)

Animation with SVG

SVG (Scalable Vector Graphics) support using markup and/or code to define shapes that retain clarity/definition as they are scaled. SVG can even utilize styles defined in CSS, making them even more flexible.

Because the individual components of an SVG composition are themselves DOM elements, this is technically a special case of the DOM elements approach, so many of the same techniques apply.

Animation on a Canvas

Support for <canvas> across many browsers has made it a great option games. Though you can add a canvas via HTML (or dynamically with JavaScript), canvas is driven entirely by JavaScript, so creating animations is a matter of knowing what you’re drawing and where, and modifying over time with JavaScript.

Because JavaScript is the only way to “talk” to the canvas, we’ll focus on /js/default.js for the rest. Add a pointer to init() like above, then thefunction:

Because canvas uses immediate mode graphics, it’s not as simple as creating an object and moving by setting location properties (like you can with DOM and SVG animation.) So, canvas-based games will typically create JavaScript classes for things to be tracked and displayed, then update logic simply sets properties (x, y, etc.) on those instances, which the render loop dutifully draws to the canvas.

Using Animation Frameworks

Just as we saw with JavaScript physics engines in an earlier post, there are many frameworks out there that can make many of common scenarios easier. Anything that can save time and effort is worth some research.

There are many out there, but here are a couple to get you thinking.

jQuery & jQuery.animate()

jQuery is an JavaScript library that helps make common tasks easier (and reliably cross-browser).

Among the many things you’ll find in jQuery, the jQuery .animate() method has many features that can apply to game animation.

With jQuery.animate, our “smile” example could be written as:

$(‘#smile’).animate({left: ‘+=500’,top: ‘+=500’,}, 4000);

A jQuery selector is used to find the smile element, then the animate method will adjust the left and top CSS properties, increasing each by 500 pixels over 4 seconds.

CreateJS: Animation with EaselJS & TweenJS

CreateJS is a family of JavaScript libraries and tools to help make things from canvas, sound, loading, to animations easier.

I introduced using CreateJS for Windows Store Games in an earlier post. If you’re new to CreateJS, have a look. As the post details, EaselJS can make using canvas for games much easier. It also supports features like SpriteSheet, which uses multiple pictures of the same object to create animations, such as a character running:

However, another CreateJS library, TweenJS, is especially relevant to any discussion of animations.

You can use TweenJS to animate objects’ values and CSS properties. It also offers a chained syntax, where you can specify animations as steps with delays and other connections to relate them.

Like CSS Transitions and Animations, TweenJS also supports easing functions to control the rate of change of each animation.

Game Engines

Not only are there more animation frameworks out there, but there are game-related frameworks as well. I’ll probably dedicate a post to this later, but some examples are Crafty, melonJS, Akihabara and more.

Interesting, JavaScript is definitely the wave of the future, I think we will be seeing it used for more and more game development. I've been thinking a lot lately about the future of Js on the web: plus.google.com/…/Z3UpNLrwMSW