Example of adding a Canvas label to an HTML page
This article mainly introduces the example of adding a Canvas tag to an HTML page. This article provides the sample code directly and explains some important attributes and js access methods. For more information, see
In the <body> Of the HTML page, you can use the following code to add the <canvas> tag:
The Code is as follows:
<Canvas id = "canvasOne" width = "500" height = "300">
Your browser does not support HTML5 Canvas.
</Canvas>
For canvas, the following statements are not allowed:
The Code is as follows:
<Canvas id = "canvasOne" width = "500" height = "300"/>
Let's take a look at what the above Code has done. <Canvas> A tag has three main attributes:
1. id. You can reference the <canvas> label with the id value in JavaScript code. In the above Code, the id value is canvasOne.
2. width. The width of the canvas, in pixels. In the preceding 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.
You can place any piece of text between the Canvas start tag <canvas> and end tag </canvas>. When the browser that opens an HTML webpage does not support Canvas, the text is displayed in the Canvas tag. In the above Code, we use the text "Your browser does not support HTML5 Canvas .".
Reference the canvas element with a document Object in JavaScript
After an HTML page is loaded, the document Object refers to all elements in the page. Therefore, we can use DOM to reference the <canvas> defined in the above Code.
We need to reference the Canvas object so that we can know where to display the painting with the Canvas interface.
First, we define a variable named theCanvas to save the reference of the Canvas object.
Then, we call the getElementById () function of the document Object and set the passed parameter 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 ");