Getting started with the HTML5 Canvas API
08 Oct 2011The 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 JavaScript to render the image / animation may be smaller than downloading a file
- The Canvas API allows for some cool extras like scaling, rotation and even pixel by pixel image access
- Being an API means that it is programmable, so you can build applications and games purely based on the Canvas API
- The Canvas API is potentially powerful enough that you could write an image editing suite that runs in the browser (no more Photoshop required!)
- The Canvas API does not require any browser plug-ins (bye, bye Falsh!)
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:
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)
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:
Drawing shapes
You can do much more with the Canvas API than drawing lines. You can:
- Draw and fill shapes
- Draw lines
- Draw curves
- Add images
- Transform objects
- …and more!
Here is an example of drawing circle using the arc function:
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
When run in a compatible browser the output should look like so:
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!