Canvas basic learning (I): canvas basic learning

Source: Internet
Author: User
Tags linecap

Canvas basic learning (I): canvas basic learning

I. Overview

Canvas is basically the same as the use of other HTML5 labels, but it is equivalent to creating a canvas in a browser, where you can draw images, create animations, or even 3D games. Because canvas must adapt to the resolutions of different terminals, set the height and width in the label as much as possible, which also complies with W3C standards. The code format is as follows. When the browser does not support the canvas label, the text is displayed.

<Canvas id = "main" width = "800" height = "600"> your browser does not support canvas. </canvas>

In the coordinate system of canvas, the coordinate origin is in the upper left corner, and the right side is the positive direction of the X axis, and the downward side is the positive direction of the Y axis, as shown in

In canvas, you must first obtain the context of canvas, and then call the API to draw images.

var canvas = document.getElementById("main"),    ctx = canvas.getContext("2d");

 

2. Draw and fill lines

In the canvas, the image rendering code can be wrapped by the beginPath () and closePath () functions, which are mainly used to split each painting to indicate the start and end. The main calling methods for line drawing are moveTo (x, y), lineTo (x, y), stroke (), arc (), arcTo (), and fill (), the attributes used include lineWidth, lineCap, lineJoin, strokeStyle, and fillStyle.

1. Draw a line segment with rounded corners

ctx.beginPath();ctx.strokeStyle = "black";ctx.lineWidth = 6;ctx.lineCap = "round";ctx.moveTo(400,400);ctx.lineTo(600,400);ctx.stroke();ctx.closePath();

Is:

StrokeStyle indicates the line color, lineWidth indicates the line width, lineCap sets the line edge to rounded, and lineCap attributes include butt | round | square. The first value is the default value indicating the straight edge, round is the rounded corner and square is the edge of the square. MoveTo (x, y) indicates that the starting point of the line is the (x, y) Coordinate, while lineTo (x, y) sets the end point of the line to (x, y ), finally, draw by calling the stroke () method.

2. Draw two line segments with the focus rounded corner

ctx.beginPath();ctx.strokeStyle = "black";ctx.lineWidth = 10;ctx.lineJoin = "round";ctx.moveTo(400,500);ctx.lineTo(600,500);ctx.lineTo(600,600);ctx.stroke();ctx.closePath();

Is:

The difference with the demo above is that the lineJoin attribute is used, and it also has three attributes: bevel | round | miter. The first one is the default value, which indicates the diagonal angle and the miter indicates the sharp angle. At the same time, lineTo (x, y) can call multiple times to draw line segments. Therefore, you can use the moveTo () and lineTo () Methods to draw polygon.

3. Draw and fill the rectangle with color

ctx.beginPath();        ctx.moveTo(50,50);ctx.lineTo(100,50);ctx.lineTo(100,100);ctx.lineTo(50,100);ctx.lineTo(50,50);ctx.lineWidth = 4;ctx.strokeStyle = "red";ctx.stroke();ctx.fillStyle = "blue";ctx.fill();ctx.closePath();

Is:

After drawing a polygon using the moveTo () and lineTo () methods, you can call the fill () method to fill the color in a closed range, fillStyle is used to set the color in the closed interval. If you do not need the stroke () method, that is, do not draw the line of the outer border, you can save the last method that returns to the starting point ctx. lineTo (50, 50), because fill () automatically connects the start and end to get a closed range.

 

If it is a simple rectangle rather than an irregular changeable shape, you can directly call the canvas api methods strokeRect (x, y, w, h) and fillRect (x, y, w, h); the first two parameters represent the coordinates of the start point, and the last two represent the width and height of the rectangle.

ctx.beginPath();ctx.lineWidth = 3;ctx.strokeStyle = "darkgray";ctx.strokeRect(50,50,200,100);ctx.closePath();ctx.beginPath();ctx.fillStyle = "coral";ctx.fillRect(300,50,200,100);ctx.closePath();

Is:

 

4. Draw an arc chart

The first is the arc (x, y, r, beginPi, endPi, anticlockwise) function. The first two parameters represent the x and y coordinates of the center, and the r in the middle represents the circle radius, the last two parameters indicate the start radians and end radians. The last two parameters indicate whether to draw them counterclockwise. The default value is false, Which is clockwise. In the canvas, the radians of the circle are a fixed value, either clockwise or counterclockwise. For example:

ctx.beginPath();ctx.arc(320,200,50,0,Math.PI*2);ctx.lineWidth = 3;ctx.strokeStyle = "black";ctx.stroke();ctx.fillStyle = "chartreuse";ctx.fill();ctx.closePath();

Is:

 

You can also draw an arc using arcTo (x1, y1, x2, y2, r);, Which is used with moveTo (x, y), (x, y) (x1, y1) and (x1, y1) (x2, y2) take the two line segments as the tangent, draw an arc with the radius of r, and the start and end points are the two cut points.

ctx.beginPath();ctx.lineTo(400,200);ctx.arcTo(500,200,500,300,100);ctx.strokeStyle = "aqua";ctx.stroke();ctx.closePath();

Is:

The last step is to plot the curve of the besell curve. Due to the complexity of the mathematical algorithm, there is not much research.

A. Quadratic besell Curve

Cxt. quadraticCurveTo (x1, y1, x2, y2 );

It is also mixed with cxt. moveTo (x0, y0). It draws an arc for the control point through (x1, y1 ).

Http://blogs.sitepointstatic.com/examples/tech/canvas-curves/quadratic-curve.html

This URL is the URL for testing the secondary besell curve.

B. Cubic besell Curve

Cxt. bezierCurveTo (x1, y1, x2, y2, x3, y3 );

It is also used in combination with cxt. moveTo (x0, y0). It draws an arc for the control point through (x1, y1) and (x2, y2 ).

Http://blogs.sitepointstatic.com/examples/tech/canvas-curves/bezier-curve.html

This is the site for testing the three-way besell curve.

(Ps: The cubic curve is better than the quadratic curve, and he can draw various prominent arcs and waves)

 

Iii. Graphic Transformation

No matter which language processes images, there is an idea. That is, first determine the graph painting function, and then use the graph transformation function to change the displacement, rotation angle, and size of the graph.

In canvas, because canvas is a state-based programming, we mentioned that it is used to draw a straight line and color between a vertex and a vertex.

Context. beginPath ();

Context. closePath ();

These two functions can isolate the state of the functions between points, and can also complete closed graphics, that is, the first and last points are automatically connected.

Such standard writing is also required in graphic transformation. They are

Context. save ();

Context. restore ();

Use these two functions to isolate function transformation Functions

1. translat

Context. translat (x, y)

It is used to translate the image, x is the distance for horizontal translation, and y is the distance for vertical translation.

ctx.save();
ctx.translate(50,50);
ctx.beginPath();
ctx.strokeRect(10,10,20,20);
ctx.closePath(); 
ctx.restore();

Is:

Originally, this rectangle should be drawn in the upper left corner. After graphical transformation, it is shifted to the x and y directions by 50 pixels (PS: note the function call of graphic transformation, to be executed before the function is drawn)

 

2. rotate

Context. rotate (rot );

This method is used to set the Rotation Angle of the image, where the rot should be a radian. If the angle is input, it needs to be converted, for example, 80. Some must be Math. PI * 80/180.

ctx.save();ctx.rotate(20*Math.PI/180);ctx.beginPath();ctx.fillRect(100,100,50,50);    ctx.closePath();ctx.restore();

Is: 20 degrees shifted clockwise

 

3. scale

Context. scale (x, y)

This method is used for image scaling. x is the horizontal scaling ratio, and y is the vertical scaling ratio.

(PS: this function has a problem, that is, the displacement in the upper left corner of the image will change in the same proportion and the border line of the image will also change)

ctx.save();ctx.scale(0.5,0.5);ctx.beginPath();ctx.fillRect(100,100,200,200);    ctx.closePath();ctx.restore();

It is to scale the x and y directions of a square to half the size.

4. transform

Context. transform (a, B, c, d, e, f );

