Pro HTML5 Programming (Second Edition) 2. Canvas API (2), html52.canvas
1. Add the canvas element to the page
Eg:
1 <!DOCTYPE html> 2
Note: The ID feature with the value "diagonal" is added to the Code above. In this way, you can quickly find the canvas Element by ID. For any cnavas object, the ID feature is very important, because all operations on the canvas element are controlled by the script code. If there is no ID, it is difficult to find the canvas element to be operated on.
Run the following command:
2. Draw a diagonal line in the canvas.
Test02.js
1 function drawDiagonal () {2 // obtain the canvas Element and Its Drawing context. 3 var canvas = document. getElementById ("diagonal"); 4 var context = canvas. getContext ("2d"); 5 6 // use absolute coordinates to create a path 7 context. beginPath (); 8 context. VPC: moveTo (70,140); 9 context. lineTo (); 10 11 // draw this line to 12 context on the canvas. stroke (); 13} 14 15 windows. addEventListener ("load", drawDiagonal, true );
The code above demonstrates the important process of using the HTML5 Canvas API:
First, you can obtain access to the canvas object by referencing a specific canvas id value. Then, you can define a context variable, call the getContext method of the canvas object, and input the expected canvas type, in the code list, pass in "2d" to get a two-dimensional context.
Three methods are called in the Code: beginPath, moveTo, and lineTo. the start and end points of the line are passed in. The moveTo and lineTo methods do not actually draw lines, but call the context. stroke () method to draw lines when the canvas operation is completed.
Note:
All operations on the canvas are performed by context objects. All functions related to visual output effects can only be used by context objects rather than canvas objects. The display results are not directly modified by many functions in canvas that set the style and appearance. The result is displayed only when the stroke or fill method is applied to the path. Otherwise, only the image, text, or painting is displayed, canvas is updated immediately when the rectangle is filled and cleared.