Basic concepts of HTML canvas

Source: Internet
Author: User

Canvas

The canvas element is the element of the new home of HTML5, which is responsible for setting an area in the page, which can then be used to dynamically draw graphics in this area via JavaScript

Basic usage

When you use a canvas element, you must first set its width properties and height properties to specify the size of the drawing area. The content that appears in the canvas label is fallback information that is displayed if the browser does not support the canvas element.

<canvas id="canvas" width="300" height="200">您的浏览器不支持Canvas</canvas>

To draw on this canvas, you need to get its drawing context, get a reference to the drawing context object, call the getContext() method, the method receives a parameter, that is, the name of the context, passed 2d in, you can get a 2D context object, you can also pass webgl in the object that gets the WEBGL context.

var canvas = document.getElementById("canvas");if (canvas.getContext) {    var ctx = canvas.getContext(‘2d‘);}//在使用canvas元素之前,首先要检测是否有getContext()方法,有些浏览器会将HTML规范之外的元素创建为默认的HTML元素对象,这种情况下,即使获取了id为canvas的元素,也不一定是canvas元素,没有getContext()方法。

Using the toDataURL() method, you can export the image drawn on the canvas element, which receives a parameter, the MIME type of the image, and applies to any context in which the image is created.

var canvas = document.getElementById(‘canvas‘);if (canvas.getContext) {    //获取图像的数据URI    var imgURL = canvas.toDataURL(‘img/png‘);    //显示图像    var image = document.createElement(‘img‘);    image.src = imgURL;    document.body.appendChild(image);}
The context

Use the methods provided by the 2D drawing context. You can draw simple 2D graphics, such as rectangles, arcs, and paths. The coordinates of the 0,0 context start at the upper-left corner of the canvas element, the coordinate origin is (), the horizontal direction represents the x-axis, the right is positive, the vertical direction represents the y-axis, and the downward is positive.

Fills and strokes

Padding fills a shape with a specified style (color, gradient, or image), which you can use strokeStyle to specify the style.
The stroke is the edge of the graphic, and this action uses the fillStyle property to specify the style.
fillStylestrokeStylethe value of the and property can be a string, a gradient object, or a pattern object whose default value is #000000, and if you use a string value that represents a color, you can use any form of the color value specified in the CSS, hexadecimal code, RGB, RGBA, HSL, Hsla, and so on.

ctx.strokeStyle = "red"; //指定描边颜色ctx.fillStyle = "#0000ff"; //指定填充颜色
Draw a rectangle

The rectangle can be drawn directly by the context object, with the following methods:

    • FillRect (x, y, Width, height): Draws a rectangle with the upper-left coordinate (x, y), width wide, height height, and fills the pattern specified by FillStyle
    • Strokerect (x, y, Width, height): Draws the upper-left coordinate to (x, y), width to width, height-height rectangle, and strokes by Strokestyle-specified pattern
    • Clearrect (x, y, Width, height): Clears the rectangular area and actually makes a portion of the area transparent.
 <! DOCTYPE html> 

Operating effect:

The width of the stroke line can be controlled by using lineWidth attributes, its property values can be any number of integers, and you can use lineCap properties to control whether the shape at the end of the line is flat ( butt ), round () round , or Square ( square ), and the lineJoin property can control how the depression intersects in a round () round , skew ( bevel ), or miter ( miter ).

Draw Path

Canvas uses a state-based approach to drawing, meaning that the result of your drawing depends on the state of your current settings, and we use strokeStyle and fillStyle specify the color of strokes and fills, and when we give these two properties a new value again, The fill color and stroke color of the redrawn shape will follow. When you draw a path, you can set the properties of a path first, such as the above, and so on, and strokeStyle fillStyle lineWidth then start drawing the route, and finally decide to draw the path as a fill or stroke, and then specify the properties of the new path.
To draw a path, you first call the beginPath() method, which means to start drawing a new path, and then draw the path using the following method:

    • Arc (x, y, radius, startangle, Endangle, counterclockwise): Draws an arc at the center of (x, y), radius of radius, angle (in radians) StartAngle and Endangle, respectively, and the last parameter indicates whether to be calculated in a counterclockwise direction, or false to indicate clockwise.
    • ArcTo (x1, y1, x2, y2, radius): Draws an arc from the previous point, up to (x2, y2), and gives the specified radius radius through the point (x1, y1).
    • Beziercurveto (C1x, c1y, C2X, c2y, X, y): Draws a curve from the previous point to (x, y) and passes (C1x, c1y) and (C2X, c2y) two points.
    • LineTo (x, y): Draws a line from the previous point to (x, y).
    • MoveTo (x, y): Moves the current brush to (x, y) without drawing the path.
    • Quadraticcurveto (CX, CY, X, y): Draws a two-time curve from the previous point to (x, y) and passes (CX, CY).
    • Rect (x, y, Width, height): Draws a rectangle from (x, y), width and height, respectively.

After the path is drawn, use the closePath() method to finish drawing the path. stroke() fill() You can then use the or method to draw the line or fill, or create a clipping region with the ' clip () ' method.

<! DOCTYPE html>

Results:

* in this note, arc() in the method, the positive direction of X, that is, the angle of the horizontal right direction is 0, then the clockwise direction increases, the y positive direction, namely the vertical downward direction is 90 degrees, the horizontal left direction is 180 degrees, the vertical upward direction is 270 degrees, again to the horizontal right direction, is 360 degrees, so, Want to create a full circle, you can write this: ' Ctx.arc (100,100,100,0,math.pi 2,true) ' * *

About closePath() , there is another function, if it is called and closePath() then executed stroke() , the graph will be closed automatically, otherwise it will not be closed. As shown in the following example:

ctx.beginPath()ctx.arc(100,100,100,0,Math.PI / 2, true);ctx.closePath()ctx.stroke()

Results:

Draw text

The three-way context also provides methods for drawing text, with two main ways to draw text:

    • Filltext (str, x, y,? width)
    • Stroketext (str, x, y,? width)

Both methods have four parameters: the string of the text to be drawn, the x-coordinate, the y-coordinate, the optional parameter, and the maximum pixel width. Both of these methods are based on the following three properties:

    • Font: Represents the text style, size, and font that can be specified using the format of the specified font in CSS, such as "10px Arial"
    • TextAlign: Represents the alignment of text, the possible values are "start", "End", "left", "right" and "center", where "start" and "left", "End" and "right" have the same effect, but the former is recommended.
    • Textbaseline: Represents the baseline of the text, the possible values are "top", "hanging", "middle", "alphabetic", "ideographic", and "bottom"

In fact, and respectively, the horizontal alignment and vertical alignment of the textAlign textBaseline text are determined.

<!DOCTYPE html>

Operation Result:

Transform

Through the transformation of the context, the processed image can be drawn to the canvas, when the drawing context is created, the transformation matrix is initialized with the default values, and when the transformation is used, different transformation matrices are used for processing, resulting in different effects.
You can modify the transformation matrix by using the following methods:

    • Rotate (angle): Rotates angle radians around the origin
    • Scale (ScaleX, ScaleY): Scales the image, multiplies the X-direction by ScaleX, multiplies the Y-direction by ScaleY
    • Translate (x, y): Move the coordinate origin to (x, y)
    • Transform (M1_1,m1_2,m2_1,m2_2,dx,dy): Modifies the transformation matrix directly by multiplying the following matrix: \begin{bmatrix} m1_1 & M1_2 & dx\m2_1 & m2_2 & DY \ 0 & 0 & 1 \end{bmatrix}
    • Settranform (M1_1,m1_2,m2_1,m2_2,dx,dy): Resets the transformation matrix to the default value, and then calls transform ()
<! DOCTYPE html>

Operation Result:

Drawing an image

The three-way context object provides support for the image, and if you want to draw an image on the canvas, you can use the DrawImage () method, which has several possibilities depending on your needs.

    1. An element is passed in, and the x and Y coordinates of the starting point of the image are drawn

      var image = document.images[0]ctx.drawImage(image,10,10)
    2. IMG element, image start X, y, Target image width and height
      ctx.drawImage(image, 50, 10 20 30)

    3. The image to draw, 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, the y-coordinate of the target image, the width of the target image, the height of the target image.
<!DOCTYPE html>

Operation Result:

Shadow

The three-way context automatically draws a shadow for a shape or path based on the values of several properties.

    • Shadowcolor: Shadow color in CSS color format, default to Black
    • Shadowoffsetx: Shadow offset in shape or path x-axis direction, default = 0
    • Shadowoffsety: Shadow offset in the direction of the y-axis of a shape or path, default 0
    • Shadowblur: Number of blurred pixels, default = 0
<!DOCTYPE html>

Run results

Gradient

The

Gradient is represented by an canvasgradient instance and can be created and modified through a 2D context.
Create a linear gradient you can use the createlineargradient () method, which has four parameters: the x-coordinate of the starting point, the y-coordinate of the starting point, the x-coordinate of the endpoint, and the y-coordinate of the end point. After the
has created a gradient object, you can use the addcolorstop () method to specify the color label, which receives two parameters: the color label position and the CSS color value, and the color label position is a number between 0 (the starting color)-1 (the ending color).
Finally, set FillStyle or Strokestyle to this object to use a gradient to draw a shape or stroke.
When creating a radial gradient, you can use the createradialgradient () method, which receives 6 parameters that correspond to the radius of the center of the two circles. The first three parameters specify the center coordinate x, y and radius of the start circle, and the last three parameters refer to the center coordinate of the end circle, x, y, radius.

<! DOCTYPE html>

Operation Result:

Mode

Patterns are duplicate images that can be used for filling or stroke implementation.
Create a new pattern: createPattern() There are two parameters: an IMG element, a string that represents how the image is repeated, where the value of the second parameter is the same as the value of the CSS's Background-repeat property, including, repeat repeat-x repeat-y andno-repeat

var image = document.images[0],    pattern = ctx.createPattern(image, "repeat")ctx.fillStyle = patternctx.fillRect(10,10,150,150)
Working with image data

The cube context can use the getImageData() data that gets the original image, which receives 4 parameters: the x and y coordinates of the paint area to get its data, and the height and width of the region's pixels.
var imageData = context.getImageData(10,5,150,150)
The returned object is an instance of ImageData, with each ImageData object having three properties: Width,height and Data,data are an array that holds the data for each pixel in the image, and in the data array, each pixel is saved with 4 elements. Indicates red, green, blue, and transparency values, respectively.

<! DOCTYPE html>

Run results

Synthesis

There are also two properties that apply to all drawing operations in the 2D context

    • Globalalpha: A value between 0-1 that specifies the transparency of all draws, defaults to 0, and if all subsequent operations are based on the same transparency, you can set the Globalalpha to the appropriate value, draw it, and then set it to the default value of 0
    • Globalcompositionopreation: Indicates how the drawing after drawing is combined with the first drawing, the value of this property is a string, the possible values are as follows:
      • Source-over: Default value, after which the drawing is drawn above the first drawing
      • Source-in: After drawing the graphic with the first drawing overlap part courseware, the other parts are all transparent
      • Source-out: After the drawing of the graphic with the first drawing does not overlap part of the courseware, the other parts are completely transparent
      • Source-atop: After drawing the drawing with the first drawing of the graphic repeated part of the visible, first draw the graphic is not affected
      • Destination-over: The drawing is placed below the first drawing, only the part below the transparent pixel is visible
      • Destination-in: After drawing the graphic below the first drawing, the part that does not overlap is completely transparent
      • Destination-out: The overlapping portion of the drawing's drawing after erasing the drawing with the first drawing
      • Destionation-atop: The drawing is drawn in the shape below the first drawing, two non-overlapping places, the first drawing will be completely transparent
      • Lighter: After drawing the drawing with the value of the overlapping part of the drawing first, make the part brighter
      • Copy: Draws a graphic that completely replaces the first drawing that overlaps with it
      • XOR: Performs an "XOR" operation on the portion of the drawing that overlaps with the first drawn graphic

Basic concepts of HTML canvas

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.