Click here to Skip to main content
13,254,154 members (61,366 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


1 bookmarked
Posted 15 Feb 2013

Simple Linear Animation Using HTML5 Canvas

, 15 Feb 2013
Rate this:
Please Sign up or sign in to vote.
Linear Animation By HTML5 Canvas


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 

      <style type="text/css">
         canvas{ border:#666 1px solid;}
      <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");
               // 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);
               var loopTimer = setTimeout('draw('+x+','+y+')', 20);
      <button onclick="draw(0,0)">Draw</button>
         <canvas id = "canvas" width ="550" height ="400"></canvas>

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


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


About the Author

You may also be interested in...


Comments and Discussions

-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.171114.1 | Last Updated 15 Feb 2013
Article Copyright 2013 by arnavs
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid