Canvas API Summary

Source: Internet
Author: User
Tags linecap repetition

From simple basic graphics to complex, cool animations, the 2D graphics rendering context obtained through the canvas element CanvasRenderingContext2D enables graphical drawing using a rich API. This article summarizes the APIs for all the rendering contexts used in previous canvas tutorials.

You can refer to the previous tutorials:

    • How to draw basic graphics can be consulted: Canvas basic graphics drawing
    • How to move the rotation scale for basic graphics can be consulted: Canvas graphics transformations
    • How to set basic graphic colors and styles can be consulted: canvas styles and colors
    • How to use external pictures and graphic combinations can be consulted: canvas using pictures, graphic combinations and cropping
    • Canvas how to save and load images can be consulted: Canvas image preservation
    • Canvas animation Tutorials and Examples:
    • Canvas Series Tutorials can be consulted: canvas

The methods and properties described below are the CanvasRenderingContext2D methods and properties of the object. The method is called as follows:

var=document.getElementById("canvas");var=canvas.getContext("2d");// 使用ctx即可调用ctx.fillStyle="rgba(0, 0, 200, 0.5)";ctx.fillRect (30,30,55,50);

More detailed interface API documentation can be found in the official documentation.

Basic graphic Drawing

Used to draw basic graphics. Refer to this article for more detailed usage: Canvas basic drawing

Rectangle Drawing (no path required)
    • void ctx.fillRect(x, y, width, height);
      • Draws a filled rectangle with the beginning of the rectangle at (x, y), and the size of the rectangle is width and height
    • void ctx.strokeRect(x, y, width, height);
      • In canvas, use the current drawing style to draw a rectangle with a starting point in (x, y), W width, h for height
    • void ctx.clearRect(x, y, width, height);
      • Sets the specified rectangular area (at points (x, y) as the starting point, the range is (width, height)) all pixels become transparent and erases everything drawn before

The above API parameters are described below:

    • xX-coordinate of the starting point of the rectangle (upper-left point)
    • yY-coordinate of the starting point of the rectangle
    • widthWidth of Rectangle
    • heightHeight of the rectangle
Draw text
    • void ctx.fillText(text, x, y [, maxWidth]);
      • Draw (fill) text at (x, y) position
    • void ctx.strokeText(text, x, y [, maxWidth]);
      • Draw (stroke) text at (x, y) position
    • ctx.measureText(text);
      • Returns a Textmetrics object that contains information about the size of the text (such as the width of the text)

The above API parameters are described below:

    • xX-coordinate of the beginning of text
    • yThe y-coordinate of the beginning of the text
    • textText that needs to be drawn
    • maxWidthOptional, maximum width to draw
Path graphics
  • void ctx.beginPath();
    • Start a new path by clearing the empty path list
  • void ctx.closePath();
    • Returns the point of the pen to the starting point of the current sub-path. It attempts to draw a line from the current point to the starting point. If the graphic is already closed or has only one point, then this method does nothing
  • void ctx.moveTo(x, y);
    • Moves the starting point of a new sub-path to (x, y) coordinates
  • void ctx.lineTo(x, y);
    • Use a straight line to connect the last point of the subpath to the x, Y coordinates
  • void ctx.quadraticCurveTo(cpx, cpy, x, y);
    • Add a 2-time Bezier curve path
    • cpx, cpyFirst control point (x, y) coordinates
    • x,yTo end point coordinates
  • void ctx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
    • Add a 3-time Bezier curve path. This method requires three points. The first, second point is the control point, and the third point is the end point. The starting point is the last point of the current path and can be modified by calling MoveTo () before the Bezier curve is drawn.
    • cp1x, cp1yFirst control point (x, y) coordinates
    • cp2x, cp2ySecond control point (x, y) coordinates
    • x,yEnd point coordinates
  • void ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise);
    • Draws an ARC path, where the center of the ARC path is at (x, y), the radius is r, and the direction specified by anticlockwise (clockwise by default) is drawn from StartAngle to the end of the Endangle.
    • x,yTo draw the center coordinate of the circle on which the arc is located
    • radiusAs Radius
    • startAngleand endAngle A parameter that defines the start and end radians for the x-axis as the base radian.
    • anticlockwiseAs a Boolean value that specifies the draw reverse, the default is false to indicate a clockwise direction. True indicates a counterclockwise direction.
  • void ctx.arcTo(x1, y1, x2, y2, radius);
    • Draws an ARC path based on the control point and radius, using the current stroke (the stop point for a function such as the previous MoveTo or LineTo). Draws an arc path between two tangents based on the line that the current stroke is connected to a given control point 1, and a line connected by Control point 1 to control point 2 as a tangent of a circle with a specified radius.
    • x1,y1Specify the coordinates of the first control point
    • x2,y2Specify the coordinates of the second control point
    • radiusSpecify the radius of the arc
  • void ctx.ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise);
    • Add an elliptical path, where the center of the ellipse is at (x, y), the radius is RadiusX and radiusy, in the direction specified by anticlockwise (the default clockwise), drawn from StartAngle, and ended with Endangle.
    • x,y(x, y) coordinates of the ellipse center
    • radiusXRadius of the elliptical long axis
    • radiusYRadius of the elliptical short axis
    • rotationThe rotation angle of the ellipse, expressed in radians (non-angular degrees)
    • startAngleThe angle of the starting point to be drawn, measured from the x-axis, expressed in radians (non-angular degrees)
    • endAngleThe angle of the end point that the ellipse will be drawn in radians (non-angular degrees)
    • anticlockwiseAs a Boolean value that specifies the draw reverse, the default is false to indicate a clockwise direction. True indicates a counterclockwise direction.
  • void ctx.rect(x, y, width, height);
    • Creates a rectangular path, where the starting position of the rectangle is (x, y), and the dimensions are width and height
Path
  • void ctx.fill();void ctx.fill(fillRule);void ctx.fill(path, fillRule);
    • Populate a subpath with the current style
    • pathThe path that needs to be populated Path2D
    • fillRuleAn algorithm that determines whether the point is within the path or outside the path: "Nonzero", "evenodd"
  • void ctx.stroke();void ctx.stroke(path);
    • Stroke sub-path using the current style
  • void ctx.clip();void ctx.clip(fillRule);void ctx.clip(path, fillRule);
    • Creates a clipping path from the current path. clip()after the call, all the information drawn will only appear inside the clipping path
  • boolean ctx.isPointInPath(x, y);boolean ctx.isPointInPath(x, y, fillRule); boolean ctx.isPointInPath(path, x, y);boolean ctx.isPointInPath(path, x, y, fillRule);
    • Determine if the current path contains a detection point
  • boolean ctx.isPointInStroke(x, y);boolean ctx.isPointInStroke(path, x, y);
    • Determine if the detection point is on the stroke of the path
Colors and styles

Controls the color and style of drawing graphics. Refer to this article for more detailed usage: Canvas styles and colors

Linear
    • ctx.lineWidth = value;
      • The width of the line. Default 1.0
    • ctx.lineCap = "butt" || "round" || "square";
      • The type of the end of the line. Allowable values: Butt (default), round, square
    • ctx.lineJoin = "miter" || "round" || "bevel";
      • Defines the type of inflection point at which two lines intersect. Allowable values: round, Bevel, miter (default)
    • ctx.miterLimit = value;
      • The miter face limit scale. Default 10
    • Array ctx.getLineDash();
      • Returns a set of numbers that describe the length of alternating line segments and spacing (coordinate space units). If the number of array elements is odd, the array elements are copied and duplicated. For example, setting the segment to [5, 15, 25] will get the following return values [5, 15, 25, 5, 15, 25].
    • void ctx.setLineDash(segments);
      • Sets the current line segment style
    • ctx.lineDashOffset = value;
      • Sets the dashed offset property, which is the number of float precision. The initial value is 0.0.
