Basic animation

Canvas animations in HTML5 relies on the build in double buffering of the canvas element and the built in timers in JavaScript. The following example demonstrates. When the page is loaded, the initializeAnimation function is called. The initializeAnimation function sets some values to some variables and fires the animation by calling the setInterval function. The setInterval function uses JavaScript’s built in timer to repeatable call a given function (in this case drawFrame) at a given interval (in this case 30 milliseconds). The drawFrame function then manipulates the variables and draws the frame.


<html>
   <head>
      <script language="javascript">
          
          //Some global initialization.
          var x, y, xspeed, yspeed, myCanvas, g;

          function initializeAnimation() {
              x = 20; y = 30; xspeed = 7;  yspeed = 4;
              myCanvas = document.getElementById("myCanvas");
              g = myCanvas.getContext("2d");
              setInterval(drawFrame, 30);
          }
                    
          //Frame handeling.
          function drawFrame() {
              //Clear the image (making it black).
              g.fillStyle = "#000";
              g.fillRect(0, 0, 400, 300);

              //Apply the movement.
              x += xspeed; y += yspeed;
              if (x >= 390 || x <= 10)
                  xspeed *= -1;
              if (y >= 290 || y <= 10)
                  yspeed *= -1;

              //Draw the ball (yellow).
              g.fillStyle = "#ff0";
              g.fillRect(x-10, y-10, 20, 20);
         }
      </script>
   </head>
   <body onload="initializeAnimation();">
      <canvas id="myCanvas" width="400" height="300"></canvas>
   </body>
</html>

The result will be a black region with a yellow “ball” bouncing around (shown here).

Filling and drawing boxes

The HTML5 canvas is an excellent way to display vector graphics on the web, that is, images that isn’t made up by pixels, but geometrical shapes, such as lines and boxes. To display a vector image, you will need a canvas tag that defines the size of the image, and some JavaScript code that defines the picture content. This will create a 400×300 pixel image. The ID attribute is used to access the canvas from your script.

<canvas id="myCanvas" width="400" height="300"></canvas>

The JavaScript code that you write, is suitable to call from the onLoad event of your page, like so:

<html>
   <head>
      <script language="javascript">
         function doSomeDrawing(){
         }
      </script>
   </head>
   <body onload="doSomeDrawing();">
      <canvas id="myCanvas" width="400" height="300"></canvas>
   </body>
</html>

The rest of what you see, takes place from within the doSomeDrawing function. First off, acquire the references you need.

//Get a reference to the canvas element.
var myCanvas=document.getElementById("myCanvas");
            
//Get a reference to the graphics context object.
var g=myCanvas.getContext();

The rest of this example, will use the graphics context object (the g reference). Now, the fillStyle property will control how shapes are filled. Assigning null to the fillStyle property will prevent filling all together. Likewise, the strokeStyle property will control how shape outlines are stroked, and assigning null will prevent outlines. In some cases, as with the rectangle, the name of the method tells if the shape will be stroked or filled. The following code will do a red outline and an overlapping green filled rectangle:

//Get a reference to the canvas element.
var myCanvas=document.getElementById("myCanvas");

//Get a reference to the graphics context object.
var g=myCanvas.getContext("2d");

g.strokeStyle="#ff0000";
g.strokeRect(10, 10, 100, 100);

g.fillStyle="#00ff00";
g.fillRect(30, 30, 100, 100);

And this is the result: