Use HTML5canvas for Web plotting-

Source: Internet
Author: User
Tags canvas rectangle
The new HTML5 specification aims to help developers easily compile various Web applications to adapt to the latest trends in SaaS, cloud computing, and RIA technologies. Before HTML5 can be widely promoted, developers usually use SVG, VML, and other technologies for Web plotting, but these operations are based on X ...,. Introduction:The new HTML5 specification aims to help developers easily compile various Web applications to adapt to the latest trends in SaaS, cloud computing, and RIA technologies. Before HTML5 is widely promoted, developers usually use technologies such as SVG and VML for Web plotting, however, these XML-based declarative drawing methods cannot meet the performance requirements of complex drawing operations, such as the pixel-Level Drawing capability required by Web games. The emergence of HTML5 canvas elements fills in this deficiency. developers can use JavaScript scripting language to draw a series of command-Based Graphics operations in the canvas, this article explains how to use the canvas Element to perform basic drawing operations, complete simple animation and user interaction tasks, and clarify the capabilities canvas can provide to help build Web graphics applications.


Background

The canvas element introduced in HTML5 allows Web developers to draw on Web pages directly using JavaScript scripts without any third-party plug-ins (such as Flash and Silverlight. For the first time, it was introduced and implemented by Apple's Webkit framework and successfully applied in the Safari browser. Here, readers can experience wonderful canvas-based examples. Currently, canvas has become a fact standard in HTML5 specifications and is supported by browsers such as Firefox 3.0 +, Safari 3.0 +, Chrome 3.0 +, and Opera10.0 +. Recently (at the time of writing this article), IE officially announced that it will begin to support the canvas Element after its version 9.0.

Canvas-Based Drawing fills up the shortcomings of SVG drawing in complex drawing operations, especially in performance. It can be widely used in Dashboard, 2D/3D Game and other Web applications.

Basic Drawing API

After learning what a canvas element is, it is time to use canvas to Perform Drawing operations on the Web page. In fact, a single canvas tag only defines a rectangular area on the page, and there is nothing special about it. developers can complete various graphics and lines only by using JavaScript scripts, compared with SVG-based implementation of the same drawing effect, canvas drawing is a pixel-level bitmap technology, while SVG is a vector drawing technology. In view of the difference in this essential mechanism, how to perform canvas rendering more quickly and efficiently becomes one of the important indicators of the mainstream JavaScript execution engine performance competition. Currently, Google Chrome's V8, Firefox's SpiderMonkey, Safari's Nitro and other engines have all been able to meet the necessary performance indicators required for 2D plotting, although the CPU usage is relatively high when running some canvas-based games, we have reason to believe that with the participation of a series of hardware vendors such as NVIDIA and AMD, hardware acceleration technology will greatly improve the performance of Web applications.

Before starting plotting, we need to first create a canvas of the specified size and specify an id for it to obtain the DOM instance object in a JavaScript script. To declare a canvas node, follow these steps.

 
     
        Fallback content, in case the browser does not support Canvas.  
      

It must be noted that, because it is unable to ensure that all browsers used by users support the canvas Element, "Fallback content" must be added to the Development of canvas-based Web applications ", to remind users that they cannot normally experience this function, or suggest them download the latest browser.

Here, curious readers may ask, since this is a common DOM node, it means that the canvas size can be changed by directly changing its width or height attribute value? This is true, but, as mentioned earlier, canvas is a pixel-level plotting method. Therefore, once the canvas size is adjusted dynamically, canvas will be "reset" to a new initial state. Even the following operations will clear the bitmap in the canvas and restore all relevant attributes to the initial state. Of course, we can also use this as a tip to reset the canvas.

 document.getElementById("canvas").width = document.getElementById("canvas").width; 

Simple Drawing

Canvas-Based Drawing does not directly perform various drawing operations on the drawing screen created by the canvas tag, but relies onRendering Context)All drawing commands and attributes are defined in the rendering context. The first thing to do after obtaining the corresponding DOM object through the canvas id is to get the rendering context object. The rendering context corresponds to the canvas one by one. No matter how many times the getContext () method is called on the same canvas object, the same context object is returned. Currently, all browsers that support the canvas label support 2D rendering context. You can use the following code to obtain the object.

 var context = document.getElementById("canvas").getContext("2d"); 

