This text provides an overview of the HTML5 canvas basic usage. The overview is split into two parts:
- Declaring an HTML5 canvas element.
- Drawing graphics on the canvas element.
Declaring a Canvas Element
First, let's see how to declare a canvas element in an HTML page:
The code above declares a single canvas
element with width
set to 500, height
set to 150, and style
set to a 1 pixel border with color #cccccc
.
The text inside the canvas
element is ignored, if the browser supports the HTML5 canvas element. If the HTML5 canvas element is not supported, the text will probably be displayed as ordinary text by the browser.
You should put the canvas HTML code in your page at the location where you want the canvas to be visible. Just like any other HTML element (e.g. a div
element).
Drawing Graphics on a Canvas Element
Graphics drawn on an HTML5 canvas is drawn in immediate mode. Immediate mode means, that as soon as you have drawn a shape on the canvas, the canvas no longer knows anything about that shape. The shape is visible, but you cannot manipulate that shape individually. It is like a real canvas for a painting. Once painted, all you have left is color pigments / pixels.
This is contrary to SVG, where you can manipulate the shapes individually, and have the whole diagram redrawn. In HTML5 you will have to redraw everything yourself, if you want to change the drawn figure.
Drawing graphics on an HTML5 canvas element is done using JavaScript, following these steps:
- Wait for the page to be fully loaded.
- Obtain a reference to the canvas element.
- Obtain a 2D context from the canvas element.
- Draw graphics using the draw functions of 2D context.
Here is a simple code example that shows the above steps:
First, an event listener function is attached to the window. This event listener function is executed when the page is loaded. This function calls another function I have defined, called drawExamples()
.
Second, the drawExamples()
function obtains a reference to the canvas element usingdocument.getElementById()
function, passing the id
of the canvas element, as defined in the declaration of the canvas element.
Third, the drawExamples()
function obtains a reference to a 2D context from the canvas element, by callingcanvas.getContext("2d")
on the canvas element obtained earlier.
Fourth, the drawExamples()
function calls various drawing functions on the 2D context object, which results in graphics being drawn on the canvas.
Here is how the code looks when executed: