HTML5 brief introduction, html5
Today, let's talk about a canvas element unique to HTML5. It aims to make vector images on Web pages do not need to rely on flash or other plug-ins to use canvas elements on Web pages, it creates a rectangular area. The default value is 300*150, which can also be customized. The coordinates in the Canvas start from the upper left corner. The X axis is horizontally oriented (by pixel) to the right, and the Y axis is vertically oriented down. The coordinates of x = 0 in the upper left corner and y = 0 in the upper left corner are called the origin.
Although Canvas is powerful, if it achieves the same effect as the existing HTML5 elements, it still directly uses existing elements, the execution efficiency is faster. If the canvas element is not supported by some browsers, the canvas must be compatible and define an alternative content in the canvas, the alternative content can be a text description or an image. The general style of a Canvas, such as the border and margin, can be defined using css syntax. The text added inside the canvas is the same as that of the Canvas element by default.
Let's talk about the use of the canvas API. Let's start with an example. Draw a diagonal line in the canvas: first put a canvas element in the html and then start the line in the javascript script,
Function drawDiagonal (){
// Obtain the canvas Element and Its Drawing Context
Var canvas = document. getElementByIdx_x ("diagonal ");
Var context = canvas. getContext ('2d ');
// Use absolute coordinates to create a path
Context. beginPath ();
Context. moveTo (10,140 );
Context. lineTo (140,70 );
// Draw the line to the canvas
Context. stroke ();
}
Window. addEventListener ("load", drawDiagonal, true );
The effect is as follows:
Although relatively simple, it shows an important process for using the HTML5 canvas API. First, obtain the canvas access permission by ID, then define a context variable, call the getContext method of the canvas object, and pass in the canvas type to be used. The Code calls three methods: beginPath, moveTo, and lineTo, and passes in the coordinates of the start and end points of the line.
The powerful functions of Canvas are far more than that. Of course, they are limited to space. We recommend that you write a book titled HTML5 advanced programming in great detail, which is suitable for beginners to read carefully.