In addition, in the near future, developers will be able to get OpenGL-based 3D rendering context for 3D drawing in the canvas.

Unlike SVG, canvas supports only one type of basic graphics, and other shapes such as circles and polygon are drawn by paths. Listing 1 shows how to use the rectangular Drawing Method in the rendering context to complete the graph shown in Figure 1.


Figure 1. sample image corresponding to listing 1


Listing 1. Drawing a canvas rectangle
Function drawRect () {var canvas = document. getElementById ('canvas '); if (canvas. getContext) {var ctx = canvas. getContext ('2d '); // obtain the 2d rendering context ctx. clearRect (300,200, 300); // clear all pixels ctx in the 200 * rectangular area with () as the upper left coordinate origin. fillStyle = '# 00f'; // you can specify the filling attribute of a rectangle. # 00f indicates the blue ctx. strokeStyle = '# f00'; // you can specify the line color of the rectangle. # f00 indicates the red ctx. fillRect (50, 25, 150, 80); // fill a * 80-size rectangle ctx with fillStyle. strokeRect (160, 90); // draw a non-filled rectangle with the color of the edge as the strokeStype attribute }}

Draw path

Before you start to draw a path, you must first make it clear that the rectangular drawing API is a real-time API. After the corresponding drawing function is executed, render the image on the screen instantly. However, this is not the case with the path drawing API. The complete path drawing process can be divided into the following two phases:

  • Define path outlines:

Each canvas instance object has a path object. The process of creating a custom image is the process of constantly operating on the path object. Every time you start a new drawing task, you must first use the beginPath () method to reset the path object to the initial state, and then call the moveTo/lineTo and other draw line methods through a series of calls, draw the expected path, where the moveTo (x, y) method sets the starting coordinate of the drawing, while lineTo (x, y) and other line drawing methods can draw a straight line from the current starting point, the arc and the curve to the target position. The last step is also an optional step. It is to call the closePath () method to close the custom image. This method will automatically create a straight line from the current coordinate to the start coordinate.

  • Draw path

After defining the path outline, no path is displayed on the canvas screen. You can also modify the path. Once determined, you need to continue calling the stroke ()/fill () function to complete the last step of rendering the path to the screen. The outline color and fill color of the path are determined by the strokeStyle and fillStyle attributes.

Listing 2 draws a semi-arc shown in Figure 2 and closes the image using the closePath () method.


Figure 2. sample image corresponding to listing 2


Listing 2. Drawing the canvas path
Function draw () {var canvas = document. getElementById ('canvas '); if (canvas. getContext) {var ctx = canvas. getContext ('2d '); ctx. fillStyle = '# 00f'; ctx. strokeStyle = '# f00'; ctx. beginPath (); ctx. arc (75,75, 30,0, Math. PI, false); // draw a semi-circular arc ctx. closePath (); // automatically draws a straight line to close the arc. If you do not call this method, only a half arc ctx is displayed. fill (); // you can comment out the fill or stroke function to observe the changes in the image ctx. stroke ();}}

2d Deformation

Another important concept in Canvas plotting isDrawing State)The painting status reflects the current instantaneous state of the rendering context. developers can quickly return to the previous attributes and deformation operations by saving/restoring the painting status. The painting status consists of the following three parts:

  • Current deformation matrix)
  • Current Cropping Area (clipping region)
  • Attributes in the current context, such as strokeStyle, fillType, globalAlpha, and font.

It should be noted that the current path object and the current bitmap are not included in the painting state, and the path is a persistent object. As mentioned above, only beginPath () operations will be reset, while bitmap is the canvas attribute, not the rendering context.

Developers can use the save and restore methods to save and restore the canvas status. Each time the save method is called, the current status is pushed into the stack, the corresponding restore method will pop up a status from the stack and restore the current screen to this status. The painting state is widely used and important in the deformation operation of the canvas image, because calling a restore method is much easier than manually restoring the previous State. Therefore, A good habit is to save the canvas status before performing the deformation operation.

Common deformation operations of 2D drawing can be well supported in canvas, including translation, rotation, and Scale. Since all the deformation operations are based on the deformation matrix, developers always need to remember that, once the save/restore operation is not used to keep the original drawing state, subsequent drawing operations, all will be completed in the current deformation state of the application. Listing 3 draws the following screen using the translation and rotation methods.


Figure 3. example Figure 3


Listing 3. Use the translation/rotation deformation method to draw a complex bitmap
Function drawPointCircle () {var canvas = document. getElementById ('canvas '); if (canvas. getContext) {var ctx = canvas. getContext ('2d '); ctx. translate (150,150); // translate the canvas origin from (150,150) to () for (I = 1; I <= 2; I ++) {// Draw Internal and External 2 layers if (I % 2) = 1) {ctx. fillStyle = '# 00f';} else {ctx. fillStyle = '# f00';} ctx. save (); // keep the state consistent when you start to draw each layer for (j = 0; j <= I * 6; j ++) {// number of points generated at each layer ctx. rotate (Math. PI/(3 * I); // rotate the coordinate system clockwise around the current origin. pi/(3 * I) ctx. beginPath (); ctx. arc (0, 20 * I, 5, 0, Math. PI * 2, true); ctx. fill (); // fill each vertex with the fillType value} ctx. restore ();}}}

Pixel-level plotting

Pixel-level plotting is one of the most obvious features of drawing technologies, such as SVG and VML. The rendering context provides three methods: createImageData, getImageData, and putImageData, all objects are imageData objects. The imageData object contains three attributes: width, height, and data. data contains the width x height x 4 pixel values, multiplied by 4, each pixel has an RGB value and a transparency alpha value.

The code shown in Listing 4 adds a simple color inversion filter effect to the sample image in the previous section. You can call the getImageData (x, y, width, height) method to obtain the filter by (x, y) it is all pixels in the rectangle area of the upper left coordinate, then the RGB values of all pixels are reversed, and the putImageData (imageData, x, y) re-draw the modified pixel value on the canvas.


Figure 4. example Figure 4


Listing 4. Simple filter effects
Function revertImage () {var canvas = document. getElementById ('canvas '); if (canvas. getContext) {var context = canvas. getContext ('2d '); // obtain the canvas pixel array var imgdata = context from the specified rectangular area. getImageData (100,100,100,100); var pixels = imgdata. data; // traverse each pixel and reverse the RGB value (var I = 0, n = pixels. length; I
     

Animation Effect

Canvas does not appear in order to make an animation. Naturally, it does not have the concept of frames in animation production. Therefore, using the timer to repeatedly redraw the canvas image has become a common solution to achieve the animation effect. SetInterval in Javascript(Code, millisecThe method can call the function or code string pointed to by code repeatedly according to the specified time interval. In this way, the plotting function is passed as the first parameter to the setInterval method, the position of the image in the image is moved during each call to achieve an animation experience. It should be noted that although the second parameter of the setinterval method allows developers to set the call frequency of the drawing function, this is always the most ideal situation, because the drawing frequency depends largely on the rendering speed of the underlying JavaScript Engine supporting canvas and the complexity of the corresponding drawing function, the actual running results are usually slower than the specified drawing frequency.

Listing 5 shows the animation effect of a small elastic ball. When the ball does not reach the surrounding boundary, the drawing method keeps moving the horizontal and vertical coordinates of the painted ball. In addition, the clear method is used to clear the previous image before each re-painting.


Listing 5. Small stretch ball Animation
  

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.