HTML and CSS Reference
Adding Canvas to the HTML Page
In the <body> section of the HTML page, add a <canvas> tag using code such as the
<canvas id="canvasOne" width="500" height="300">
Your browser does not support HTML5 Canvas.
Now, let's break this down to understand what we are doing. The <canvas> tag has
three main attributes . In HTML, attributes are set within pointy brackets of an HTML
tag. The three attributes we need to set are:
canvasOne is the name we will use.
The width, in pixels, of the canvas. The width will be 500 pixels.
The height, in pixels, of the canvas. The height will be 300 pixels.
HTML5 elements, including canvas , have many more attributes:
tabindex , title , class , accesskey , dir , draggable , hidden , etc.
Between the opening <canvas> and closing </canvas> tags, you can put text that will be
displayed if the browser executing the HTML page does not support Canvas. For our
Canvas applications, we will use the text “Your browser does not support HTML5
Canvas.” However, you can adjust this text to say anything.
We will now make use of the DOM to reference the <canvas> we defined in HTML.
Recall that the document object represents every element of an HTML page after it has
We need a reference to the Canvas object so that we will know where to display the
First, we will define a new variable named theCanvas that will hold the reference to the
Next, we retrieve a reference to canvasOne by calling the getElementById() function
of document , and passing the name canvasOne , which we defined as the id of the
<canvas> tag we created in the HTML page:
var theCanvas = document.getElementById("canvasOne");