Drawing with the Canvas Element

 May 17, 2013

Yesterday I had my first go at using the canvas element and some Javascript to draw dynamic graphics in a web app. What follows are my notes from the process to help get this to stick, and to help anyone else exploring the same.

While I’ve come across this plenty of times before via 3rd-party libraries and on other sites I’ve never tried it myself and I’m very pleased to say its a lot easier that I feared and I got my first (very basic) diagram up and running in about 30 minutes.

Getting Setup

First off you need to specify the canvas element itself.

<canvas id="my_drawing" height="200" width="800"></canvas>

Think of this like a piece of paper that you are going to start drawing on with a set of Javascript commands. Now the first thing I found was that the Javascript must come after the canvas element (or possibly in the document onload handler) otherwise nothing will appear

First Bit of Javascript

I’m using vanillajs here, as I don’t want to assume jQuery or suchlike, but it should be pretty easy to modify this if you want.

Once you’ve got a canvas element in the DOM, you need to reference it in your JS

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

Next you need to setup a canvas context, which for now I’ll be sticking with 2D

var context = canvas.getContext('2d');

I only had the need for 2 elements to my diagram, lines and circles, so that’s all I’ll cover here, but it should give a taste for what’s possible

Drawing a Line

For each new element on the canvas you need to start a new path

context.beginPath();

Then specify the start and end co-ordinates of the line. The numbers passed to these methods are the x,y co-ordinates of the point in question based on 0,0 being the top-left of the canvas element

context.moveTo(40, 25);
context.lineTo(760, 25);

The last bit of our line now is to provide some settings like thickness and colour (there are more, but this will do for now)

context.lineWidth = 2;
context.strokeStyle = 'red';
context.stroke();

This code will give us a horizontal red line running across the top of the canvas, 25px from the top edge and with a 40px margin on each end

Drawing a Circle

Once again, remember you need to start a new path for each separate part of the graphic, otherwise you may find (as I did) that customising stroke widths, colours etc will become awkward to say the least

context.beginPath();

To draw a circle we basically use the arc method (whose 4th and 5th paras are the start and end angle) and use it to draw a complete cricle

// the params here are 
// arc(xCenter, yCenter, radius, startAngle, endAngle, counterClockwise);
context.arc(25, 25, 5, 0, 2 * Math.PI, false);

This command will draw us a complete circle with a radius of 5px, centered at co-ordinate 25,25 in the canvas element (remember thats from the top-left corner)

Once we have our circle we can pass in some settings to style it, a red dot with a black border.

context.fillStyle = 'red';
context.fill();
context.lineWidth = 1;
context.strokeStyle = 'black';
context.stroke();

Adding Text

The last of my elements was to add a label to each dot along the line, luckily the canvas toolset includes text.

This code is pretty self explanitory. We set a font, colour and alignment the write the text to the canvas with fillText.

The fillText function takes 3 params. The text string, the x co-ordinate and the y co-ordinate to place the text box.

context.font = '9pt Tahoma';
context.fillStyle = '#757575';
context.textAlign = 'center';
context.fillText('Label Text Here', 25, 45);

Conclusion

Well I’ve barely scratched the suface here, only showing 3 possible elements in a drawing. To be honest, when I said earlier that I only needed a simple drawing it was exactly that, a horizontal line with “bus stop” progression points along it for a flow through a process. These two elements allowed me to do that perfectly while giving me a taster of using the canvas tools.

It turns out not only to be pretty simple, but very fast and supported by all modern browsers, so if you need dynamic graphics in your web site I highly recommend giving this a crack.

I’ll certainly be revisiting this and exploring more complex graphics as soon as I have the time

Resources