Adding Canvas to the HTML Page

In the <body> section of the HTML page, add a <canvas> tag using code such as the following:

<canvas id="canvasOne" width="500" height="300">
 Your browser does not support HTML5 Canvas.
</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:

id

The id is the name we will use to reference this <canvas> tag in our JavaScript code. canvasOne is the name we will use.

width

The width, in pixels, of the canvas. The width will be 500 pixels.

height

The height, in pixels, of the canvas. The height will be 300 pixels.

Note

HTML5 elements, including canvas, have many more attributes: tabindex, title, class, accesskey, dir, draggable, hidden, and so on.

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.

Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.