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

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *