HTML 5 canvas--Basic syntax

Source: Internet
Author: User
Tags custom graphics

Directory
    • Briefly
    • Canvas Basics
    • The context API
      • Basic lines
      • Path
      • Inserting images
      • Pixel-level operation
      • Text
      • Shadow
      • Color Gradient
    • Section

Briefly

The HTML 5 Specification introduces many new features, one of the most anticipated is the canvas element. HTML 5 canvas provides a way to draw graphics by using JavaScript, which is simple but powerful. Each canvas element has a "context" (pictured as a page on the drawing board) in which any shape can be drawn. The browser supports multiple canvas contexts and provides graphical rendering capabilities through different APIs.

Most browsers support the 2D canvas context-including Opera, Firefox, Konqueror and Safari. And some versions of Opera also support 3D canvas, Firefox can also be used in the form of plug-in support 3D canvas:

    • Download Opera with support for 3D canvas, HTML video and File I/O
    • Articles about the Opera 3D canvas context
    • Articles about the Firefox 3D canvas context

This article describes 2D canvas

Basics and how to use basic canvas functions, such as lines, shapes, images, and text. To understand this article, you'd better understand the basics of JavaScript.

Click here to download the sample code in bulk

Canvas Basics

The way to create a canvas is simply to add elements to the HTML page <canvas> :

<canvas id= "MyCanvas" width= "height=", >fallback content, in case the browser does no support CANVAS.</CA Nvas>

To be able to reference elements in JavaScript, it is best to set the ID for the element, and the canvas to set the height and width.

Once you've created the canvas, let's prepare the brush. To draw a graphic in the canvas, you need to use JavaScript. First, the canvas is found through the  getElementById function

Element, and then initializes the context. You can then use the context API to draw a variety of shapes. The following script draws a rectangle in the canvas ( click here to see the effect ):

Get a reference to the Element.var Elem = document.getElementById (' MyCanvas ');//Always check for properties and methods,  To make sure your code doesn ' t break//in other browsers.if (Elem && elem.getcontext) {//Get the 2d context.  Remember:you can only initialize one context per element.  var context = Elem.getcontext (' 2d '); if (context) {//are done!    Now you can draw your first rectangle.    You are need to provide the (x, y) coordinates, followed by the width and//height dimensions.  Context.fillrect (0, 0, 150, 100); }}

You can place the above code in the document head section, or in an external file.

The context API

After describing how to create a canvas, let's take a look at the 2D canvas API to see what we can do with these functions.

Basic lines

The example above shows how easy it is to draw a rectangle.

fillStyle strokeStyle You can easily set the fill and line of a rectangle by using the and properties. Color values are used in the same way as CSS: hexadecimal number, RGB (), Rgba (), and Hsla () (if browser support, such as Opera

Firefox 3).

fillRectyou can draw a filled rectangle by drawing it. strokeRectyou can use a rectangle that draws only the border without padding. If you want to clear some of the canvas can be used clearRect . The parameters of the above three methods are the same:,,, x y width height . The first two parameters set (x, y) coordinates, and the last two parameters set the height and width of the rectangle.

You can use lineWidth attributes to change the line weight. Let's see how it 's used fillRect ,

strokeRect clearRect and other examples :

Context.fillstyle = ' #00f '; Bluecontext.strokestyle = ' #f00 '; Redcontext.linewidth = 4;//Draw Some rectangles.context.fillRect (0, 0, 60, 0); (Context.clearrect); Context.strokerect (30, 25, 90, 60);

This example is shown in Figure 1.



Figure 1:fillrect, Strokerect and

Clearrect

Path

Any shape can be drawn through the canvas path (path). You can draw the outline first, and then draw the border and fill. Creating a custom shape is simple, using  beginPath() start drawing, and then drawing your drawing using lines, curves, and other graphics. Call fill and stroke add fills or set borders when you are finished drawing. Invokes the  closePath() end of custom graphics drawing.

Here is an example of a drawing triangle:

Set the style Properties.context.fillStyle = ' #00f '; context.strokestyle = ' #f00 '; context.linewidth = 4;context.begi Npath ();//Start from the Top-left point.context.moveTo (10, 10); Give the (x, y) Coordinatescontext.lineto (Context.lineto), Context.lineto (ten);//done! Now fill the shape, and draw the stroke.//note:your shape won't be visible until your call any of the and the Methods.contex T.fill (); Context.stroke (); Context.closepath ();

See Figure 2.



Figure 2: Triangles

In another more responsible example , lines, curves, and arcs are used .

Inserting images

drawImagemethod allows you to insert additional images in the canvas

(  img and canvas elements). In Opera, you can draw SVG graphics in canvas again. This method is more complex and can have 3, 5, or 9 parameters:

    • 3 parameters: The most basic drawImage method of use. One parameter specifies the image location, and the other two parameters set the position of the image in the canvas.
    • 5 Parameters: Intermediate drawImage usage, including the 3 parameters described above, plus two parameters indicate the width and height of the inserted image (if you want to change the image size).
    • 9 Parameters: The most complex drawImage miscellaneous use method, including the above 5 parameters, the other 4 parameters set the position and height width in the source image. These parameters allow you to crop the source image dynamically before the image is displayed.

Here are some examples of the above three ways to use :

Three arguments:the element, destination (x, y) coordinates.context.drawImage ( img_elem dx dy );//Five Arguments:the element, destination (x, y) coordinates, and destination//width and height (if you want to resize the source image). Contex T.drawimage ( img_elem dx dy dw dh );//Nine arguments:the element, source (x, y) coordinates, source width and//heigh T (for cropping), destination (x, y) coordinates, and destination width//and height (resize). Context.drawimage ( img_elem sx syswshdxdydwdh);

The effect is shown in Figure 3.



Figure 3: drawImage .

Pixel-level operation

The four-tier Context API provides three methods for pixel-level operations: createImageData , getImageData , and

putImageData

ImageDataThe object holds the image pixel values. Each object has three properties: width , height and

data。 The data property type is Canvaspixelarray, which is used to store width*height*4 a pixel value. Each image is known as an RGB value and a transparency alpha value (its value is 0 to

255, including Alpha!). The order of pixels is stored from left to right, top to bottom, by row.

To better understand the principle, let's look at an example-- draw a red rectangle

Create an ImageData Object.var imgd = Context.createimagedata (50,50), var pix = imgd.data;//Loop over each pixel and set A transparent red.for (var i = 0; n = pix.length, i < n; i + = 4) {Pix[i] = 255;//red channel pix[i+3] = 127;// Alpha channel}//Draw The ImageData object at the given (x, y) coordinates.context.putImageData (IMGD, 0,0);

Note: Not all browsers are implemented  createImageData . In a supported browser, you need to  getImageData get the object through a method  ImageData . Please refer to the sample code .

ImageDataMany functions can be accomplished by doing so. If you can implement image filters, or you can implement mathematical visualizations (such as fractals and other effects). The following effect implements a simple color reversal filter :

CanvasPixelArrayFrom the given coordinates and dimensions.var IMGD = Context.getimagedata ( x y width height x y );

Figure 4 shows the Opera after using this filter

Image (Figure 3 is the original).



Figure 4: Color reversal Filter

Text

Although the recent WebKit version and the Firefox 3.1 nightly build started to support the text API, I decided to still introduce the text API here in order to ensure the integrity of the article.

contextObject can set the following text property:

    • font: Text font, same as CSS

      font-familyProperty
    • textAlign: Text horizontal alignment. Desirable attribute values:,, start end left ,

      right, center . Default value:

      start.
    • textBaseline: Vertical alignment of text. Desirable attribute values:,, top hanging middle ,

      alphabetic, ideographic , bottom . Default value: alphabetic .

There are two ways to draw text: fillText and strokeText . The first draws a fillStyle filled text, which draws only strokeStyle the bounding text. The parameters are the same: the position (x, y) coordinates of the text and text to be drawn. There is also an optional option--maximum width. If needed, the browser shrinks the text so that it fits the specified width.

Text alignment properties affect text and settings

The relative position of the (x, y) coordinates.

Here is an example of drawing "Hello World" text in a canvas

Context.fillstyle = ' #00f '; context.font = ' Italic 30px sans-serif '; context.textbaseline = ' top '; Context.filltex T (' Hello world! ', 0, 0); Context.font = ' bold 30px sans-serif '; Context.stroketext (' Hello world! ', 0, 50);

Figure 5 is its.



Figure 5: Text effects

Shadow

Currently only Konqueror and Firefox 3.1 nightly build support Shadows API. The properties of the API are:

    • shadowColor: Shadow color. Its value is the same as the CSS color value.
    • shadowBlur: Sets the degree of shadow blur. The larger the value, the more blurred the shadow. The effect is the same as Photoshop's Gaussian blur filter.
    • shadowOffsetXand shadowOffsetY : The X-and Y-offsets of the shadow, measured in pixels.

Here is an example of a canvas shadow :

Context.shadowoffsetx = 5;context.shadowoffsety = 5;context.shadowblur = 4;context.shadowcolor = ' Rgba (255, 0, 0, 0.5 ) '; context.fillstyle = ' #00f '; Context.fillrect (20, 20, 150, 100);

The effect is shown in Figure 6.



Figure 6:canvas Shadow effect--blue rectangle, red Shadow

Color Gradient

In addition to CSS colors,  fillStyle and strokeStyle properties can be set to CanvasGradient objects. -- CanvasGradient You can use color gradients for lines and fills.

To create CanvasGradient an object, you can use two methods: createLinearGradient and createRadialGradient . The former creates a linear color gradient, which creates a circular color gradient.

After you create a color gradient object, you can use the object's addColorStop methods to add a color intermediate value.

The following code shows how color gradients are used:

You need to provide the source and destination (x, y) coordinates//for the gradient (from where it starts and where it ends ). var gradient1 = context.createlineargradient (sx,sy,dx,dy);//Now you can add colors in your gradient.//The first argument tells the position for the color in your gradient.  the//accepted value range is from 0 (gradient start) to 1 (gradient end).//The second argument tells the color you want, Using the CSS color format.gradient1.addColorStop (0, ' #f00 '); Redgradient1.addcolorstop (0.5, ' #ff0 '); Yellowgradient1.addcolorstop (1, ' #00f '); blue//for the radial gradient-also need to provide source//and destination circle radius.//the (x, y) coordinates D Efine The Circle Center points (Start and//destination). var Gradient2 = context.createradialgradient (sx,sy,sr,dx,dy,dr)///Adding colors to a radial gradient are the same as Adding colors to linear//gradients.

I've also prepared a more complex example that uses linear color gradients, shadows, and text . The effect is shown in Figure 7.



Figure 7: Example of using linear color gradients

Canvas Demo

If you want to know what you can do with canvas, you can see the following works:

    • Opera Widgets:
      • Simaquarium
      • Artist ' s

        Sketchbook
      • Spirograph
    • Online Engineering and Demos
      • Newton polynomial
      • canvascape– "3D Walker"
      • Paint.web–paintingdemo, Open-source
      • Star-field Flight
      • Interactive blob
Section

Canvas is one of the most anticipated features of HTML 5 and is now supported by most WEB browsers. Canvas can help create games and enhance the graphical user interface. The context

The API provides a lot of graphical drawing capabilities-I hope that through this article you understand the use of canvas and you are interested to learn more!

ZT from hp:http://duanxin.me/#/articles/html5-canvas-the-basics/

HTML 5 canvas--Basic syntax

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.