My journey of canvas drawing (common basic interface)


Introduction to canvas

1. Create a canvas

<canvas id="myCanvas" width="400" height="400"></canvas>

Note that writing width and height attributes directly in the tag is different from writing them in style.

The width and height of the canvas label are the actual width and height of the canvas, and the graphics are drawn on it. The width and height in style are the height and width of canvas to be rendered in the browser. If the width and height of canvas are not specified or the values are incorrect, they are set to the default values( width:300px , height:150px )。

two . Draw an image

First, get the canvas element

var canvas=document.getElementById("myCanvas");

Then create the context object:

var context=canvas.getContext("2d");

Getcontext (“2D”) object is a built-in HTML5 object, which has many methods to draw paths, rectangles, circles, characters and add images. Context is a 2D drawing context environment. All interfaces of canvas drawing are provided by context.

Now we have a canvas that we can draw.

3. Path

  • context . beginPath (); Represents the beginning of a new drawing
  • context.closePath (); represents that the current path should be closed and closed

Because canvas draws graphics based on state, when drawing multiple line segments with different widths and styles, canvas will automatically draw based on the last state, so beginpath should be used at this time () To start a new drawing; When you draw a polygon, combine beginpath () And closepath () It can draw a correct and complete closed graph.

4. Straight line

(1) Line segment

  • context.moveTo (x, y) define the starting coordinates of the line
  • context.lineTo (x, y) define the line end coordinates (point to draw the line to a certain place)

Note that there is no straight line on the page after writing these two methods, because painting on canvas is divided into two steps. The first step is to draw the path, and the second step is to stroke or fill.So finally, we need to add:

  • context.stroke();

Basic attributes of lines:

  • context.lineWidth Set line width (value is numeric)
  • context.strokeStyle Set line style (generally color value)
  • context.lineCap Set the style of the two ends of the line (values include button (default), round and square)
  • context.lineJoin Set the style of both ends of the line (values include miter (default), bevel and round)
    When setting context.miterLimit If the width of the sharp corner is greater than this value, it will be displayed in the form of bevel.

(2) Rectangle

  • context.rect In (x, y, width, height), X and Y represent the starting coordinates of the rectangle, width represents the width, and height represents the height
  • context.fillRect (x, y, width, height) can draw the filled rectangle directly, while stroke rext (x, y, width, height) can draw the stroke rectangle directly
  • context.clearRect (x, y, width, height) can clear a rectangular area, which is often used in animation drawing

5. Curve

(1) Round

  • context.arc In (x, y, R, start, stop, anticlockwise (optional)), X and Y represent the coordinates of the center of the circle, R represents the radius, and start and stop represent the start and end positions of the arc. Anticlockwise is an optional parameter to set whether the drawing is in the counterclockwise direction. The default is false, that is, the drawing is in the clockwise direction.

Notice the starting position of the arc, 0pi is in the positive direction of X axis (right), 0.5pi is in the positive direction of Y axis (bottom), 1Pi is in the negative direction of X axis (left), 1.5pi is in the negative direction of Y axis (top), 2pi returns to the positive direction of X axis (right). And the position of 0-2pi is unchanged whether it is drawn clockwise or counterclockwise.

(2) Arc


X0 and Y0 are the starting points of the arc; x1, Y1, X2 and Y2 are the two points of the tangent. The two lines of the three points are the two tangents of the arc, but the tangents are not necessarily on the two auxiliary lines.

(3) Quadratic Bezier curve


This method is similar to the arc drawing method, except that (x0, Y0) is the starting point of the curve, and (X2, Y2) is the end point of the curve. Because this method is more flexible and practical than acrto().
Specific examples can be understood in the…See.

(4) Cubic Bezier curve


In this method ( x1 , y1 ) and ( x2 , y2 ) It’s two control points, not one ( x0 , y0 ) and ( x3 , y3 ) It is the starting point and the ending point.
Specific examples can be understood in the

6. Filling

Except to draw lines context.stroke (), you can also fill closed graphics:


Basic properties of filling:

  • context.fillStyle Set fill style

Note that when you need to draw a pattern with both fill and stroke, you need to fill before stroke, otherwise the general width of stroke will be covered by fill.

In addition to filling in the same colors, canvas also uses methods to fill in gradients, images, canvases, and videos.

(1) Linear gradient:

