HTML5 Canvas Tutorial: The Basics

canvas basics

A canvas is a rectangular HTML5 element in which you can make drawings and animations with Javascript. By default, the canvas element is 300 px wide by 150 px high, but you can customize it to whatever size. Below you can see how the HTML code of the canvas element looks like in its most basic form.

<canvas></canvas>

After placing the canvas element on the page, you can place drawings using Javascript , from simple, such as a simple line, to complicated. Also you can place animations within the canvas element. The canvas element is intended as an area for placing dynamically created drawings and animations and emphatically not for styling other HTML elements such as title heads. For this, you should use the elements specially designed for it (<h1>, <h2> etc).

To program within the canvas element you must first be carry out one essential act: calling the context in which you you want to apply certain actions.

document.createElement("canvas").getContext("2d");
or
var canvas = document.getElementById("Id-name");   
var context = canvas.getContext("2d");  

Checking for browser support

Because not yet all browsers (especially older versions of Internet Explorer) fully support , the canvas element, it is advisable to place alternative content (known as fallback content) for this kind of browsers, such as in the code below:

<canvas>
Update your browser for support of the canvas element
</canvas>

This is what you should should do at least. Another option is to use something like the javascript script below, which makes use of so-called object-detection:

try {
  document.createElement("canvas").getContext("2d");
  document.getElementById("support").innerHTML =
  "This browser supports HTML5 canvas";
  } catch (e) {
  document.getElementById("support").innerHTML = "HTML5 Canvas 
  is not supported by this browser.";
  }

The canvas coordinates

As can be seen in image 1, the canvas element has a coordinate system. The coordinates with x = 0 and y = 0, is written as (0.0) and also referred to as the origin, are located on the top left in the canvas element. Different from in a Cartesian coordinate system, in the canvas coordinate system the x-value element increases to the right and the y value increases downwardly. The coordinates (20,20) thus lie right below the origin.

canvas coordinaten
Image 1. Coordinates in a canvas element.

CSS and Canvas

As is the case to most HTML elements, there may also be applied CSS rules on the canvas element, like borders, margins, padding, etc. Some CSS values are inherited by the content of the canvas, such as the text value; default text in a canvas has the same properties as described in the CSS rules for the canvas itself.

Browser support for the Canvas element

BrowserDetails
ChromeSupport in version 10 +
FirefoxSupport in version 1.5+
Internet ExplorerSupport in version 9+
OperaSupport in version 9+
SafariSupport in version 1.3+

As you can see the HTML canvas element is supported by all browsers except the older versions of Internet Explorer. For applying the canvas element in IE7 and IE8 explorer canvas you can use open-source project explorercanvas (http://code.google.com/p/explorercanvas). To do this you have to place the following conditional comment inside the <head> element of your page

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

The Canvas API

Let's see how we can use the Canvas API. Below we will build an HTML5 page with a canvas element, with a width and height of 200px, and a javascript section.

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

It is better not to use CSS rules to define the height and width of the canvas. The canvas element, as you know by now, contains a 2d rendering context which makes that a by CSS defined width and height on the canvas can give unexpected results.

lege canvas
Image 2. A HTML5 Canvas element with a border.

Now, lets draw a star on the canvas. Previously, making a drawing in an HTML page was a rather precarious job. Using canvas is a matter of a few lines of javascript code that we place in the <head> tags of our HTML page:


<script>   
function drawStar() 
{   
// Get the canvas element and its drawing context
var canvas = document.getElementById("star");   
var ctx = canvas.getContext("2d");  
// Save a copy of the current state of the canvas.
ctx.save;
// Create a path with absolute coordinates
ctx.beginPath();   
ctx.moveTo(100, 66);     
ctx.lineTo(108, 94);   
ctx.lineTo(132, 78);   
ctx.lineTo(121, 102);   
ctx.lineTo(145, 110);     
ctx.lineTo(121, 118);   
ctx.lineTo(132, 142);   
ctx.lineTo(109, 132);   
ctx.lineTo(100, 156);           
ctx.lineTo(91, 132);   
ctx.lineTo(68, 142);   
ctx.lineTo(79, 118);     
ctx.lineTo(55, 110);      
ctx.lineTo(79, 102);   
ctx.lineTo(68, 78);   
ctx.lineTo(92, 94);      
ctx.lineTo(100, 66);
// Return to the starting point and close the path with the closePath function.
// This also tells the canvas  that the star is a closed figure.
  ctx.closePath();
// Draw the star on the canvas (only after giving the line a stroke it will be actually visible)
ctx.stroke();
// Restore the saved state of the canvas
ctx.restore();   
}  
window.addEventListener("load", drawStar, true);   
</script>
</head>
<body>
<canvas id="star" style="border: 1px solid;" width="350" height="200"> U
Update your browser for  support of the canvas element
</canvas>

Now let us see what the above Javascript code actually does. First, we provide for access to the canvas (with id = "star") object by referring to the ID of the respective canvas. Then create a variable (ctx) for the context and we call the getContext method (function) of the canvas object with as as a parameter the type of canvas that you want to create (2d). In this case it is a canvas with a two-dimensional context ("2d"), which, by the way, is the only context available at this time. (it is expected that there will be a three-dimensional context in the future)

We then use the context to perform drawing operations using the three methods beginPath, moveTo, and lineTo. Finally, you actually draw the line by calling the stroke method and finish the operation using the restore function. (see image 3). The restore function is important because it places the canvas back into the state in which it was when you saved it with the save function and thus explain that following drawing commands relate to the saved canvas and not any longer to the star.

The closePath function used in the script here is actually not even necessary, but it is important in the case, for example, that you want to fill the star with a color. It tells the canvas that the star is a closed figure.

ster in canvas
Image 3. Canvas element with a drawing of a star.

The main thing we need to remember after reading this tutorial is that all operations on the canvas element should run via the context object. All functions with visual output are only accessible via the context and not through the canvas element itself. If we talk of an operation on the canvas we mean an operation on the context of the canvas.

A second lesson to be learned from the above is that many operations which are performed on the canvas context not actually refresh the display of your drawing. Functions like start path, moveTo, and lineTo and many other features not directly update the display on the screen. Only when a stroke or fill function is used, the display will actually change and the drawing on screen will be visible. Just compare it to a database transaction. All changes to a database transaction will only be put into effect when the transaction is completed. This will prevent for example that a cash dispensing machines debits a sum of your account, but never does the , money roll out of the machine. The analogy with Canvas operations is that when you perform an interim update of the context, the drawing doesn't appear on the screen halfly. Now it is: or in whole or not at all.

 

Next tutorial

Leave a comment