Like this article? We recommend

Donnie Santos and I teach programming courses at the same college. Not surprisingly, many students mention gaming and animation as reasons for their interest in programming. Gaming, anime, and other forms of animation generate a lot of buzz, which is why we often introduce animation concepts into our programming courses. Some of the more recent buzz revolves around the Canvas element in HTML 5, which allows for dynamic, scriptable rendering of 2D shapes and bitmap images. In this article, we provide a framework for creating basic animation in HTML 5 Canvas.

In HTML 5, Canvas generally corresponds to the functionality of Flash in earlier browsers. Canvas is intended to be standard across all browsers, as opposed to Flash, which is proprietary. In theory, installing the Flash player provides a reliable model for animation, regardless of the platform. As with everything else in HTML 5, the hope is that all browsers will eventually comply with the specification, including Canvas. Meanwhile, the current performance of Canvas with respect to Flash is open to debate.

The framework that we present here will eventually lead to an implementation of a modified Pong game. This framework consists of three primary gaming components: a rectangle (paddle), a circle (ball), and some basic text. The concepts are simple, yet central to any animation. Our intent is to give you a concise and compact amount of code that you can easily get up and running. Then it's up to you to research, explore, and expand the game.

NOTE

This article focuses on the concept of the framework, and we won't go into much detail regarding the specific API components. These components are well documented at w3schools.com. We strongly believe that a major part of the educational process is to practice researching what you need to get the job done. A good developer must utilize online resources, such as w3schools, to become proficient as a programmer. In this spirit, we provide the framework, as well as some key concepts, but expect the reader to explore further and fill in many of the details.

The Canvas Framework: HTML

One strength of this game framework is that it doesn't require a lot of code, and this application is almost exclusively JavaScript. The lone HTML file is pretty concise:

The canvas for the application will be 600 × 600 pixels. Basically, the canvas is the area of the screen on which we'll draw the animation. In 2D graphics, we'll call the paint() method over and over to draw on the canvas. This act of continuously painting will create the effect of animation.

The only other lines of code in the HTML are the callouts to JQuery and the application's JavaScript file, scripts.js.

The Animation Code in Chrome: JavaScript

The heart of this application is in the JavaScript. Considering the core functionality, it's not much code. This is the entire script:

Before we start explaining the code details, go ahead and load the application in the Chrome browser. Using Chrome is important because we used that platform for these examples. Once you get the code running in Chrome, you can expand your testing to other browsers.

When you execute this application, the screen in Figure 1 appears in the browser.

The canvas (600 × 600) is immediately apparent as defined by the border. Notice the three game elements: the rectangle and circle are the game pieces, and the text indicates the position of the mouse. When you move the mouse, its text coordinates are updated, proof that the screen is being repainted continuously.

Game Concepts

Let's take a look into the code. Here's the first line in the application:

var Main = {};

To make life easier, we create a sort-of-global scope called Main, which allows us to reference components at the application (global) level. This technique may not technically be required, but it makes the code much easier to construct and follow in relationship to the design. This reasoning will become apparent in the next several lines of code.

The second line represents the actual canvas:

Main.Canvas = document.getElementById('myCanvas');

Here we assign the element from the HTML to Main.Canvas. We could do this (perhaps more efficiently) in JQuery, but for this basic example we'll stick with document.getElementById.

Canvas is a predefined object that comes with methods defined by the specification, such as getContext(). If you use the getContext() method with the parameter '2d', you can acquire a context object:

Main.Context = Main.Canvas.getContext('2d');

The names Main.Canvas and Main.Context are not specifically required (you can name them anything you want), but we use them here for clarity.

For all of your canvas applications, it's good practice to create globally scoped MX and MY variables to keep track of the mouse's location:

Main.MX = 0;
Main.MY = 0;

Loading the Document

When the application code is loaded into the browser (when the application is ready), we execute the following code:

$(document).ready(function()
{
Main.Animate();
});

The call to Animate() is the only line of code in this method, because it's a recursive process.

The Animate Method

The final Pong game will include much more functionality in the Animate() method, but at this point we'll strip the code down to the basics for illustration purposes. Obviously, more variables will be declared in the final Pong application, as well as more code.

At this point, we're simply painting three primary components of our Pong game—a rectangle (paddle), a circle (ball), and the text for the mouse coordinates:

In addition to painting the paddle, ball, mouse coordinates, and current score, which are specific to this application, a couple of lines are included in all animations. The following line clears the entire context (screen) using the globally defined coordinates:

Main.Context.clearRect(0, 0, Main.Canvas.width, Main.Canvas.height);

The other really interesting line in this method is the last one:

requestAnimFrame(function() { Main.Animate(); });

The window in HTML/JavaScript (the DOM) requires that you call this method at the end of your Animate() method:

We won't go into detail here regarding this method; essentially it handles browser differences and various compatibility issues. The one feature that we will point out in this method is the following line of code, which controls the speed at which the screen is repainted:

callback, 1000 / 60

You may have noticed that the Animate() method actually calls itself in an endless loop. This is a prime example of recursion. Since the Animate() method is called over and over, the screen is continuously repainted. Closing the window is the only way to stop the application.

The Framework

The following code is pretty basic, but consider it a framework to be included in all animations:

The Pong Game

All the animation code for the Pong game is listed at the end of this section in the Main.Animate() method. Actually, not much code has to be added. As noted earlier, this is a modified Pong game:

A single ball moves around the screen.

The left side of the screen holds a single paddle.

The mouse controls the ball's location.

The screen displays the coordinates of the paddle and the ball, along with the current score.

The game starts by launching a ball, which bounces around the confines of the Canvas. When the ball hits a wall, it changes direction. The point of the game is to use the mouse to control the paddle and strike the ball before it hits the "left wall." Each time the ball strikes the paddle, the game records a "hit." If the paddle misses the ball and bounces off the left wall, the game records a "miss."

Note the C-style comments in the code, which explain the important concepts of this game. The amount of code is small enough that the comments are the best form of illustration. As noted earlier, we won't explain every aspect of the code here; we leave the details for you to explore. However, the following list provides the important design requirements for the functionality of this Pong game:

The size and shape of the paddle and ball have been adjusted for this specific game.

Variables keep track of the ball's direction and angle.

Additional code controls the paddle with the mouse.

Code checks when the ball intersects the plane of the paddle.

Code checks whether the ball strikes the paddle.

If the ball strikes the paddle, it changes the direction and angle of the ball.

If the ball strikes the paddle, the score of "hits" is incremented.

If the ball strikes the left wall, the score of "misses" is incremented.

Conclusion

Now that we've explained the framework and basic concepts, it's time for the reader to start exploring. Once the code provided in this article is up and running, you should experiment, revising the specifications of the Pong game to add new functionality. Use the animation framework we've provided and create a baseline set of code that you can incorporate into any animation application.

Finally, test the application with various browsers (different vendors as well as versions) to identify issues that may affect distribution of the applications you might publish. It would also be interesting to see how your Canvas applications compare to Flash in programming, portability, and performance.

Our hope is that this concise animation framework will whet your programming appetite for the Canvas specification, as well as your interest in gaming and other forms of animation. The w3schools site provides a wealth of information about Canvas, HTML 5, and many other topics.