HTML5 Programming Notes (II)

Source: Internet
Author: User

Canvas API

1. HTML5 Canvas Overview1.1 History

The concept of canvas was originally proposed by Apple to create a dashboard widget (Dashboard widget) in Mac OS X WebKit. Before the advent of canvas, developers could use the drawing API in their browsers, using only Adobe's Flash and SVG plug-ins, or only VML supported by IE, and some other outlandish javascript tricks.

SVG vs. canvas

"Canvas is essentially a bitmap canvas, and the graphics drawn on it are non-scalable and cannot be zoomed out like SVG images." In addition, objects drawn with canvas are not part of the page DOM structure or any clear space-this is considered a flaw. SVG images can be scaled smoothly at different resolutions and support click Detection (which can detect which point on the image the mouse clicks).

So why not use SVG for WHATWG's HTML5 attribution? Although canvas has obvious shortcomings, the HTML canvas API has two advantages to compensate: first, you do not need to store each element in the drawing image as an object, so performance is very good; second, the implementation of canvas is based on the excellent two-dimensional drawing API available in other programming languages. The API is relatively straightforward.

What is 1.2 Canvas?

When you use a canvas element on a Web page, he creates a rectangular area. By default, the rectangular area is 300 pixels wide and 150 pixels high, but you can also customize the size or set other properties of the canvas element.

1 <canvas></canvas>

After the page has a canvas element, we can control it from JavaScript. You can add pictures, lines, and text, and you can also draw in them, and you can even add advanced animations.

Using canvas becomes the first thing to get its context (content). The actions are then executed in the context, and the actions are finally applied to the context. You can think of this way of editing a canvas as a database transaction: The developer initiates a transaction, then performs some action and finally commits the transaction.

1.3 Canvas coordinates

The coordinates in the canvas start from the upper-left corner, the x-axis extends to the right in the horizontal direction (in pixels), and the y-axis extends vertically. The point at the upper-left corner of the x=0,y=0 is called the origin point.

1.4 What is the case without canvas

In some cases, the canvas element should not be used if other elements are already sufficient. For example, using a canvas element to dynamically draw all the different headings in an HTML page is not as straightforward as heading styles (H1, H2, and so on), and they achieve the same effect.

1.5 Alternative content

When accessing a page, it is a good idea for developers to provide a replacement code if the browser does not support canvas elements, or if some features in the HTML5 Canvas API are not supported. For example, a developer can tell a visitor by using an alternate image or some descriptive text, with the latest browser for better viewing.   

1 <canvas>2     Update your browser to enjoy canvas!  3 </canvas>

What about the accessibility of the canvas element?

"Providing alternative images or alternative text leads to the topic of accessibility--Unfortunately, this is a glaring flaw in the HTML5 canvas specification. For example, there is no native method that automatically generates a textual description for a picture that has been inserted into a canvas for substitution. Similarly, there is no native method to generate alternate text to match text that is dynamically generated by the canvas text API. ”

Future iterations of the canvas API may contain focusable sub-regions related to the canvas display and interaction controls between them. However, if your image display requires significant interaction, consider using SVG instead of the canvas API. SVG is also used for drawing, and he integrates the DOM of the browser.

1.6 CSS and canvas

Like most HTML elements, canvas elements can be added by applying CSS to add borders, set padding, margins, and so on, and some CSS properties can be inherited by elements within the canvas. For example, font style, text that is added to the canvas, has the same style as the canvas element itself.

In addition, setting properties for the context in the canvas also follows the CSS syntax. For example, applying color and font styles to a context is exactly the same syntax used in any HTML and CSS document.

1.7 browser support for HTML5 canvas

With the advent of IE9, all browser vendors now offer support for HTML5 canvas, and he has been mastered by most users.

2. Using the HTML5 Canvas API2.1 Detection of browser support

Before you create a HTML5 canvas element, make sure that the browser supports it first. If not, you will need to provide some alternative text for those antique browsers.

1 Try 2 {3     document.createelement ("Canvas"). GetContext ("2d"); 4     document.getElementById ("Support"). InnerHTML = "HTML5 Canvas was supported in your browser"  ; 5 }6catch(e)7{8     document.getElementById ("Support"). InnerHTML = "HTML5 Canvas was not supported in your browser"; 9 }

The code above attempts to create a canvas object and gets its context. If an error occurs, you can catch the error and know that the browser does not support canvas. The page has pre-placed an element with the ID of support, and by updating the content of the element with the appropriate information, it can reflect the browser's supporting situation.

2.2 On the page, if the canvas
1 <canvas height= "width=" ></canvas>

The above code shows a "hidden" area of 200x200 pixels on the page. If you want to add a border to it, use the standard CSS border property to set it.

1 <canvas id= "diagonal" style= "border:1px solid;" Width= "height=" ></canvas>

Note that the above code adds an id attribute with a value of "diagonal", which means that the canvas element can be quickly found by ID in the future development process.

1<script>2     functiondrawdiagonal () {3         //Get canvas elements and drawing context4         varCanvas = document.getElementById (' diagonal ');5         varcontext = Canvas.getcontext (' 2d ');6 7         //create a path with absolute coordinates8 Context.beginpath ();9Context.moveto (70, 140);TenContext.lineto (140, 70); One  A         //draw this line to the canvas - Context.stroke (); -     } the  -Window.addeventlistener ("Load", drawdiagonal,true); -</script>

First, access to the canvas object is obtained by referencing a specific canvas ID value. The ID in this code is diagonal. Then define a context variable, call the GetContext method of the canvas object, and pass in the canvas type you want to use. Of these, "2d" is 2D, "WebGL" is 3D.

Next, you perform the line-drawing operation based on this context. The code calls three methods--beginpath, MoveTo, LineTo, and the coordinates of the beginning and end of the line are passed in.

Methods MoveTo and LineTo do not actually draw lines, but rather finish drawing lines by calling the Context.stroke () method when the canvas is finished. MoveTo (x, y), moves the context to the coordinate specified point, lineTo (x, y), draws a line from the specified point to the target point.

As you can see from the code above, all the actions in the canvas are done through the context object. The results are displayed only when you apply the draw (stroke) or fill (filling) method to the path. Otherwise, the canvas is updated immediately only when the image is displayed, the text is displayed, or when the rectangle is drawn, filled, and cleared.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.