Dispersion Design

< Back

Vector graphics with HTML5 canvas



The new HTML <canvas> element that is part of the HTML5 specification enables the creation of dynamic graphics with a simplicity that has not been available prior to now. Although it may take some time before browsers support all the features of the canvas element, some of it’s capabilities can be utilized today.

The canvas element supports both vector and bitmap graphic creation, and in this article I will demonstrate how to use the vector graphic capabilities to create a simple image.

Creating the Canvas Element

The HTML tag used to create a canvas element is <canvas>.

<canvas width="300" height="200"></canvas>

We should give the canvas element an ID so that it can be easily referenced using JavaScript. This element can also be styled using CSS in the same way as all HTML elements. We will create a new canvas element and use inline CSS to style it.

		border: 1px solid #808080;
		background: #ffffff;

Which gives us the following:

Canvas Coordinates

Vector graphics are drawn on the canvas using a coordinate system. The coordinate system can be redefined in any way that you desire, however it is initially defined with the origin in the top left corner.

Our canvas is 300 pixels wide and 200 pixels high. Since the coordinate (0, 0) is located in the top left corner, the coordinate (300, 200) will be the bottom right corner.

Figure showing the default canvas coordinates

Accessing the Canvas Using JavaScript

Drawing on the canvas is performed using JavaScript. We can access the canvas element by using it’s ID:

var canvas = document.getElementById('canvas1');

Now we need to access the 2D graphics layer of the canvas element:

ctx = canvas.getContext('2d');

This 2D layer supports either vector or bitmap graphics. This example will utilize vector drawing functions.

Drawing On the Canvas

Now we can set the line width and stroke color:

ctx.lineWidth = "2";
ctx.strokeStyle = "#ff0000";

And finally draw a line across the canvas:

ctx.moveTo(50, 100);
ctx.lineTo(250, 100);

Putting It Together

The complete JavaScript code for this example is:

var canvas = document.getElementById('canvas1');
var ctx = canvas.getContext('2d');

ctx.lineWidth = "2";
ctx.strokeStyle = "#ff0000";

ctx.moveTo(50, 100);
ctx.lineTo(250, 100);