var gradient = context.createLinearGradient(xstart,ystart,xend,yend);

Xstart, ystart, xend and yend form two coordinate points, and the connected line is a gradient line, which represents the gradient of color along this line; while the stop parameter is a floating-point number between 0-1, which represents the position of color.

(2) Radial gradient:

var gradient = context.createRadialGradient(x0,y0,r0,x1,y1,r1);

The principle of radial gradient is very similar to that of linear gradient. X0, Y0, R0 and x1, Y1, R1 form two circles, and the radial gradient changes according to these two circles. The second method is the same as that of linear gradient.

(3) Picture, canvas, video fill

var pattern = context.createPattern(img,repeat-style);

Repeat style has four parameters: no-repeat, repeat-x, repeat-y and repeat.

Note that the first parameter img can be filled with canvas and video besides img. At the same time, the filling method used here can also be used on the strokestyle () method

seven . Graphic transformation

There are three methods for graphics transformation

  • context.translate(x,y)
  • context.rotate(deg)
  • context.scale(sx,sy)

Note that in canvas, the effect of graphics transformation is superimposed, so the second transformation does not start from the initial state, which causes some trouble. But with (); and context.restore () can save the state of the transformation so that one of the transformations does not affect the others.
At the same time, note that the scale transformation will affect the starting point coordinates and the width of the border.

There is also an advanced method:

  • context.transform(a,b,c,d,e,f)

Where a, B, C, D, e and F are actually values in an identity matrix.

a. D represents horizontal and vertical scaling; B, C represents horizontal and vertical tilt; E, f represents horizontal and vertical displacement

When there are too many transformations and you don’t know how to recover, you can use context . setTransform () Method, which means to restore the original state first, and then transform according to the set state.

8. Words

context.font = "bold 40px Arial";
/* context.strokeText(string,x,y,[maxlen]);*/

Filltext() can write solid fonts, while stroketext() can write hollow fonts. The optional parameter [manxlen] indicates the maximum width of the text to be drawn, and the unit is px.

Basic properties of font:

  • context.font Style text
    context.font =”Font style font variant font weight font size font family”, the default value is “20px san serif”.

The default value of font style is normal [default], and the options are italics and oblique.
The default value of font variant is normal [default], and small caps [small caps] is optional.
The default value of font weight is normal [default], and the options are lighter [thinner], bold [thicker]. You can also use 100-900 to control, 100-400 is normal, 500-700 is bold.
Font size, font family and CSS are similar, so I won’t introduce them more.

  • context.textAlign Set the text left and right alignment (values are left, center, right)
  • context . Textbaseline sets the top and bottom of the text , middle , bottom , alphabeticdefault, ideographic, hanging)
  • context.measureText (string). Width can get the width of the whole text

9. Pictures

var img = new Image();
img.src = "***.jpg";

So you can create an image in the canvas~

10. Others

(1) Shadow

  • context.shadowColor Set shadow color
  • context.shadowOffsetX Sets the shadow horizontal displacement distance
  • context.shadowOffsetY Sets the shadow vertical displacement distance
  • context . Shadowblur sets the shadow blur distance

(2) Synthesis

  • Globalalpha sets the global transparency (the default value is 1 and the value range is 0) – 1)
  • Global composite operation sets the state of the image when it overlaps (the value is “source over”)default, destination over (the one drawn first is on top of the one drawn later). There are nine values: source over, source atop, source in, source out, destination over, destination atop, destination in, destination out, lighter, copy, XOR)

(3) Clip area

  • context.clip () set the next drawing area in the edited area

(4) Click detection

  • context.isPointInPath (x, y) check whether the point is within the current planned path

The standard method to get the click position of mouse in canvas is as follows:

x=event.clientX - canvas.getBoundingClientRect().left;
y=event.clientY - canvas.getBoundingClientRect().top;

(5) Add your own method to the context object

CanvasRenderingContext2D . prototype . The way you define it =  function (){}

Summary and thoughts

Now that you have learned some common methods of canvas, you should try to make an effect or a small game. This learning article is for referenceHTML5 Canvas | Rookie courseDetailed explanation of canvas drawing on MOOCS, a text version of the tutorial, a video version of the tutorial, and combined with their own understanding summed up into a canvas entry article. I hope I can be more and more powerful ~ Come on, everyone ~