HTML5 Canvas Tutorial With Examples

The canvas concept was originally introduced by Apple to be used in Mac OS X WebKit to create dashboard widgets. Before the arrival of canvas, you could only use drawing APIs in a browser through plugins such as Adobe plugins for Flash and Scalable Vector Graphics (SVG), Vector Markup Language (VML) only in Internet Explorer, or other clever JavaScript hacks.

You will learn the basic concepts of HTML5 canvas and be able to draw following diagram at the end of this tutorial. I hope you will enjoy it.

HTML5 Canvas Tutorial

What is Canvas

When you use a canvas element in your web page, it creates a rectangular area on the page. By default, this rectangular area is 300 pixels wide and 150 pixels high, but you can specify the exact size and set other attributes for your canvas element. Following code snippets shows the most basic canvas element that can be added to an HTML page.

<canvas></canvas>

Once you have added a canvas element to your page, you can use JavaScript to manipulate it any way you want. You can add graphics, lines, and text to it; you can draw on it; and you can even add advanced animations to it.

Canvas Coordinates Understanding

This is the very important part of this tutorial, I will say this part is the Heart of HTML5 Canvas Tutorial.

Coordinates in a canvas start at x=0,y=0 in the upper-left corner – which we will refer to as the origin and increase (in pixels) horizontally over the x-axis and vertically over the y-axis.

Let’s understand the concept canvas coordinates via following diagram,

Canvas Html5 Tutorial

I will draw a rectangle box of 200×200 pixels having vertical and horizontal lines. Let’s dissect the above diagram,

  • Top Left Corner (Origin): x = 0, y = 0
  • x values will increase horizontally, as you will observe x=100 at the Top Middle, and x = 200 at Top Right
  • y values will increase vertically, as you will observe y=100 at the Middle Left and y=200 at Bottom Left

CSS and Canvas

As with most HTML elements, CSS can be applied to the canvas element itself to add borders, padding, margins, etc. Additionally, some CSS values are inherited by the contents of the canvas; fonts are a good example, as fonts drawn into a canvas default to the settings of the canvas element itself.

Adding a Canvas to a Page

Adding a canvas element in an HTML page is pretty straight-forward. Let’s draw a canvas 200 × 200 pixel rectangle on your page, and style with red border to make it visible on the page.

Please use Google Chrome, Mozilla Firefox, Opera or Safari to learn the tutorial, as these browsers have built-in support for HTML5 Canvas. I will explain, how to make HTML5 Canvas compatible to Internet Explorer at the end of tutorial

<canvas id="c" style="border: 1px solid #F00;" width="200" height="200"></canvas>

Output

Canvas With Red Border

Note the addition of the ID diagonal to make it easy to locate this canvas element programmatically. An ID attribute is crucial to any canvas because all the useful operations on this element must be done through scripting. Without an ID, you will have difficulty locating the element to interoperate with it.

Create a Context Variable

You first gain access to the canvas object by referencing a particular canvas’s ID value. In this tutorial, the ID is “c”. Next, you create a context variable and you call the canvas object’s getContext method, passing in the type of canvas you are looking for. You pass in the string “2d” to get a two-dimensional context – the only available context type at this time. Code snippet is,

<script>

window.onload = function() {

// Get the canvas element and its drawing context
  var canvas = document.getElementById('c');
  var context = canvas.getContext('2d');

};

</script>

Canvas Drawing Methods

You then use the context to perform drawing operations. In this case, you can create the diagonal line by calling three methods—beginPath, moveTo, and lineTo—passing in the line’s start and end coordinates.

The drawing methods moveTo and lineTo do not actually create the line; you finalize a canvas operation and draw the line by calling the context.stroke(); method.

<script>

window.onload = function() {

  // Get the canvas element and its drawing context
  var canvas = document.getElementById('c');
  var context = canvas.getContext('2d');

  context.beginPath();
  context.moveTo(0, 0);
  context.lineTo(200, 200);
  context.stroke();

};

</script>

Draw First Line

I hope you have learned the basic concepts of canvas till now. Now i am going to draw first line on our canvas with the simple but interesting explanation.

1. Usage of Canvas Element

<canvas id="c" style="border: 1px solid #F00;" width="200" height="200"></canvas>

