The HTML5 Canvas Animation Allows You to Program Animations For Your Website

flash vs html5If animation excites you, you should be thrilled at the release of HTML5. HTML5 is the latest release of HTML, the core technology that powers the internet. HTML5 incorporates elements of HTML and XHTML making it the most powerful version HTML has released to date. One of the aims of HTML5 is to support various multimedia applications. The new elements that HTML5 offers, makes adding animated elements to your website easier than ever.

To get a jumpstart on your HTML5, try the HTML5 Beginners Crash Course today and learn about the new powerful features that HTML5 has to offer.

As mentioned above, HTML5 offers a host of new features that make adding animation to your website really simple. One of these elements is the introduction of the canvas element, which essentially allows you to create a canvas on your HTML page that can be used to draw elements.

This tutorial will show you how to use the canvas element to animate a shape and it also includes an example of how to animate text using the HTML5 canvas element. To follow the tutorial and the concepts in the tutorial, I suggest you have a solid foundation in HTML5 Fundamentals.

Create a simple canvas

The first step to creating an animation in HTML5 is to create a canvas on your web page. The canvas element in HTML5 creates an area that allows for the drawing of graphics on the fly using script, normally JavaScript. The canvas element is a container for the graphics. Canvas also has several methods for drawing circles, rectangles, boxes and paths as well as adding images. The canvas represents a two dimensional grid with the upper left coordinates being zero zero.

To create a canvas you need to use the canvas element id and then set the height and width of the canvas you want to create. Take a look at the following example script to draw a simple canvas:

<html>