Text Style
    • ctx.font = value;
      • Sets the properties of the current font style when drawing text
      • valueA domstring string that conforms to the CSS font syntax. The default font is 10px Sans-serif.
    • ctx.textAlign = "left" || "right" || "center" || "start" || "end";
      • Text alignment Settings
    • ctx.textBaseline = "top" || "hanging" || "middle" || "alphabetic" || "ideographic" || "bottom";
      • Baseline alignment Settings
    • ctx.direction = "ltr" || "rtl" || "inherit";
      • Direction of text
Fill and stroke styles
    • ctx.fillStyle = color || gradient || pattern
      • The color and style inside the graphic. The default #000 (black).
      • colorDomstring string, converted to CSS color color value
      • gradientCanvasgradient object (linear gradient or radioactive gradient)
      • patternCanvaspattern objects (REPEATABLE images)
    • ctx.strokeStyle = color || gradient || pattern
      • The color and style of the graphics edge. Default #000 (Black)
Gradients and Patterns
    • CanvasGradient ctx.createLinearGradient(x0, y0, x1, y1);
      • Creates a gradient of a line specified along the parameter coordinates
    • CanvasGradient ctx.createRadialGradient(x0, y0, r0, x1, y1, r1);
      • Creates a radioactive gradient of a line specified along the parameter coordinates
    • CanvasPattern ctx.createPattern(image, repetition);
      • Creates a pattern using the specified picture (a canvasimagesource)
      • imageAn object that is a duplicate image source CanvasImageSource
      • repetitionDomstring, specifies how the image is repeated. The allowed values are: "Repeat" (both directions), "repeat-x" (horizontal only), "repeat-y" (vertical-only), "No-repeat" (neither).
Shadow
    • ctx.shadowBlur = level;
      • Describes the blur effect. Default 0
    • ctx.shadowColor = color;
      • The color of the shadow. Default Fully-transparent Black
    • ctx.shadowOffsetX = offset;
      • The offset in the horizontal direction of the shadow. Default 0
    • ctx.shadowOffsetY = offset;
      • The offset in the vertical direction of the shadow. Default 0
Transform

Objects in the CanvasRenderingContext2D rendered background will have a current transformation matrix, which can be controlled by some methods. This transformation matrix is applied when creating the current default path, drawing text, graphics, and path2d objects. For details, refer to: Canvas graphics transformation

  • void ctx.rotate(angle);
    • Increases the rotation in the transformation matrix, which represents a clockwise rotation angle and is expressed in radians
    • angleThe arc that rotates clockwise. If you want to calculate by angle value, you can use the formula: Degree * math.pi/180
  • void ctx.scale(x, y);
    • Adds a zoom transform to the canvas unit based on the x horizontal and y vertical directions
  • void ctx.translate(x, y);
    • Add a translation transformation by moving the canvas and canvas Origin x horizontal, Origin y vertically in the grid
  • void ctx.transform(m11, m12, m21, m22, dx, dy);
    • Use the matrix described by the method parameter to overlay the current transformation matrix multiple times.
    • m11Horizontal Scaling
    • m12Tilt in horizontal direction
    • m21Tilt in the vertical direction
    • m22Vertical orientation of scaling
    • dxHorizontal direction of movement
    • dyMove in a vertical direction
  • void ctx.setTtransform(m11, m12, m21, m22, dx, dy);
    • Re-sets the current transformation to the unit matrix and invokes the method with the same variable transform()
  • void ctx.resetTransform();
    • To reset the current transformation using the unit matrix
Synthesis

Specifies the combination of two or two graphs drawn before and after each other. Detailed instructions can be found here: Canvas using pictures, graphic combinations and cropping

    • ctx.globalAlpha = value;
      • Sets the value of the graphics and image transparency before compositing to the canvas. The default is 1.0 (opaque).
    • ctx.globalCompositeOperation = type;
      • globalAlphaset how to draw graphics and images on existing bitmaps by applying
Image-related

Set the interaction between the picture and canvas, detailed instructions can refer to here: Canvas image Preservation

Drawing an image

drawImagemethod is used to draw an image on a canvas in the following three forms:

    • void ctx.drawImage(image, dx, dy);
    • void ctx.drawImage(image, dx, dy, dWidth, dHeight);
    • void ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);

