Simple 2D animation in HTML5 canvas

HTML5 animation demo screenshot smallI needed some animation for E.A.T., so I tried a little bit around with animations in the HTML5 canvas element and want to share some simple code with all of you wanting to know how animations in a canvas work. The example will use image sprites for the animation width a width and height of 48×48 pixels.

The following code will not be as optimized as it could be, because I think for the educational purpose it’ll be enough and the optimization and customization should be on you. As always I will not explain how to code at all and expect knowledge in HTML, CSS and Javascript programming. Also, you should know about basic game techniques e.g. game loops, sprites, frames and surfaces.

Before we see the code let’s have a peek at the final result:


Refresh the page if you don't see the example above!

But now let’s begin…

First of all, we need a basic html header like

<!DOCTYPE html>
<html><head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <style type="text/css">
    #screen {
      background: url('images/bg.png') lightblue;
    }
  </style>
</head>

As you can see, I already added some style that we’ll use later. Before we set the body, let’s add some javascript to the header first. What we need is a sprite class, that organizes the drawing and animation and some routine to run the game. In addition I added a function to print out a status message.

The full header looks like this:

<!DOCTYPE html>
<html><head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <style type="text/css">
    #screen {
      background: url('images/bg.png') lightblue;
    }
  </style>
  <script>
    // Simple sprite class
    function Sprite(args) {
      this.image = new Image();
      this.image.src = args.imgSrc;
      this.x = args.x  || (args.screen.width/2)-(args.spw/2);
      this.y = args.y || (args.screen.height-args.spw);
      this.imgFrames = args.frames || 1;
      this.frame = 0;
      // Draw the sprite to the screen
      this.Draw = function() {
        ctx.drawImage(this.image, this.frame, 0, args.spw,
                      args.spw, this.x, this.y, args.spw, args.spw);
        this.frame += 48;
        if( this.frame >= this.image.width ) this.frame = 0;
      };
    };

    // Display status message
    function Status(ticks) {
      var el = document.getElementById('status');
      el.innerHTML = 'Ticks: '+ticks;
    }

    // Main function to call
    function Run() {
      ctx.clearRect(0,0, screen.width, screen.height);
      ticks++;
      Status(ticks);
      sprite.Draw();
    }
  </script>
</head>

The first thing in the script block is the sprite class, which takes an object of parameters as an argument. The parameters are the image source file name, position, frame count and sprite width. It has only one function, but for our purpose we don’t need more. If you want to do more complex things with that, you should maybe seperate the animation in a seperate function and add a real frame limiter. In this example we don’t need a frame limiter.

Next, you see the simple debug output function and finally the main Run function which will be called via window.setInterval later. This function only increments the ticks, prints out the debug message and calls the Draw function of our sprite.

The image used for this example is:

HTML5 animation sprite

Now, lets see what the rest of the document looks like:

<body>
  <div style="margin: 0 auto; width: 320px;">
    <canvas id="screen" width="320" height="120"></canvas>
    <p id="status"></p>
  </div>
  <script>
    // Fetch the canvas element and context
    var screen = document.getElementById('screen');
    var ctx = screen.getContext('2d');  

    // Set ticks to 0 and initialize options array for our sprite
    var ticks = 0;
    var spriteOptions = {
      screen: screen,
      imgSrc: 'images/run2.png',
      spw: 48,
      frames: 10
    };

    // Initialize the sprite and run the demo
    var sprite = new Sprite(spriteOptions);
    window.setInterval(Run, 60);
  </script>
  <noscript>You need javascript to run the demo!</noscript>
</body></html>

In the body section we first see the canvas and the status paragraph element followed by another block of javascript. This block only defines some variables we need, like fetching the canvas element and its context or set the sprite options. This code should be self explanatory.

Last thing in the block is the definition of our sprite object and the call of window.setInterval with the arguments of our Run function and a timeout of 60 milliseconds. This timeout is more or less the frame limiter for this example as it runs the example with the same speed on every machine.

That’s all! Now you know how to create basic animations, it’s on you to extend the function and create your own! 😉

Here’s the complete code:

<!DOCTYPE html>
<html><head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <style type="text/css">
    #screen {
      background: url('images/bg.png') lightblue;
    }
  </style>
  <script>
    // Simple sprite class
    function Sprite(args) {
      this.image = new Image();
      this.image.src = args.imgSrc;
      this.x = args.x  || (args.screen.width/2)-(args.spw/2);
      this.y = args.y || (args.screen.height-args.spw);
      this.imgFrames = args.frames || 1;
      this.frame = 0;
      // Draw the sprite to the screen
      this.Draw = function() {
        ctx.drawImage(this.image, this.frame, 0, args.spw,
                      args.spw, this.x, this.y, args.spw, args.spw);
        this.frame += 48;
        if( this.frame >= this.image.width ) this.frame = 0;
      };
    };

    // Display status message
    function Status(ticks) {
      var el = document.getElementById('status');
      el.innerHTML = 'Ticks: '+ticks;
    }

    // Main function to call
    function Run() {
      ctx.clearRect(0,0, screen.width, screen.height);
      ticks++;
      Status(ticks);
      sprite.Draw();
    }
  </script>
</head>
<body>
  <div style="margin: 0 auto; width: 320px;">
    <canvas id="screen" width="320" height="120"></canvas>
    <p id="status"></p>
  </div>
  <script>
    // Fetch the canvas element and context
    var screen = document.getElementById('screen');
    var ctx = screen.getContext('2d');  

    // Set ticks to 0 and initialize options array for our sprite
    var ticks = 0;
    var spriteOptions = {
      screen: screen,
      imgSrc: 'images/run2.png',
      spw: 48,
      frames: 10
    };

    // Initialize the sprite and run the demo
    var sprite = new Sprite(spriteOptions);
    window.setInterval(Run, 60);
  </script>
  <noscript>You need javascript to run the demo!</noscript>
</body></html>

 

Similar Posts:

  • Regine rodriguez

    wow! its nice