2. Create Context Variable

<script>
window.onload = function() {
var canvas = document.getElementById('c');
var context = canvas.getContext('2d');
}
</script>

3.  Drawing Method: beginPath()

context.beginPath();

4. Origin Coordinates of Line: context.moveTo()

We will start (originate) our first line from the Top Left corner. Guess what will be the coordinates according to diagram. Great, the coordinates will be x=0 and y=0

context.moveTo(0, 0);

5. End Coordinates of Line: context.lineTo()

According to diagram our first line will end up at the Right Bottom Corner, so the coordinates will be x=200 and y = 200

context.lineTo(200, 200);

6. Draw Line: context.stroke();

We have determined our coordinates, and now it is time to draw our first line.

context.stroke();

First Line – Origin: Top Left / End: Bottom Right

Now we will draw a first line whose origin position will be Top Left and ending position will be Bottom Right. Guess to find Origin and End coordinates, and code snippet will be,

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>HTML5 Canvas</title>
<script>

window.onload = function() {

  	// Get the canvas element and its drawing context
	var canvas = document.getElementById('c');
	var context = canvas.getContext('2d');

	/*
	|---------------------
	| Origin: Top Left
	| End: Bottom Right
	|---------------------
	*/

	context.beginPath();
	context.moveTo(0, 0);
	context.lineTo(200, 200);
	context.stroke();

};

</script>
</head>
<body>
<canvas id="c" style="border: 1px solid #F00;" width="200" height="200"></canvas>
</body>
</html>

Output

HTML5 Canvas First Line

Second Line – Origin: Top Middle / End: Bottom Middle

Now we will draw a second line whose origin position will be Top Middle and ending position will be Bottom Middle. Guess to find Origin and End coordinates, and code snippet will be,

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>HTML5 Canvas</title>
<script>

window.onload = function() {

  	// Get the canvas element and its drawing context
	var canvas = document.getElementById('c');
	var context = canvas.getContext('2d');

	/*
	|---------------------
	| Origin: Top Left
	| End: Bottom Right
	|---------------------
	*/

	context.beginPath();
	context.moveTo(0, 0);
	context.lineTo(200, 200);
	context.stroke();

	/*
	|---------------------
	| Origin: Top Middle
	| End: Bottom Middle
	|---------------------
	*/

	context.save();
	context.beginPath();
	context.moveTo(100, 0);
	context.lineTo(100, 200);
	context.stroke();
	context.restore();

};

</script>
</head>
<body>
<canvas id="c" style="border: 1px solid #F00;" width="200" height="200"></canvas>
</body>
</html>

Output

Third Line – Origin: Top Right / End: Bottom Left

Now we will draw a third line whose origin position will be Top Right and ending position will be Bottom Left. Guess to find Origin and End coordinates, and code snippet will be,

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>HTML5 Canvas</title>
<script>

window.onload = function() {

  	// Get the canvas element and its drawing context
	var canvas = document.getElementById('c');
	var context = canvas.getContext('2d');

	/*
	|---------------------
	| Origin: Top Left
	| End: Bottom Right
	|---------------------
	*/

	context.beginPath();
	context.moveTo(0, 0);
	context.lineTo(200, 200);
	context.stroke();

	/*
	|---------------------
	| Origin: Top Middle
	| End: Bottom Middle
	|---------------------
	*/

	context.save();
	context.beginPath();
	context.moveTo(100, 0);
	context.lineTo(100, 200);
	context.stroke();
	context.restore();

	/*
	|---------------------
	| Origin: Top Right
	| End: Bottom Left
	|---------------------
	*/

	context.save();
	context.beginPath();
	context.moveTo(200, 0);
	context.lineTo(0, 200);
	context.stroke();
	context.restore();

};

</script>
</head>
<body>
<canvas id="c" style="border: 1px solid #F00;" width="200" height="200"></canvas>
</body>
</html>

Output

HTML5 Third Line

Fourth Line – Origin: Middle Left / End: Middle Right

Now we will draw a fourth line whose origin position will be Middle Left and ending position will be Middle Right. Guess to find Origin and End coordinates, and code snippet will be,

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>HTML5 Canvas</title>
<script>

