JavaScript Advanced Programming Learning Notes Chapter 15th-Using canvas drawing

Source: Internet
Author: User

I. Basic usage

1. To use the <canvas> element, you must first set its width and Height properties to specify the size of the area that can be plotted. You can add a style to the element through CSS, and if you don't add any styles or do not draw any graphics, you won't see the element in the page.

2. To draw on this canvas (canvas), you need to get the drawing context. To get a reference to the drawing context object, you need to call the GetContext () method and pass in the name of the context. Before using the <canvas> element, it is important to first detect the existence of the GetContext () method. Detection can be done in the following ways:

1 var drawing = document.getElementById ("drawing"); 2 // determine browser support <canvas> elements 3 if (drawing.getcontext) {4var context = Drawing.getcontext ("2d"); 5 // More Code 6 }

3. Using the Todataurl () method, you can export an image drawn on the <canvas> element. This method takes a parameter, which is the MIME type format of the image, and is suitable for any context in which the image is created. For example:

1 varDrawing = document.getElementById ("Drawing");2 //determine browser support <canvas> elements3 if(drawing.getcontext) {4 //gets the data URI of the image5 varImguri = Drawing.todataurl ("Image/png");6 //Display Image7 varImage = Document.createelement ("img");8IMAGE.SRC =Imguri;9 Document.body.appendChild (image);Ten}

Two. 2D Context:

1. Using the method provided by the 2D drawing context, you can draw simple 2D graphics, such as rectangles, arcs, and paths.

The coordinates of the 2.2D context start at the upper-left corner of the <canvas> element, and the origin coordinates are (0,0). All coordinate values are calculated based on the origin, the larger the x value, the more right, and the greater the y value, the higher the lower the point.

3. Fill and Stroke:

The two basic drawing operations for the

2D context are fills and strokes. The results of these two operations depend on two properties: FillStyle and Strokestyle. The values of these two properties can be strings, gradient objects, or schema objects, and their default values are #000000. If you assign them a string value that represents a color, you can use any format that specifies the color value in the CSS, including the color name, hexadecimal code, RGB, RGBA, HSL, or Hsla. For example:

1 var drawing = document.getElementById ("drawing"); 2 // determine browser support <canvas> elements 3 if (drawing.getcontext) {4var context = Drawing.getcontext ("2d"); 5 Context.strokestyle = "Red"; 6 context.fillstyle = "#0000ff"; 7 }

4. Draw the rectangle:

A rectangle is the only shape that can be drawn directly in a 2D context. The methods associated with rectangles include fillRect (), Strokerect (), and Clearrect (). All three methods can receive 4 parameters: the x -coordinate of the rectangle, the y -coordinate of the rectangle, the width of the rectangle, and the height of the rectangle. The units of these parameters are pixels.

FillRect (): The rectangle that the method draws on the canvas fills the specified color. The color of the fill is specified by the FillStyle property. Use the following:

1 // draw a red rectangle 2 context.fillstyle = "#ff0000"; 3 context.fillrect (10, 10, 50, 50);

Strokerect (): The rectangle that the method draws on the canvas uses the specified color stroke. The stroke color is specified by the Strokestyle property. Use the following:

1 // draw a red stroke rectangle 2 context.strokestyle = "#ff0000"; 3 context.strokerect (10, 10, 50, 50);

Clearrect (): This method clears the rectangular area on the canvas. Essentially, this method can make a rectangular area of the drawing context transparent.

5. Draw the path:

To draw a path, you must first call the Beginpath () method, which indicates that you want to start drawing a new path. Then, you can actually draw the path by calling the following methods.

  • Arc (x, y, radius, startangle, endangle, counterclockwise): With (x ,y) to draw an arc for the center, radius of radius, starting and ending angles (in radians) for StartAngle and
    Endangle. The last parameter indicates whether StartAngle and Endangle are calculated in a counterclockwise direction, and a value of false indicates a clockwise calculation.
  • ArcTo (x1, y1, x2, y2, radius): Draws an arc from the previous point, to (x2,y2), and crosses (x1,y1) with a given radius radius.
  • Beziercurveto (c1x, c1y, C2X, c2y, x, y): Draws a curve from the previous point, up to (x, y), and with (c1x,c1y) and (c2x,c2y ) is the control point.
  • LineTo (x, y): Draws a line from the previous point to (x,y).
  • MoveTo (x, y): Moves the drawing cursor to (x,y) without drawing a line.
  • Quadraticcurveto (CX, CY, X, y): Draws a two curve from the previous point, up to (x, y), and with (Cx,cy) as the control point.
  • Rect (x, y, width, height): Draws a rectangle starting from the point (x,y), specified by width and height, respectively. This method draws a rectangular path, not a separate shape drawn by Strokerect () and FillRect ().
  • Closepath (): After creating the path, you want to draw a line that connects to the beginning of the path.
  • Fill (): If the path is complete and you want to populate it with FillStyle, you can call the Fill () method.
  • Stroke (): Stroke the path, color using the Strokestyle property
  • Clip (): Create a clipping region on the path
  • Ispointinpath (): Receives x and y coordinates as parameters to determine if a point on the canvas is on the path before the path is closed

6. Draw the text:

There are two main methods of drawing text: Filltext () and Stroketext (). The Filltext () method draws text using the FillStyle property, while the Stroketext () method uses the Strokestyle property for text strokes. Both methods can receive 4 parameters: The text string to be drawn, the x -coordinate, the y -coordinate, and the optional maximum pixel width. Furthermore, both of these methods are based on the following 3 properties:

    • Font: Represents the text style, size, and font, specified in the format of the specified font in CSS, such as "10px Arial".
    • TextAlign: Represents the text alignment. Possible values are "start", "End", "left", "right" and "center". It is recommended that you use "start" and "end" instead of "left" and "right".
    • Textbaseline: Represents the baseline of the text. Possible values are "top", "hanging", "middle", "alphabetic", "ideographic", and "bottom".

7. Transform: You can modify the transformation matrix by the following methods.

    • Rotate (angle): Rotates the image angle radians around the origin.
    • Scale (ScaleX, ScaleY): Scales the image, multiplies the X-direction by ScaleX, and multiplies the ScaleY in the y direction. The default values for both ScaleX and ScaleY are 1.0.
    • Translate (x, y): Moves the coordinate origin to (x, y). After performing this transformation, the coordinates (0,0) become the points previously represented by (x, y).
    • Transform (M1_1, M1_2, m2_1, m2_2, DX, dy): Modifies the transformation matrix directly by multiplying the matrix as follows.
    • SetTransform (M1_1, M1_2, m2_1, m2_2, DX, dy): Resets the transformation matrix to the default state, and then calls transform ().
    • Save (): Save context State

8. Draw the Image:

DrawImage () function: A total of 9 parameters are required: The image to be drawn, the x -coordinate of the source image, the y -coordinate of the source image, the width of the source image, the height of the source image, the x -coordinate of the target image, and the Y- c4> coordinates, the width of the target image, and the height of the target image. This calls the DrawImage () method to get the most control. For example: context.drawimage (image, 0, ten, 0 , +, +);


9. Shadows: There are several properties

    • Shadowcolor: The shadow color in CSS color format, which is black by default.
    • SHADOWOFFSETX: The shadow offset of the shape or path x -axis direction, which defaults to 0.
    • Shadowoffsety: The shadow offset in the direction of the y -axis of the shape or path, which defaults to 0.
    • Shadowblur: Blur the number of pixels, default 0, that is, not blurred.

10. Gradients: Gradients are represented by canvasgradient instances and are easily created and modified through 2D contexts.

Createlineargradient (): Creates a new gradient that receives 4 parameters: the x -coordinate of the starting point, the y -coordinate of the origin, the x -coordinate of the end point, and the y -coordinate of the end point. When this method is called, it creates a gradient of the specified size and returns an instance of the Canvasgradient object. After you create a gradient object, the next step is to use the Addcolorstop () method to specify the color label. This method receives two parameters: the color label position and the CSS color value. The color label position is a number between 0 (the starting color) and 1 (the ending color). For example:

1 var gradient = context.createlineargradient (+,-); 2 gradient.addcolorstop (0, "white"); 3 gradient.addcolorstop (1, "Black");

Createradialgradient (): Creates a radial gradient (or radiation gradient) that receives 6 parameters that correspond to the center and radius of the two circles. The first three parameters specify the original heart (x and y) and radius of the starting circle, and the last three parameters refer to the
The original Heart (x and y) and radius of the end circle are determined.

11. Mode: The pattern is actually a duplicate image that can be used to fill or stroke a graphic. To create a new schema, you can call the Createpattern () method and pass in two parameters: an HTML element and a string representing how to repeat the image. Where the value of the second parameter is the same as the Background-repeat property value of the CSS, including "Repeat", "repeat-x", "repeat-y", and "no-repeat". For example:

1 var image = Document.images[0],2 pattern = Context.createpattern (image, "repeat"); 3 // Draw a rectangle 4 Context.fillstyle = pattern; 5 Context.fillrect (10, 10, 150, 150);

12. Get Raw data:

One of the obvious advantages of the getimagedata context is that the raw image data can be obtained through the (). This method receives 4 parameters: the x and y coordinates of the screen area where the data is to be obtained, and the pixel width and height of the area. The object returned by this function is an instance of ImageData. Each ImageData object has three properties: width, height, and data. Where the Data property is an array that holds each pixel in the image.



JavaScript Advanced Programming Learning Notes Chapter 15th-Using canvas drawing

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.