Getting Started with HTML5 Canvas
The HTML5 canvas is a really neat new feature which allows you to draw shapes. It’s a little unknown of how it will be implemented in the mainstream web, however current forecasts suggests it can create really cool games such as Pirates Love Daisies, applications such as Sketchpad or even a new method of CAPTCHA.
Here is a quick cookbook on how to get started with Canvas where you will learn how to draw basic shapes and colours.
Finding your Feet
The first thing you need to start playing with the canvas tool is a browser which supports canvas. Currently most modern browsers do support canvas (This includes, IE9, Google Chrome and Firefox).
Next, set up the shell of your HTML5 page. To save you time I have made a basic example you can copy.
The important thing to remember about adding the canvas tag to your page is:
- Your page has the html5 doctype, otherwise it might not work.
- You add a width and height, otherwise your graphics may look cropped.
- You add a “Your browser does not support the HTML5 notice” notice in the canvas tag for older browsers.
Making a Square
Making a square is pretty simple; in a nutshell all you need to be able to do is understand how x/y coordinates work. I’ve uploaded this demo.
[code]// More canvas stuff will go here.
context.moveTo(5, 10); // Move the start point to x = 5, y = 10
context.beginPath(); // Open the path i.e. Start drawing
context.lineTo(55, 10); // Draw the line to x = 55, y = 10 then continue
// Fill the shape.
// Colour in the border of the shape.
Building a Circle
Creating a circle is a little different, instead of just putting the x/y coordinates you also have to state the starting radius, ending radius and whether if you your arc to be anti-clockwise (Weird right?). Here is the code example.
[code]context.arc(100,75,50,0,Math.PI*2,true); // arc(x coordinate, y coordinate, radius, startAngle, endAngle, anticlockwise)[/code]
Rotating your Canvas
This is probably one of the most useful features for most web designers out there. Pretty much you can rotate the canvas. Check out my example.
[code]// Rotate the canvas 15%