HTML 5 Canvas Demos | The Basics

By | May 10, 2011

Today we’re going to look at the golden boy of HTML5 codes, the canvas tag. This is the thing that has caught most peoples attention. The ability to draw with javascript and then animate is very powerful and some very clever people have been creating games, apps and other tools with it. So what are we going to do I hear you ask? First we’re going to go through the basics (drawing lines and shapes), then we’re going to have a look at more complex stuff (gradients, animation and interactivity) then at the end we’re going to create a drawing application (and hopefully in the process bring me some traffic and recognition for my amazing drawing app). Anyway I digress, lets get on with it.

View Demo 1View Demo 2Download Source

Getting Started

Ok getting started is the (really) easy part.








 


So canvas is just a simple html tag. One thing to note is that in my tests you need to put the width and height here in the html and not in the css as with other elements because the stuff that you draw on to the canvas blurs if you set the size with css. It’s as if the canvas is set to a default size and you stretch it with css and the pixel count stays the same. Ok so we have our canvas tag but if you test this there will be nothing there. Thats because canvas has is own javascript API (Application Programming Interface) which allows us to do all the cool things. So sorry guys if you haven’t wanted to learn javascript before trust me, your going to have to now.
So where do we start? Well as you can see above I have linked to a file called canvas.js, lets have a look in that and see how its structured.

window.onload=(function() {
        var c = document.getElementById('canvas');	
	if (c.getContext){
	  var ctx = c.getContext("2d");
	} else {
	  alert("Your Browser doesn't support canvas!");
	}				
})();

So this is the basic code and the beginning of our file. We wait for the window to load and then we look through the document for the element with the id of canvas which is surprisingly our canvas element. Then we check to see if the browser has support for the getContext object. If so we create a context object. So now we have the context object we can start to do the magic.

Drawing a line

window.onload=(function() {
        var c = document.getElementById('canvas');	
	if (c.getContext){
	  var ctx = c.getContext("2d");
          ctx.moveTo(20,20);
	  ctx.lineTo(340,230);
	  ctx.stroke();
	}else{
	  alert("Your Browser doesn't support canvas!");
	}				
})();

So lets explain whats going on here. The first method .moveTo() is setting where the line starts from. The next method .lineTo() is where the line goes to. And basically stroke() draws the line on the canvas.

So thats ok but what about thickening up the line.

window.onload=(function() {
        var c = document.getElementById('canvas');	
	if (c.getContext){
	  var ctx = c.getContext("2d");
          ctx.moveTo(20,20);
	  ctx.lineTo(340,230);
          ctx.lineWidth = 10; 
	  ctx.stroke();
	}else{
	  alert("Your Browser doesn't support canvas!");
	}				
})();

So we add lineWidth and tell it how thick the line should be here we create 10px width line.
Thick line in Canvas
What about changing the colour?

window.onload=(function() {
        var c = document.getElementById('canvas');	
	if (c.getContext){
	  var ctx = c.getContext("2d");
          ctx.moveTo(20,20);
	  ctx.lineTo(340,230);
          ctx.lineWidth = 10;
          ctx.strokeStyle = "#ff0000"; 
	  ctx.stroke();
	}else{
	  alert("Your Browser doesn't support canvas!");
	}				
})();

Add strokeStyle and then the colour. Easy.
red line in Canvas
There are 3 caps (ends) to the stroke square, round and butt. These are created using the following code.(This is just for square cap but the image has all the caps in). See the demos at the end for the full code.

window.onload=(function() {
        var c = document.getElementById('canvas');	
	if (c.getContext){
	  var ctx = c.getContext("2d");
          ctx.moveTo(20,20);
	  ctx.lineTo(340,230);
          ctx.lineWidth = 10;
          ctx.strokeStyle = "#ff0000";
          ctx.lineCap = "square";
	  ctx.stroke();
	}else{
	  alert("Your Browser doesn't support canvas!");
	}				
})();

Add lineCap and which ever line end you want.
lineCap in Canvas

Drawing a shape

So now we can draw strokes what about shapes? Firstly rectangles. We have to tell it where to start the shape then how big its going to be.

window.onload=(function() {
        var c = document.getElementById('canvas');	
	if (c.getContext){
	  var ctx = c.getContext("2d");
          ctx.beginPath();
	  ctx.rect(70, 70, 220, 100);
          ctx.lineWidth = 2;
	  ctx.strokeStyle = "#000000";
	  ctx.stroke();
	}else{
	  alert("Your Browser doesn't support canvas!");
	}				
})();

So as you can see we start with beginPath() we use this for all our shapes the we tell the context object that we are going to draw a rectangle with .rect and pass in parameters. The first 2 are where the rectangle should start and the second 2 are the width and height of the box. Then we give it a lineWidth and colour.

rectangle in Canvas

So we have our rectangle but its just an outline. How do we fill it in?

window.onload=(function() {
        var c = document.getElementById('canvas');	
	if (c.getContext){
	  var ctx = c.getContext("2d");
          ctx.beginPath();
	  ctx.rect(70, 70, 220, 100);
          ctx.fillStyle = "#ff0000";
    	  ctx.fill();
          ctx.lineWidth = 2;
	  ctx.strokeStyle = "#000000";
	  ctx.stroke();
	}else{
	  alert("Your Browser doesn't support canvas!");
	}				
})();

So we add the fillStyle where we declare the colour and then we call fill() to fill the rectangle with colour.

rectangle fill in Canvas
Ok so thats the rectangle what about a circle. Well this is slightly different. This is how the arc is created arc(x, y, radius, startAngle, endAngle, anticlockwise). We set the x and y co-ordinates of the centre of the circle(arc) then the radius, then how many degrees to run the arc through (in this case) 0 to 2 * Math.PI (or 360 degrees to me and you) then we tell it to draw anticlockwise(true) or clockwise(false).

window.onload=(function() {
        var c = document.getElementById('canvas');	
	if (c.getContext){
	  var ctx = c.getContext("2d");
          ctx.beginPath();
    	  ctx.arc(180, 125, 70, 0, 2 * Math.PI, false); 
	  ctx.fillStyle = "#ff0000";
	  ctx.fill();
	  ctx.lineWidth = 2;
	  ctx.strokeStyle = "#000000";
	  ctx.stroke();
	}else{
	  alert("Your Browser doesn't support canvas!");
	}				
})();

And what do we get.



Finally lets create a semi circle.

window.onload=(function() {
        var c = document.getElementById('canvas');	
	if (c.getContext){
	  var ctx = c.getContext("2d");
          ctx.beginPath();
	  ctx4.arc(180, 100, 70, 0, Math.PI, false);
	  ctx.closePath();
		 
	  ctx.lineWidth = 2;
	  ctx.fillStyle = "#ff0000";
	  ctx.fill();
	  ctx.strokeStyle = "#000000";
	  ctx.stroke();
	}else{
	  alert("Your Browser doesn't support canvas!");
	}				
})();

So here we create an arc but we do not complete the circle we only create half a circle then call the .closePath() method to create a semi circle then we fill it as before.

So there we are there’s the some of the basics. Next I will be delving further into the canvas api looking at gradients, interaction and animation. See you then.
View Demo 1View Demo 2Download Source

One thought on “HTML 5 Canvas Demos | The Basics

Leave a Reply

Your email address will not be published. Required fields are marked *