HTML 5 canvas-basic syntax

Source: Internet
Author: User
  • Directory

  • Brief Introduction
  • Canvas Basics
  • 2d context API
    • Basic Line
    • Path
    • Insert Image
    • Pixel-level operations
    • Text
    • Shadow
    • Color gradient
  • Section
Brief Introduction

Html5. Specifications introduce many new features, one of the most promising ones iscanvasElement. HTML 5canvasIt provides a method for Drawing Images through JavaScript, which is simple but powerful. EverycanvasEach element has a "context" (as a page on the drawing board) where any image can be drawn. The browser supports multiple canvas contexts and uses different APIsSupports drawing.

Most browsers support 2D canvas context, including opera, Firefox, Konqueror, and safari. In addition, some versions of opera also support 3D canvas, and Firefox also supports 3D canvas through plug-ins:

  • Download opera that supports 3D canvas, HTML video, and file I/O
  • Article on opera 3D canvas Context
  • About Firefox 3D canvas
    Context article

This article introduces 2D canvas
Basic 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.

You can click here to batch download the instance code of this Article

Canvas Basics

The canvas creation method is simple. You only need to add<canvas>Element:

<canvas id="myCanvas" width="300" height="150">Fallback content, in case the browser does not support Canvas.</canvas>

In order to reference elements in Javascript, it is best to set the ID for the element. You also need to set the height and width for the canvas.

After creating the canvas, let's prepare the paint brush. Javascript is required to draw a graph in the canvas. First pass getElementByIdThe function finds the canvas.
And then initialize the context. Then you can use the context API to draw various images. The following script draws a rectangle in the canvas (click here to view 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) {// You are done! Now you can draw your first rectangle. // You only 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 documentheadOr put it in an external file.

2d context API

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

Basic Line

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

PassFillStyleAndStrokeStyleYou can easily set the filling and line of a rectangle. The usage of color values is the same as that of CSS:Hexadecimal number, RGB(), Rgba() And HSLA() (If supported by a browser, such as opera
10 and Firefox 3 ).

PassfillRectYou can draw a rectangle with padding. UsestrokeRectYou can draw a rectangle without borders. You can useclearRect. The parameters of the preceding three methods are the same:X,Y,Width,Height. The first two parameters set the coordinates (x, y), and the last two parameters set the height and width of the rectangle.

AvailableLineWidthProperty to change the line width. Let's take a look.fillRect,
strokeRect clearRectAnd other examples:

context.fillStyle   = '#00f'; // bluecontext.strokeStyle = '#f00'; // redcontext.lineWidth   = 4;// Draw some rectangles.context.fillRect  (0,   0, 150, 50);context.strokeRect(0,  60, 150, 50);context.clearRect (30, 25,  90, 60);context.strokeRect(30, 25,  90, 60);

This example is shown in Figure 1.


Figure 1: fillrect, strokerect, and
Clearrect

Path

You can draw any shape using the canvas path. You can draw an outline first, then draw a border and fill it. It is easy to create a custom shape. beginPath()Start drawing, and then draw your graph using straight lines, curves, and other figures. Called after drawingfillAndstrokeTo add or set the border. Call closePath()End custom image painting.

The following is an example of creating a triangle:

// Set the style properties. context. fillstyle = '# 00f'; context. strokestyle = '# f00'; context. linewidth = 4; context. beginpath (); // start from the top-left point. context. moveTo (10, 10); // give the (x, y) coordinatescontext. lineto (100, 10); context. lineto (10,100); context. lineto (10, 10); // done! Now fill the shape, and draw the stroke. // Note: Your shape will not be visible until you call any of the two methods. context. fill (); context. stroke (); context. closepath ();

See figure 2.


Figure 2: Triangle

In another example, we use straight lines, curves, and arcs.

Insert Image

drawImageThis method allows you to insert other images into the canvas.
( imgAndcanvasElement ). In opera, you can draw SVG images in canvas. This method is complex and can have three, five, or nine parameters:

  • Three parameters: the most basicdrawImageUsage. One parameter specifies the image position, and the other two parameters set the position of the image in the canvas.
  • Five parameters: IntermediatedrawImageThe usage includes the three parameters described above. Add two parameters to specify the width and height of the inserted image (if you want to change the image size ).
  • Nine parameters: the most complexdrawImageThe preceding five parameters are included. The other four parameters are used to set the position and height of the source image. These parameters allow you to dynamically crop the source image before displaying the image.

The following are examples of the above three methods:

// 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).context.drawImage(img_elem, dx, dy, dw, dh);// Nine arguments: the element, source (x,y) coordinates, source width and // height (for cropping), destination (x,y) coordinates, and destination width // and height (resize).context.drawImage(img_elem, sx, sy, sw, sh, dx, dy, dw, dh);

The effect is shown in figure 3.


Figure 3:drawImage.

Pixel-level operations

The 2D context API provides three methods for Pixel-level operations:createImageData,getImageData, And
putImageData.

ImageDataThe object stores the pixel value of the image. Each object has three attributes:Width,HeightAnd
Data.DataThe attribute type is canvaspixelarray, which is used for storage.width*height*4Pixel value. Each pixel has an RGB value and a transparency Alpha value (the value ranges from 0
255, including alpha !). The pixel sequence is stored from left to right, from top to bottom, by row.

To better understand its principles, let's look at an example-drawing 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 have implemented createImageData. In the supported browsers getImageDataMethod acquisition ImageDataObject. See the sample code.

PassImageDataMany functions can be completed. For example, Image filters or mathematical visualization (such as fragment and other special effects) can be implemented ). The following special effects implement a simple Color Reversal filter:

// Get the CanvasPixelArray from the given coordinates and dimensions.var imgd = context.getImageData(x, y, width, height);var pix = imgd.data;// Loop over each pixel and invert the color.for (var i = 0, n = pix.length; i < n; i += 4) {  pix[i  ] = 255 - pix[i  ]; // red  pix[i+1] = 255 - pix[i+1]; // green  pix[i+2] = 255 - pix[i+2]; // blue  // i+3 is alpha (the fourth element)}// Draw the ImageData at the given (x,y) coordinates.context.putImageData(imgd, x, y);

Figure 4 shows the opera with this filter
Image (figure 3 is the source image ).


Figure 4: Color Reversal Filter

Text

Although the text API is supported only in the latest WebKit version and Firefox 3.1 nightly build, I decided to introduce the text API here to ensure the integrity of the article.

contextYou can set the following text attributes for an object:

  • font: Text font, same as CSS
    font-familyAttribute
  • textAlign: Horizontal alignment of text. Optional property values:start,end,left,
    right,center. Default Value:
    start.
  • textBaseline: Vertical alignment of text. Optional property values:top,hanging,middle,
    alphabetic,ideographic,bottom. Default Value:alphabetic.

There are two ways to draw text:fillTextAndstrokeText. First draw bandFillstyleFilled text, which is drawn onlyStrokestyleBorder text. The two parameters are the same: the coordinates of the text and text to be drawn (x, y. There is also an optional option-maximum width. If necessary, the browser will reduce the text so that it can adapt to the specified width.

Text alignment attributes that affect text and settings
The relative position of the (x, y) coordinate.

The following is an example of drawing "Hello World" text in the canvas.

context.fillStyle    = '#00f';context.font         = 'italic 30px sans-serif';context.textBaseline = 'top';context.fillText  ('Hello world!', 0, 0);context.font         = 'bold 30px sans-serif';context.strokeText('Hello world!', 0, 50);

Figure 5 shows it.


Figure 5: Text Effect

Shadow

Currently, only Konqueror and Firefox 3.1 Build support the shadows API. The API attributes are:

  • shadowColor: Shadow color. The value is consistent with the CSS color value.
  • shadowBlur: Sets the shadow blur level. The larger the value, the blurrier the shadow. The effect is the same as that of the Gaussian blur filter in Photoshop.
  • shadowOffsetXAndshadowOffsetY: The offset between x and y of the shadow, in pixels.

The following is an example of 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 the CSS color, fillStyleAndstrokeStyleAttribute can be setCanvasGradientObject. -- PassCanvasGradientYou can use color gradient for lines and fills.

To createCanvasGradientObject, you can use two methods:createLinearGradientAndcreateRadialGradient. The former creates a linear color gradient, and the latter creates a circular color gradient.

After creating a color gradient object, you can useaddColorStopMethod to add the color median.

The following code demonstrates how to use a color gradient:

// 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 you also need to provide source // and destination circle radius. // The (x, y) coordinates define the circle center points (START and // destination ). vaR gradient2 = context. createradialgradient (SX,Sy,Sr,DX,Dy,Dr); // Adding colors to a radial gradient is the same as adding colors to linear // gradients.

I have also prepared a more complex example using linear color gradient, shadow, and text. The effect is shown in figure 7.


Figure 7: Linear color gradient example

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.