次の方法で共有


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?

How Will You Start the Show?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: image  

What the user actually sees: image

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.

There’s now a more efficient way - requestAnimationFrame.  Instead of specifying how long until the next iteration, requestAnimationFrame asks the browserto call back when it’s ready to display the next frame.  For a demonstration, see the requestAnimationFrame example (and the Windows SDK sample):

image

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:

    function renderLoop() {
requestAnimationFrame(gameLoop);

        // Draw stuff…
}

[Here, I’m using a tip from Martin Wells’ Sprite Animation article that putting requestAnimationFrame before drawing code can improve consistency.]

Note that if you’re creating a browser-based (vs. Windows Store) game, you’ll want to check for vendor-specific prefixed requestAnimationFrame implementations (e.g. window.msRequestAnimationFrame).

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:

    <body>
<img id="smile" src="images/Smile.png" />
</body>

Set some starting CSS in /css/default.css:

    #smile {
        position:absolute;
        background:#ffd800;
        border:4px solid #000;
        border-radius:20px;
}

Now we can write some basic animation in /js/default.js.  First add the highlighted to the existing args.setPromise line:

args.setPromise(WinJS.UI.processAll().then(init()));

Now, add a variable, init function to start things, and gameLoop to animate things:

image

Give it a run, and prepare to be amazed!

imageimage

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.

Transitionscan help you animate the presentation changes from state A to B, simply using CSS.  See the Hands On: transitions sample:

image

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.) 

See the Hands On: animations sample:

image

See Also:

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. 

Some examples (don’t forget, View Source is your friend): SVG-oids, SVG Dice, and SVG Helicopter.

imageimageimage

SVG is a powerful option, but when should you use it, and how does it compare with using canvas? See How To Choose Between SVG and Canvas.

See also:

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.

New to canvas?  Try the ”drawing to a canvas” Quickstart.

Let’s use canvas in a new example.  Create a new Blank App project and add a <canvas> element to default.html:

    <body>
        <canvas id="gameCanvas" height="800" width="800"></canvas>
    </body>

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:

image

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. 

Here’s what you should see when you run the “game”:

imageimage

Of course, there’s a lot more to canvas and canvas animation than that.  Canvas can work with images, video, animations, gradients and much more.  For details, see the Quickstart and ”How to animate canvas graphics", and for demos see Canvas Pad and Canvas Pinball:

imageimage

  

Also, there are a number of libraries available to make working with canvas easier, for example EaselJS, which we’ll get to a little later.

Animating Windows Store Games with WinJS

The Windows Library for JavaScript (WinJS) contains helpful namespaces and classes to create animations in an efficient and reliable way.

For example, you can use WinJS.UI.executeTransition to activate one or more CSS transitions.  Our earlier DOM element example could become:

image

Even more useful, there’s a full library of animations available in WinJS.UI.Animation, including animations for:

  • Adding/Removing content
  • Transitioning & navigating
  • Dragging & dropping
  • Selecting content
  • et al.

These are most frequently helpful with Windows Store apps, but games can benefit as well.  To see some in action, try the HTML animation library sample from the Windows SDK:

image

See Animating your UI to learn more.

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()

imagejQuery 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.

For some interesting examples/tutorials, see "13 Excellent jQuery Animation Techniques" on WDL.

CreateJS: Animation with EaselJS & TweenJS

imageCreateJS 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:

imageimage

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.

imageimage

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.

A great directory of what’s out there is the Game Engines list on GitHub.

Also see Bob Familiar’s “Windows 8 Game Development for the Win” list of various game tools and frameworks (free and commercial) that can lead to Windows Store games.

Let’s Get Moving!

Ready to dive in?  Here are a few more references to get you started.

Enjoy, and good luck!

-Chris

Comments

  • Anonymous
    September 29, 2012
    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