window.onload = function() {

  	// Get the canvas element and its drawing context
	var canvas = document.getElementById('c');
	var context = canvas.getContext('2d');

	/*
	|---------------------
	| Origin: Top Left
	| End: Bottom Right
	|---------------------
	*/

	context.beginPath();
	context.moveTo(0, 0);
	context.lineTo(200, 200);
	context.stroke();

	/*
	|---------------------
	| Origin: Top Middle
	| End: Bottom Middle
	|---------------------
	*/

	context.save();
	context.beginPath();
	context.moveTo(100, 0);
	context.lineTo(100, 200);
	context.stroke();
	context.restore();

	/*
	|---------------------
	| Origin: Top Right
	| End: Bottom Left
	|---------------------
	*/

	context.save();
	context.beginPath();
	context.moveTo(200, 0);
	context.lineTo(0, 200);
	context.stroke();
	context.restore();

	/*
	|---------------------
	| Origin: Middle Left
	| End: Middle Right
	|---------------------
	*/

	context.save();
	context.beginPath();
	context.moveTo(0, 100);
	context.lineTo(200, 100);
	context.stroke();
	context.restore();

};

</script>
</head>
<body>
<canvas id="c" style="border: 1px solid #F00;" width="200" height="200"></canvas>
</body>
</html>

Output

HTML5 Final Diagram

Browser Support for HTML5 Canvas

With the exception of Internet Explorer, all browsers now provide support for HTML5 Canvas. However, there are some parts of the specification that were added later that are not supported as widely. An example of this is the Canvas Text API. As a whole, however, the specification is at a very advanced stage and is unlikely to change a whole lot. As shown in the following table, HTML5 Canvas is already supported in many browsers at the time of this tutorial.

BrowserDetails
Google ChromeSupported in version 1.0 and greater
Mozilla FirefoxSupported in version 1.5 and greater
Internet ExplorerNot supported
OperaSupported in version 9.0 and greater
SafariSupported in version 1.3 and greater

Internet Explorer Compatibility

As you can see, HTML5 Canvas is supported in all the browsers except Internet Explorer. If you want to use canvas in Internet Explorer, you can use the open-source project explorercanvas. Download ExplorerCanvas.

Explorer is the current browser and include a script tag in your web pages (head section) to launch explorercanvas, such as the following:

<!--[if IE]><script src="excanvas.js"></script><![endif]-->

HTML5 Canvas Cross Browser Compatibility

Here is a full code that will work in all browsers (You have to download ExplorerCanvas for Internet Explorer)

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>HTML5 Canvas</title>
<!--[if IE]><script src="excanvas.js"></script><![endif]-->
<script>

window.onload = function() {

  	// Get the canvas element and its drawing context
	var canvas = document.getElementById('c');
	var context = canvas.getContext('2d');

	/*
	|---------------------
	| Origin: Top Left
	| End: Bottom Right
	|---------------------
	*/

	context.beginPath();
	context.moveTo(0, 0);
	context.lineTo(200, 200);
	context.stroke();

	/*
	|---------------------
	| Origin: Top Middle
	| End: Bottom Middle
	|---------------------
	*/

	context.save();
	context.beginPath();
	context.moveTo(100, 0);
	context.lineTo(100, 200);
	context.stroke();
	context.restore();

	/*
	|---------------------
	| Origin: Top Right
	| End: Bottom Left
	|---------------------
	*/

	context.save();
	context.beginPath();
	context.moveTo(200, 0);
	context.lineTo(0, 200);
	context.stroke();
	context.restore();

	/*
	|---------------------
	| Origin: Middle Left
	| End: Middle Right
	|---------------------
	*/

	context.save();
	context.beginPath();
	context.moveTo(0, 100);
	context.lineTo(200, 100);
	context.stroke();
	context.restore();

};

</script>
</head>
<body>
<canvas id="c" style="border: 1px solid #F00;" width="200" height="200"></canvas>
</body>
</html>

I hope you have enjoyed the HTML5 canvas tutorial. You may also be interested to master for rounded corners using CSS without images. Don’t forget to write your comments and subscribe your email to stay up to dated with fresh and professional tutorials and resources.

2 thoughts

Comments are closed.