Tweetegy On the edge of chaos with Ruby, Rails, CoffeeScript and Angular JS.

Getting started with the HTML5 Canvas API

The Canvas API essentially allows the developer to draw on a web page using a JavaScript API. Now you might think, what is the point of this? If you want to show some artwork or animation why not create this first and then send it to the browser as a file?

The main benefits of using the Canvas API

The Basics

Eveytime you use the canvas API there are always some things you must do. The first thing is to use the DOM to get a reference to the Canvas object:

var canvas = document.getElementById("my-id");

Then we must get the 2D context of the Canvas object like so: (in the near future a 3D context will become more widely available)

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

At this point we have access to the 2D context of our canvas object, so we can begin to call methods on this. The following example draws a line on the canvas:

context.beginPath();
context.moveTo(10,10);
context.lineTo(150,150);
//Need to call stroke() function otherwise nothing will appear!
context.stroke();

Drawing shapes

You can do much more with the Canvas API than drawing lines. You can:

Here is an example of drawing circle using the arc function:

context.arc(0,0,180,7,0.71);
context.lineWidth = 5;
context.stroke();

Here is a full example (JavaScript within the HTML Script tag) that uses the quadraticCurveTo function to draw a colorful arc! This example shows the HTML5 Canvas element as well as the full method to get the object and the context and draw the arcs. Notice that it is possible to set many properties on the context object like lineWidth. strokeStyle etc

<canvas id="rainbow" style="border: 1px solid;" width="470" height="400" />

When run in a compatible browser the output should look like so: Arc Canvas API Example

That's it for this very basic introduction! If you want to see the full power of the HTML5 Canvas API then check out some of the (really) cool examples below!

Some cool examples

Some books and tutorials