Because not all browsers support Canvas, I’ll use Modernizr to help out. Modernizr will let me know if Canvas is supported, and if not it will allow me to call a polyfill.
You can get started with Modernizr at Using Modernizr, Polyfills, YepNope.
But first, let’s draw something.
Canvas is a simple graphics API that draws pixels and nothing more. Hence, there’s no way to change an existing drawing or react to events, such as a click, on a particular part of your drawing. You can respond to button events and then update the Canvas image by redrawing it.
Do this in three steps:
- Place the canvas tag somewhere inside your HTML
- Draw on the HTML5 Canvas API.
But not all browsers support Canvas. Use Modernizr to check for canvas browser support, then load a polyfill when canvas is not supported by the browser.
Start by placing a canvas tag in your HTML, giving the canvas a width and height that represents the drawing surface.
The result is a line drawn on the canvas:
For example, you can draw a rectangle that if filled with the background color, clear the center, and then draw another inside it.
Canvas supports a single shape, a rectangle. All other shapes must be created by combining one or more paths.
The first step to create a path is calling the
beginPath method. Internally, paths are stored as a list of sub-paths (lines, arcs, etc) which together form a shape. Every time this method is called, the list is reset and we can start drawing new shapes.
Save and Restore State
The canvas drawing state is basically a snapshot of all the styles and transformations that have been applied. You can save and restore the state.
Canvas states are stored on a stack. Every time the
save method is called, the current drawing state is pushed onto the stack. A drawing state consists of
- The transformations that have been applied, such as translate, rotate and scale.
- The values of
- The current clipping path, which we’ll see in the next section.
You can call the
save method as many times as you like.
Every time the
restore method is called, the last saved state is returned from the stack and all saved settings are restored.
In this case, I am rotating the canvas to add rotated text.
save and restore also applies to transforms where you can stretch, scale, and transform your drawing.
And as you keep drawing, you can do this kind of thing:
Not all browsers support canvas.
Use Modernizr to detect whether canvas is supported and if the browser is not supported, you can use a polyfill.
Then you can use feature detection to do the right thing using the canvas.
For more information, see No Browser Left Behind: An HTML5 Adoption Strategy.
For more information, see :
- Using HTML5 Canvas for Data Visualization in MSDN Magazine.
- The Developer’s Guide to HTML5 Canvas
- How To Choose Between SVG and Canvas
- How To Create 3D Graphics Using Canvas
Sample code is available in the DevDays GitHub repository. See https://github.com/devdays/html5-tutorials