Home » Tutorials » JavaScript » HTML5 Canvas For Absolute Beginners – Part 4

HTML5 Canvas For Absolute Beginners – Part 4

HTML5 Canvas For Absolute Beginners – Part 4

  • Stumble it!
  • Share

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!

The idea

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.

HTML5 Canvas Bouncing Ball Tutorial

Interesting? Let’s start our tutorial now!

HTML

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.

JavaScript

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

  • canvas – This variable will be use as a reference to the canvas object
  • ctx – A variable to hold the value of the context
  • x – A x-axis value (the value must be same with the canvas’s width)
  • y – A y-axis value (the value must be same with the canvas’s height)
  • mx – A prefix x-axis value for animation
  • my – A prefix y-axis value for animation
  • WIDTH – Width of the canvas
  • HEIGHT – Height of the canvas

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.

  • beginPath() – allow us to start a new path
  • arc() – to define the size and shape of circle
  • fill() – Fill the circle with color (default color is black)

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.

HTML5 Canvas Arc

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:

HTML5 Canvas Animated Line

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 :)

HTML5 Canvas Bouncing Ball

Final Code

<!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!

Other HTML5 and CSS3 tutorial


  • How To Create jQuery Password Strength Indicator in 10 Minutes!
  • Make A jQuery Sticky Header In 5 Minutes
  • Create Sequential Animations in jQuery

  • http://www.facebook.com/jennytoribio Jenny Toribio

    =) Thanks for Sharing!! Really easy!!
    Check where it says:
    y – A y-axis value (the value must be same with the canvas’s width)
    Width is Height!
    Also
    Our circle has been defined by ‘circle(x, y, 20);’, which means that, the circle has a radius of 10 // U Mean 20 Right?

    and Again! Thanks a lot!

    • http://www.onlywebpro.com onlyWebPro

      Hi Jenny,

      Thanks for your comment. The article has been updated.

      Thanks again :)

  • Carmelo

    Nice tutorial :)
    A bit of nostalgia in this little intro i created in pure HTML 5, take a look :)

    http://www.appnjoy.com/OLD_WEBSITE_2010/Amiga_Demo/index.html

    Cheers
    Carmelo.

    • http://www.onlywebpro.com onlyWebPro

      Hi Carmelo,

      Wow! You have done a great job! You are feel free to share your canvas coding experience here or on our Facebook fan page!

      Keep it Up :)

      Regards,
      The Management of onlyWebPro.com

  • Fianna

    Thank you very much! This tutorial helped a lot!

    I am new to all this, but I really want to learn. I managed to do this, but I can’t seem to change the collor of the circle. How do I do this?

  • Fianna

    Thank you very much! This tutorial helped a lot!

    I am new to all this, but I really want to learn. I managed to do this, but I can’t seem to change the collor of the circle. How do I do this?

  • George

    I don’t want bounce affect. I am trying to achieve more like a penalty shot at a soccer cross bar. which means it should stop at a point than buncing. Any hint would be great. Thanks.

    • http://www.onlywebpro.com onlyWebPro

      Hi George,

      Thanks for reading the article. For your problem, you can easily achieve it by removing the if condition in the function of draw.

      Remove the following line of code:

      if (x + mx > WIDTH || x + mx HEIGHT || y + my < 0)
      my = -my;

      x += mx;
      y += my;

      }

      Hope it helps!

      Stay connected with us via Facebook Fan Page, Twitter or Google Plus Page.

      Regards,
      The Management of onlyWebPro.com

  • Zumzza

    Hi!
    How to slow down and stop the animation as a real ball ?
    Thanks.

  • Brishti55

    hi! could you please tell me how can i change the color of ball?? thanks ^.^

  • Ken

    Magnificent tutorial! Literally the only site on the internet that has given me an insight to collision in canvas. However, what i’d like to ask is how i could make it animate only a certain distance cos realized that you made the animation infinite. So lets say i press the right arrow, i just want it to move two px to the left. how would i do this? also can i use this algorithm on a div shape, like a square.

    • http://www.onlywebpro.com onlyWebPro

      Hi Ken,

      Thank you for your comment. :)

      Regarding your question, I strongly recommend you to read our tutorial – ”

      Most Easiest & Simplest Way to Create a Game Using HTML5 Canvas”. We do have cover animate the object in canvas with certain distance.

      Please follow us either on facebook page, twitter, or Google+ page.

      Regards,
      Management of onlyWebPro.com

    • http://www.onlywebpro.com onlyWebPro

      Here is the link of “Most Easiest & Simplest Way to Create a Game Using HTML5 Canvas”

      http://www.onlywebpro.com/2012/01/14/most-easiest-simplest-way-to-create-a-game-using-html5-canvas/

  • sakthivel

    Before animation itself , i want to create a full circle in the canvas area(Dont want to hidden).. Is it possible?

    • http://www.onlywebpro.com onlyWebPro

      Hi sakthivel,

      Hmm… From my understanding based on your question, you could just remove the setInterval method, and change some settings of the circle such as x, y property and trigger the draw function in “init function”.

      Hope this can help to solve your problem. cheers!

Android, iOS Development Tutorials