Simple animations using JavaScript

This tutorial explains how to use the HTML5 canvas element and JavaScript to animate a div in a webpage. Below is a preview of what the animation will look like. Scroll down to see the code.


Refer to the comments in the code below to find out what is happening on each line.

<title>My animation</title>
<style type="text/css">
 /* simple box */
 position:absolute; /* The element is positioned relative to its first positioned (not static) ancestor element */
 top:30px; /* This is the position of the box from the top */
 width:200px; /* This is the width of the box */
 line-height:20px; /* This is the height of the box */
 background:#58FA82; /* This is the background colour of the box */
 border:1px solid #0B610B; /* This is the border thickness and border colour of the box */
 padding:10px; /* This is the padding amount around the text in the box */
 /* Hint: Get colour codes from */
<script type="text/javascript">
var box ; // create the variable we will use as the object to animate
function doMove() { = parseInt('px'; // parseInt parses a string and returns an integer, moves 1 pixel from left
 setTimeout(doMove,20); // call doMove in 20 milliseconds
function init() {
 box = document.getElementById('animatedBox'); // get the "box" object = '0px'; // set its initial position to 0px
 doMove(); // call the doMove function to start animating!
window.onload = init; // load the init function when the page loads
<div id="animatedBox">
 <b>My animation</b>

Next tutorial: Animating (moving) an image using JavaScript