First, this method is the sum of the above methods, because this method changes the image by means of a matrix of units. In essence, the image is composed of a matrix of numbers 1 and 1, as shown in the following table.

A C E
B D F
0 0 1

 

A Indicates horizontal scaling. The default value is 1. B indicates horizontal skew. The default value is 0. c Indicates vertical skew. The default value is 0;

D Indicates Vertical Scaling. The default value is 1. The default value is 0;F indicates the vertical displacement. The default value is 0;

Therefore, the transfrom function can be used to implement the above three types of image transformations.

 

4. Miscellaneous

1. text display

Ctx. fillText (string, x, y, [maxlen]);

Ctx. strokeText (string, x, y, [maxlen]);

The first function is the text value to be written, where x and y are the coordinates of the text. Maxlen is an optional parameter and sets the maximum length of the text.

You can set relevant parameters for the text.

The default value of ctx. font is "20px sans-serif"

Its Parameters include context. font = font-style font-variant font-weight.

Font-size font-family. Each parameter has a word value.

Context. textAlign = left center right this attribute sets the center, center, and right of the text

Context. textBaseline = top middle bottom this attribute is used to set the vertical top, center, and bottom of the text.

Ctx. beginPath (); var str = "Gu yuefeng" ctx. strokeStyle = "red"; ctx. fillStyle = "aqua"; ctx. font = "40px Arial"; ctx. textAlign = "center"; ctx. textBaseline = "middle"; ctx. strokeText (str, 100,100,200); ctx. fillText (str, 100,150,200); ctx. closePath ();

Is:

 

2. Shadow

There is no shadow function in the canvas. It is added through the state. You can use the following function to add the shadow effect for lines, rectangles, circles, and texts.

Ctx. shadowColor = "gray"; // sets the color of the Shadow background.

Ctx. shadowOffsetX = 10; // sets the highlighted pixel in the x-axis direction of the shadow. The value can be negative.

Ctx. shadowOffsetY = 10; // it means the same as above, but this is for the Y axis

Ctx. shadowBlur = 5; // set the Blur degree of the Shadow. If the value is 0, the Blur is not blurred. The greater the value, the heavier the Blur.

Ctx. beginPath (); var str = "Gu yuefeng" ctx. fillStyle = "aqua"; ctx. font = "40px Arial"; ctx. textAlign = "center"; ctx. textBaseline = "middle"; ctx. shadowColor = "gray"; ctx. shadowOffsetX = 5; ctx. shadowOffsetY = 5; ctx. shadowBlur = 3; ctx. fillText (str, 100,150,200); ctx. closePath ();

Is:

 

3. global variables and transparency

Ctx. globalAlpha sets the global transparency. Its default value is 1, and the image on the canvas is transparent when it is changed to a value ranging from 0 to 1. The function scope is global. Therefore, use the save () and restore () methods for package usage.

 

4. EditingCtx. clip ();

This function has only one function mentioned above. It is a mix of functions that can draw closed spaces, such as lineTo, fillRect, and arc, the purpose is to draw a canvas only in a closed space. The drawing beyond this space is not displayed,The most common method is to make searchlights.

ctx.save();ctx.beginPath();ctx.arc(200,200,100,0,Math.PI*2);ctx.clip();ctx.fillStyle = "chartreuse";ctx.fillRect(100,100,200,200);ctx.closePath();ctx.restore();

Is:

First define a circular editing area and draw a square with a large range, but only images with a circular range can be displayed.

 

5. Interaction

In a canvas, the entire canvas is used as a canvas, and all the images drawn in the canvas cannot interact as an object through event binding, therefore, the event binding in the canvas is directly bound to the canvas, and then interacts with the judgment of the coordinates operated by the user on the canvas.

The basic method is as follows:

A. Bind events to the canvas tag. JS and jQuery become

B. Obtain the coordinates of user operations on the canvas.

Var x = event. clientX-canvas. getBoundingClientRect (). left;

Var y = event. clientY-canvas. getBoundingClientRect (). top;

It calculates the operating coordinates of the user on the entire page and the top left margin of the canvas on the page.

 

 

Related Article

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.