In the <body> of an HTML page, you can add a <canvas> tag using code like the following:
The
code is as follows:
<canvas id= "Canvasone" width= "height=" >
Your Browser does not support HTML5.
</canvas>
For canvas, the following wording is not allowed:
The
code is as follows:
<canvas id= "Canvasone" width= "" height= ""/>
Let's take a look at what this code does. The <canvas> tag has 3 main properties, including:
1.id. We can use the ID value in the JavaScript code to reference the <canvas> tag. In the above code, the ID value is Canvasone.
2.width. The width of the canvas, in pixels. In the above code, the width value is 500 pixels.
3.height. The height of the canvas, in pixels. In the above code, the height value is 300 pixels.
We can place any piece of text between the canvas start tag <canvas> and the end tag </canvas>, when the browser that opens the HTML page does not support canvas, the text is displayed where the canvas tag is located. In the above code, we use the text "Your browser does not support HTML5 Canvas.".
Using the Document object in JavaScript to refer to the canvas element
When an HTML page is loaded, the Document object refers to all the elements in the page, so we can use the DOM to reference the <canvas> defined in the above code.
We need a reference to the canvas object so we can know where to display the painting with the canvas interface.
First, we define a variable named Thecanvas to hold the reference to the Canvas object.
We then call the getElementById () function of the Document object and set the incoming argument to Canvasone (the ID of the <canvas> tag in the HTML page) to get the canvas object:
The
code is as follows:
var Thecanvas = document.getElementById ("Canvasone");