<head>

    <title>Our First Canvas</title>

    // Use the style settings to set the border width and style for our canvas

       <style>

        canvas{border: 3px solid #bbb;}

        .subdiv{width: 320px;}

        .text{margin: auto; width: 290px;}

       </style>

  </head>

  <body>

    <div>

        // Use the canvas element id to create our canvas 300 wide by 200
            // pixels high

           <canvas id=”MyCanvas1″ width=”300″ height=”200″>

        This browser or document mode doesn’t support canvas object

        </canvas>

        <p>

           Our First canvas

        </p>

    </div>

</body>

</html>

The output of the above code is:

Create a canvas and add text

Now that you know how to create a simple canvas, we can add some text to our canvas and then animate the text using JavaScript. We are going to use the fillText and font methods of canvas to write the text in our canvas. The font method allows you to set the font properties of your text whereas the fillText method allows you to specify the text you want to write as well as the start height and width of the text.

Take a look at the following script to draw the text on our canvas:

<html>

<head>

   <title>Text Animation</title>

    <style>

       // Use the style settings to set the border width and
             // style for our canvas

        canvas{border: 1px solid #bbb;}

        .subdiv{width: 320px;}

        .text{margin: auto; width: 290px;}

    </style>

  <script type=”text/javascript”>

  // Create a variable to store the canvas

  var can ;

  function init()

    {

        //Create the canvas and assign it to the variable

        can = document.getElementById(“MyCanvas”);

      ctx = can.getContext(“2d”);

        // Use the methods to set the color, font and alignment

           ctx.fillStyle = “blue”;

      ctx.font = “20pt Verdana”;

   ctx.textAlign = “center”;

   ctx.textBaseline = “middle”;

        // Use the filltext method the create the text

    ctx.fillText(“Welcome”, 140, 100);

   }

  </script>

  </head>

<body onload=”init();”>

    <div>

        <canvas id=”MyCanvas” width=”300″ height=”200″>

          This browser or document mode doesn’t support canvas object

         </canvas>

        <p>Our first canvas text example</p>

   </div>

</body>

</html>

 

The output of the above would look like this:

Now that we have created a canvas and written some text on our canvas it’s time to animate the text.

Create a function to keep redrawing the text

To create an animation effect using JavaScript is a lot like creating an animation using the flipbook technique. To create an animation we need to draw the text, then clear the text, move the location slightly and then redraw the text. To achieve this we are going to create a JavaScript function that draws, clears, move and redraws the text.

The following script will move the text from the left hand side of the screen to the right hand side of the screen

<html>

<head>

 <title>Text Animation</title>

 <style>

canvas{border: 1px solid #bbb;}

    .subdiv{width: 320px;}|

.text{margin: auto; width: 290px;}

 </style>

<script type=”text/javascript”>

  var can, ctx, step, steps = 0, delay = 20;

  function init()

  {

     //Create the canvas and assign it to the variable

        can = document.getElementById(“MyCanvas1”);

        ctx = can.getContext(“2d”);
     //Create the font and alignment of the text on the canvas

     ctx.fillStyle = “blue”;

     ctx.font = “20pt Verdana”;

     ctx.textAlign = “center”;

     ctx.textBaseline = “middle”;
     // Use the step variable to change the position where the
     // test is written

     step = 0;

     steps = can.width + 50;

     RunTextLeftToRight();

  }

  function RunTextLeftToRight()

  {

     step++;
      //Clear the previous screen

     ctx.clearRect(0, 0, can.width, can.height);

     ctx.save();

     ctx.translate(step, can.height / 2);
     // Write Welcome on the screen at the new position

      ctx.fillText(“Welcome”, 0, 0);

     ctx.restore();

   if (step == steps)

         step = 0;

      if (step < steps)

            var t = setTimeout(‘RunTextLeftToRight()’, delay);

        }

    </script>

</head>

<body onload=”init();”>

   <div>

        <canvas id=”MyCanvas1″ width=”300″ height=”200″>

       This browser or document mode doesn’t support canvas object

        </canvas>

       <p>

          Example 1 – Marquee Text left to right – scrolling text

           </p>

      </div>

</body>

</html>

 

The output of the above would look like this:

Unfortunately the article doesn’t show the animation but you can see that the text has moved from its original position. The above would result in an animated text that scrolls from left to right across the screen.

You have created your first animated scrolling text element on a webpage using HTML5. To learn how to design websites using HTML and CSS, sign up for the HTML5 & CSS3 Site Design course from udemy.

Now that we have animated text, let’s look at how to draw and animate an object.

Draw a regular square using HTML5

The process of animating a drawing element like a rectangle is the same process we used to animate the text. To create an animated rectangle, we need to use the fillRect property to draw the rectangle first before we can animate it.

Take a look at the following code to draw the rectangle:

<!DOCTYPE HTML>

<html>

 <head>

 </head>

<body>

<canvas id=”myCanvas” width=”578″ height=”200″></canvas>

 

<script>

//Create the canvas and assign it to the variable

     var canvas = document.getElementById(‘myCanvas’);

  var context = canvas.getContext(‘2d’);

  // Use the rectangle properties to draw and fill a rectangle

  context.rect(188, 50, 200, 100);

  context.fillStyle = ‘blue’;

  context.fill();

  context.lineWidth = 7;

  context.strokeStyle = ‘black’;

  context.stroke();

</script>

 </body>

</html>

The output of the above code would look like this:

Animate the square

Now that we know how to draw the square we will use the x value of the rectangle to redraw the rectangle in a slightly new position each time:

<html>

  <head>

  <style type=”text/css”>

     canvas{ border:#666 1px solid;}

  </style>

     <script type =”application/javascript” language=”javascript”>

   //

        function draw(x, y)

  {

     //Create the canvas and assign it to the variable

           var canvas = document.getElementById(“canvas”);

           var ctx = canvas.getContext(“2d”);

        // clear the previous rectangle that was drawn  

       ctx.clearRect(0, 0, 550, 400);

          // Draw the new rectangle using the rectFill property using the

          // new x coordinate

           ctx.fillRect(x, 50, 200, 100);

           ctx.fillStyle =’blue’;

         // Once the rectangle is drawn increase the value of x

          // so its ready for new rectangle to be drawn

           x+=1;

          // Create a loop based on setTimeOut to redraw the new

          // rectangle

           var loopTimer = setTimeout(‘draw(‘+x+’,’+y+’)’, 20);

          }

     </script>

  </head>

  <body>

  <button onclick=”draw(0,0)”>Draw</button>

     <canvas id = “canvas” width =”550″ height =”400″></canvas>

</html>

The output of the above can be seen below:

Unfortunately, you can’t see the animation as such but you can see the rectangle has moved. The output results in a rectangle that moves across the screen from left to right.

HTML5 offers powerful options for creating interactive applications

As you can see from the above, the combination of HTML5 and JavaScript makes for a powerful combination to allow programmers to create applications. If the above animation excites you, sign up to learn to Create a HTML5 Game from Scratch.