HTML in itself is primarily about designing and presenting content on the Web. Attempts to add new features to HTML and other related APIs have taken the Web environment to a different level altogether.
In this blog, we are going to look into designing features made available in HTML5. Talking about designing in HTML pages, the element canvas takes prime importance.
What is Canvas?
The new canvas element provides scripts with a resolution-dependent bitmap canvas, which can be used for rendering graphs, game graphics, or other visual images on the fly. The canvas API supports the same two-dimensional drawing operations that most modern operating systems and frameworks support. Furthermore, once canvas is added in an HTML page using the standard <canvas></canvas> notation, we can manipulate it with JavaScript. But to actually do something interesting, we can use JavaScript and get the context of canvas.
Before canvas, to have any drawing on the page, the only option we had were images (jpeg or gif), Flash, applets or some JavaScript hacks.
Canvas Co-ordinates
Like any other graphics system, canvas has a coordinates system with X=0 and Y=0 at the upper-left corner, as shown below.
Support
Currently, canvas is supported by all major browsers such as Firefox, Chrome, Safari, Opera etc. The recently launched IE9 beta has also incorporated support for canvas.
Note: Before we start, we assume here that the reader has a basic understanding of HTML and JavaScript.
Getting Started
Let’s get your favorite editor and start typing!
In its simplest form, a canvas element can be added in an HTML page using “<canvas></canvas>”. But to do something interesting, we will add some more attributes as well.
<canvas id="myCanvas" width="150" height="150"></canvas>
First things first: For any element, it is a good practice to have some “fallback content” just in case the element is not supported in the browser.
<canvas>Use updated browser to see new features of HTML5</ canvas >
Here is a simple piece of code on which we can build our page:
<html>
<head>
<script>
function draw() {
var canvas = document.getElementById("myCanvas ");
var ctx = canvas.getContext("2d");
}
</script>
</head>
<body onload="draw();">
<canvas id=" myCanvas " width="150" height="150">
This example requires a browser that supports HTML5.
</canvas>
</body>
</html>
The above code will create a blank rectangular area. We can use JavaScript to add whatever shapes or patterns we need to add within this area.
Going Line by Line
var canvas = document.getElementById("myCanvas");
This line obtains a reference to the canvas element so that we can use it further in our code.
var ctx = canvas.getContext("2d");
Canvas has the getContext() method which provides a reference through which we can actually draw shapes.
The “2D” parameter provides a 2D context that represents a flat Cartesian surface whose origin (0,0) is at the top left corner, with the coordinate space having x values increasing when going right, and y values increasing when going down. 2D context provides a variety of different methods for drawing shapes, text APIs etc.
Trying out a Shape
Here’s a sample piece of code to draw two overlapping rectangles of different colors.
function draw() {
var canvas = document.getElementById("myCanvas ");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgb(200,0,0)";
ctx.fillRect (10, 10, 55, 50); // Draws a filled rectangle
ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
ctx.fillRect (30, 30, 55, 50);
}
The result of the above code should look similar to the image below.

Drawing Paths
There are some additional steps that need to be taken while drawing paths: beginPath(), closePath(), stroke(), fill().
- Create a path by calling the beginPath() method. Internally, paths are stored as a list of sub-paths (lines, arcs, etc.) which together form a shape. Every time this method is called, the list is reset and we can start drawing new shapes.
- Next, call the methods that actually specify the paths to be drawn. This could be line or arc or curves.
- It is optional to call the closePath() method. This method tries to close the shape by drawing a straight line from the current point to the start.
Finally, we can call the stroke() and/or fill() methods. Calling one of these will actually draw the shape to the canvas. stroke() is used to draw an outlined shape, while fill() is used to paint a solid shape.
function draw() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(125,125);
ctx.lineTo(125,45);
ctx.lineTo(45,125);
ctx.stroke();
ctx.beginPath();
ctx.arc(75,75,50,0,Math.PI*2,true); // Outer circle
ctx.moveTo(110,75);
ctx.arc(75,75,35,0,Math.PI,false); // Mouth (clockwise)
ctx.moveTo(65,65);
ctx.arc(60,65,5,0,Math.PI*2,true); // Left eye
ctx.moveTo(95,65);
ctx.arc(90,65,5,0,Math.PI*2,true); // Right eye
ctx.stroke();
}
The above code should produce results similar to the image below.

