HTML and CSS Reference
In-Depth Information
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:
The id is the name we will use to reference this <canvas> tag in our JavaScript code.
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.
Using document to reference the canvas element in JavaScript
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
Canvas API calls we will make from JavaScript.
First, we will define a new variable named theCanvas that will hold the reference to the
Canvas object.
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");
Search WWH ::

Custom Search