Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Simple Linear Animation Using HTML5 Canvas

5.00/5 (1 vote)
15 Feb 2013CPOL 15.6K  
Linear Animation By HTML5 Canvas

Introduction

We all know about the growing demand of HTML5 Canvas. It is just being called a plug-in killer for the next generations of Web world. Anyway here I will show you how to create a simple linear animation with HTML5 canvas.

Before going to that I must describe what canvas is. Canvas is just an HTML element which is used to draw things and do animation in browser itself with just JavaScript .

To create an animation, we first need to initialize canvas and then set context too. Then with the help of JavaScript we will draw a rectangle in side the canvas with context and we will repeatedly draw it by putting it inside a loop and clearing the previous drawn. So that finally it looks like an rectangle is moving from left to right. We will set the loop timer such that it will look smooth. Below is the HTML code.

Using the code 

C#
<html>
   <head>
      <style type="text/css">
         canvas{ border:#666 1px solid;}
      </style>
      <script type ="application/javascript" language="javascript">
         //This draw function draw the rectangle for every new position and delete previous
         function draw(x, y) {
               // In the below code we are initialising canvas by the DOM .
               var canvas = document.getElementById("canvas");
               // Here we are creating context by passing 2d parameter and through the context we will
               // do all the stuff.
               var ctx = canvas.getContext("2d");
               ctx.save();
               // Each time before drawing the Rectangle in a new position the previous one was deleted
               ctx.clearRect(0, 0, 550, 400);
               ctx.fillstyle = "rgba(0,200,0,1)";
               //We will create an rectangle whose X cordinate we will change in a loop .
               ctx.fillRect(x, 20, 50, 50);
               ctx.restore();
               x+=1;
               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>

Just copy and paste it in an HTML file and run it. Are you seeing it? Hope you enjoyed.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)