- Tutorials / JavaScript
- Wednesday, 20th Jul, 2011
Home » Tutorials » JavaScript » HTML5 Canvas For Absolute Beginners – Part 4
Welcome to the fourth part of the ‘HTML5 Canvas for Absolute Beginners’. In this tutorial, we will describe the animation in canvas. If you haven’t already, be sure to read the previous articles of this series first!
One of the features of HTML5 Canvas is allowing you to create animation without any third-party software. There are some rumors said that, HTML5 Canvas would take over Adobe Flash in very near future. While some of the web communities are arguing about the possibility. Today, we are not going to talk about the issues in this tutorial, but shows you the live demo that HTML5 Canvas can achieve with the help of JavaScript.
In this tutorial, we will describe the making of bouncing ball animation with purely HTML5 and JavaScript. The demo below give you an overview of the animation that we are going to build later.

Interesting? Let’s start our tutorial now!
First, create a valid HTML5 document as shown below:
<!DOCTYPE html>
<html>
<head>
<title>HTML5 Canvas For Absolute Beginners | onlyWebPro.com</title>
</head>
<body>
<canvas id="myCanvas" width="568" height="262">
<!-- Insert fallback content here -->
Sorry, your browser doesn't support canvas technology
</canvas>
</body>
</html>
There is a very important thing you need to keep in mind when creating a valid HTML5 document, which is ‘DOCTYPE’. W3C was suggesting to declare HTML5 document as shown above. Besides, it’s a good practice that always provide the fallback content or message to the browsers that do not support canvas technology.
Ok. We had done the HTML5 structure, let’s move on to the JavaScript section.
We are going to draw a circle on the canvas element by using JavaScript, so let’s start to define all the variables that we are going to use as shown below:
<script type="text/javascript"> var canvas; var ctx; var x = 568; var y = 262; var mx = 2; var my = 4; var WIDTH = 568; var HEIGHT = 262; </script>
Description of variables
Note: Place your JavaScript after the <canvas>, but before the </body> tag.
Ok, let’s create a function called ‘init()’, which is the function that we call to start everything.
<script type="text/javascript">
function init() {
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
return setInterval(draw, 20);
}
init();
</script>
First, initialize the ‘init()’ function and get access to the canvas object with the ID and define the context as 2d, which allow us to use the JavaScript Canvas function later. The next line use ‘setInterval(function, time)’ to call the ‘draw’ function every 20 milliseconds.
Next, create a function called ‘draw’ and insert it after the ‘init’ function that we declared just now. This function draw the circle and animate the circle for us.
function draw() {
circle(x, y, 20);
}
First of all, we create a circle by calling a ‘circle()’ function, and passing the parameters of x, y and the radius(size) to it, which we will define later as shown below:
function circle(x,y,r) {
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI*2, true);
ctx.fill();
}
To create a perfect circle, we have to begin drawing with ‘beginPath’ function, follow with ‘arc’ and ‘fill’ function.
You may not familiar to the ‘arc()’ function here. The ‘arc()’ function draw an arc. There are some parameters for this function, ‘arc(x, y, radius, startAngle, endAngle, anticlockwise)’. The x and y receive the coordinate value, raidus used to dfine the size of circle, startAngle is used to define the starting angle (degrees), endAngle is the end angle (in this case, we use 2*pi radians 360 degrees to create a perfect circle) and anticlockwise is a Boolean value which when true draws arc anticlockwise, otherwise in clockwise direction.
Save your document and preview it, you should get a perfect dark circle as shown below.

Note: You circle may hidden. Don’t worry, because the default x and y position are the width of the height of the canvas.
Ok, let’s move back to the ‘draw’ function that we have declared just now, and start to animate the circle. Our circle has been defined by ‘circle(x, y, 20);’, which means that, the circle has a radius of 10 and its origin is at (x,y). To move the circle, we need to pass in the value to the (x,y) parameters as shown below:
function draw() {
circle(x, y, 20);
if (x + mx > WIDTH || x + mx < 0)
mx = -mx;
if (y + my > HEIGHT || y + my < 0)
my = -my;
x += mx;
y += my;
}
The variables mx (with prefix value 2) and my (with prefix value 4) determine the changes of x and y on every 20 milliseconds). Besides, we have to make sure the circle stay within the canvas by checking its x and y value, to make sure not greater or less than the canvas size. Save your document and run it on browser, you should see something similar as below:

We suppose to create a bouncing circle for this tutorial right? Why it become an animated line? Don’t worry :p You just need a final step! To solve this problem, what you need to do is to create a ‘clear()’ function. We use the ‘clear()’ function to erase everything on the canvas for us, it helps to erase every single previous circle.
function clear() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
}
//init the clear at draw() function
function draw() {
clear();
}
Save your document again, run it and you should get a prefect bouncing circle

<!DOCTYPE html>
<html>
<head>
<title>HTML5 Canvas For Absolute Beginners | onlyWebPro.com</title>
</head>
<body>
<canvas id="myCanvas" width="568" height="262">
<!-- Insert fallback content here -->
Sorry, your browser doesn't support canvas technology
</canvas>
<script type="text/javascript">
var canvas;
var ctx;
var x = 568;
var y = 262;
var mx = 2;
var my = 4;
var WIDTH = 568;
var HEIGHT = 262;
function circle(x,y,r) {
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI*2, true);
ctx.fill();
}
function clear() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
}
function init() {
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
return setInterval(draw, 10);
}
function draw() {
clear();
circle(x, y, 20);
if (x + mx > WIDTH || x + mx < 0)
mx = -mx;
if (y + my > HEIGHT || y + my < 0)
my = -my;
x += mx;
y += my;
}
init();
</script>
</body>
</html>
In next tutorial, we will describe more HTML5 canvas related information. Stay tune!
PHP: Object Oriented Programming for Absolute Beginners
HTML5 Canvas For Absolute Beginners – Part 4
Introduction To Device Orientation With HTML5
CSS3: Spinner Animation
Solving CSS Float's Problem
Create Facebook App Style Slide-Out Navigation
Build Intelligent Layout Using CSS Calc() Property
Catch It!
Make A jQuery Sticky Header In 5 Minutes
Koubachi Web Game
HTML5 Brain Challenge - Maths Edition