The functions used in the sample code above are described in brief below:
moveTo(x, y) – The moveTo() function takes two arguments – x and y, – which are the coordinates of the new starting point.
- lineTo(x, y) – This method takes two arguments – x and y, – which are the coordinates of the line’s end point. The starting point is dependent on previous drawn paths, whereas the end point of the previous path is the starting point for the following path etc. The starting point can also be changed by using the moveTo() method.
- arc(x, y, radius, startAngle, endAngle, anticlockwise) – This method takes five parameters: x and y are the coordinates of the circle’s center. Radius is self-explanatory. The startAngle and endAngle parameters define the start and end points of the arc in radians. The starting and closing angle are measured from the x axis. The anticlockwise parameter is a Boolean value which when true draws the arc anticlockwise, otherwise in a clockwise direction.
Using Images
We can have images in canvas for dynamic photo compositing or for use as backdrops of graphs etc. But it is a little tricky to add images in canvas. There three ways we can use images:
- Using images which are on the same page – We can access all images on a page by using either the document.images collection, the document.getElementsByTagName() method, or if we know the ID attribute of the image, the document.getElementById() method.
- Using other canvas elements – Just as with normal images we access other canvas elements using either the document.getElementsByTagName() method or the document.getElementById() method. Make sure you’ve drawn something to the source canvas before using it in your target canvas.
- Creating an image from scratch – Another option is to create a new image objects in our script:
var img = new Image(); // Create new Image object
img.src = 'myImage.png'; // Set source path
var img = new Image(); // Create new Image object
img.onload = function(){
// execute drawImage statements here
}
img.src = 'myImage.png'; // Set source path
function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image();
img.onload = function(){
ctx.drawImage(img,0,0);
ctx.beginPath();
ctx.moveTo(30,96);
ctx.lineTo(70,66);
ctx.lineTo(103,76);
ctx.lineTo(170,15);
ctx.stroke();
}
img.src = 'images/backdrop.png';
}
drawImage(image, x, y) – image is a reference to an image or canvas object and x, y form the coordinates where the image should be placed.
Pixel Data and Canvas
Remember that the canvas API is based on pixels. This gives us the ability to easily access pixel information from canvas and manipulate it.
ctx.getImageData(startX, startY, width, height)
This function returns a representation of the current state of the canvas display as a collection of integers. Specifically, it returns an object containing three properties:
- width: The number of pixels in each row of the pixel data
- height: The number of pixels in each column of the pixel data
- data: A one-dimensional array containing the actual RGBA values for each pixel retrieved from the canvas
RGBA – is Red, Blue, Green and A is an alpha component with values ranging from 0-255.
ctx.putImageData(imagedata, dx, dy)
This function can be used to update the canvas display. As you have access to the object with image data (using getImageData()), now you can easily modify the pixel values in the data array mathematically, because they are each simply integers from 0 to 255.
ctx.createImageData(sw, sh)
This method can be used if you want to create a new image from scratch using canvas. This set of data can be programmatically changed as before, even though it does not represent the current state of the canvas when retrieved.
Canvas Security
There could be security issues with respect to using pixel manipulation in canvas. For this reason, the concept of an origin-clean canvas was specified, so that canvases that are tainted with images from origins other than the source of the containing page cannot have their data retrieved.
Any canvas that contains images rendered from remote origins will throw a security exception if the getImageData() function is called. It is acceptable to render remote images into a canvas from another origin as long as you (or any other scriptwriter) do not attempt to fetch the data from that canvas after it has been tainted.
So as we have seen in this blog, the canvas API provides a powerful way to draw on HTML pages with images, gradients and paths. When properly planned, canvas applications can range from simple charts to complex visual data representing tool to cool animations and more!