The parameters of the above methods have the following meanings:

    • imageDraws the element to the context. Allow any canvas image source (Canvasimagesource), for example: Htmlimageelement,htmlvideoelement, or Htmlcanvaselement
    • dxThe X-axis position of the upper-left corner of the target canvas
    • dyThe position of the Y-axis on the target canvas in the upper-left corner of the
    • dWidthDraws the width of the image on the target canvas. Allows you to scale the drawn image. If not, the width of the picture does not scale when drawing
    • dHeightThe height of the image to draw on the target canvas. Allows you to scale the drawn image. If not, the height of the picture does not scale when drawing
    • sxThe X-coordinate of the upper-left corner of the rectangular selection box of the source image that needs to be drawn into the target context
    • syThe Y-coordinate of the upper-left corner of the rectangular selection box of the source image that needs to be drawn into the target context
    • sWidthThe width of the rectangle selection box for the source image that needs to be drawn into the target context. If not, the entire rectangle starts at the coordinates of SX and SY and ends at the lower right corner of the image
    • sHeightThe height of the rectangle selection box for the source image that needs to be drawn into the target context
Pixel control
  • ImageData ctx.createImageData(width, height);ImageData ctx.createImageData(imagedata);
    • Creates a new, blank, ImageData object of the specified size. All the pixels are transparent in the new object.
    • widthImageDatathe width of the new object
    • heightImageDataheight of new object
    • imagedataFrom an existing ImageData object, copy an object with the same width and height. The image itself is not allowed to be copied.
  • ImageData ctx.getImageData(sx, sy, sw, sh);
    • Returns an ImageData object that describes the implied pixel data in the canvas area, which is represented by a rectangle with a starting point (SX, SY), SW, and SH
  • void ctx.putImageData(imagedata, dx, dy, [ dirtyX, dirtyY, dirtyWidth, dirtyHeight ]);
    • Draws the data from the existing ImageData to the bitmap. If a dirty rectangle is provided, only the pixels of the rectangle are drawn
    • dxThe position offset of the source image data in the target canvas (offset in the x-axis direction)
    • dyThe position offset of the source image data in the target canvas (offset in the y-axis direction)
    • dirtyXOptional, in the source image data, the position of the upper-left corner of the rectangular area. The default is the upper-left corner of the entire image data (x-coordinate)
    • dirtyYOptional, in the source image data, the position of the upper-left corner of the rectangular area. The default is the upper-left corner of the entire image data (y-coordinate)
    • dirtyWidthOptionally, the width of the rectangular area in the source image data. The default is the width of the image data
    • dirtyHeightOptional, in the source image data, the height of the rectangular area. The default is the height of the image data
Canvas status

The CANVASRENDERINGCONTEXT2D rendering environment contains the style state of multiple drawings (properties wired style, fill style, shadow style, Text style). The following methods will help you to use these states:

    • void ctx.save();
      • Use the stack to save the current drawing style state, you can use to restore() restore any changes
    • void ctx.restore();
      • Reverts to the most recent drawing style state, which is save() saved to the latest element in the state stack
    • ctx.canvas;
      • HTMLCanvasElementa reverse reference to read-only. If canvas it is not associated with an element, it may be null .

The above saved and restored canvas states include:

    • The current transformation matrix
    • The current clipping region
    • List of current dashed lines
    • The current value of the following property:
      • strokeStyleWireframe Fill Style
      • fillStyleGraphic Fill Style
      • globalAlphaGlobal transparency
      • lineWidthLine width
      • lineCapThread head (wire cap)
      • lineJoinLine-to-hand mode
      • miterLimitDiagonal Face limit ratio
      • lineDashOffsetDashed offset
      • shadowOffsetXShadow x Offset
      • shadowOffsetYShadow y Offset
      • shadowBlurShadow Blur degree
      • shadowColorShadow color
      • globalCompositeOperationGraphic Combination method
      • fontFont style
      • textAlignHow text is aligned
      • textBaselineText baselines
      • directionText direction
      • imageSmoothingEnabledWhether graphic scaling is smooth

Original address: http://uusama.com/632.html
If there is anything wrong and missing place, welcome to help treatise.

Canvas API Summary

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.