Canvas API, Popular canvas Basics (III.)

Source: Internet
Author: User

The full text of the triangle, circular and other related graphics, unfamiliar students can go out to the right, first look at the previous article, then continue our graphics-curve.

Learn mathematics, or more understand JS students know the Bezier curve, of course, in mathematics, this is a profound knowledge, JS inside the Bezier curve is generally used to do animation, in fact, there are other places, such as the pen tool in Photoshop, CorelDRAW inside the Bezier tools and so on, canvas, there is also a manifestation of

Of course, if you are simply drawing a curve, you can also use the previous method:

var canvas = document.getElementById ("canvas"); var ctx = Canvas.getcontext ("2d");    Ctx.arc (100,100,100,0,90*math.pi/180,false); Ctx.stroke (); Ctx.beginpath (); Ctx.moveto (103,103); Ctx.arcto (183,83,162,182,40); ctx.stroke ();

If you want to draw a zigzag line, it's hard, this has the following protagonist debut:

Quadraticcurveto (Cpx,cpy,x,y) two times Bezier curve

Parameters: cpx,cpy represents the first control point, and X, Y represents the end point

Add the starting point, that is, 3 points control a curve, in fact, this is similar to the use of arcto, the difference is that the arcto is required to specify the radius of the arc, because it is a line in 2 lines to draw a circle and a straight line of the curve, then this two times Bezier curve of the drawing principle is what? Let's draw a picture together:

The approximate rule of quadratic Bezier curves: From the starting point, the closer the curve to the control point, the steeper the curve, and then slowly away from the control point, the curve becomes more and more gentle until the end point, and the curve is tangent to the start and end points

This control point is not a bit like a magnet, attracting the movement of the curve, as the saying goes, we'll try it:

Ctx.moveto (50,50); Ctx.lineto (70,120); Ctx.lineto (200,80); Ctx.stroke (); Ctx.beginpath (); Ctx.moveto (50,50); Ctx.quadraticcurveto (70,120,200,80); Ctx.stroke ();

See, is not this, of course, the degree of curvature of the curve is a formula, but we do not need to care, just remember one thing: the curve near the control point, the steeper the curve, away from the control point, the curve more flat, Oh!

Again, the difference between ArcTo and Quadraticcurveto, is it clear now?

Now let's introduce the three-time Bezier curve:

Beziercurveto (Cpx1,cpy1,cpx2,cpy2,x,y) three times Bezier curve

Parameters: Cpx1,cpy1 represents the first control point, Cpx2,cpy2 represents the second control point X, Y represents the end point

Including the starting point together with 4 points to determine a curve, this is the same as the two times Bezier curve principle is the same, just one more control point, its essence or that sentence: curve close to the control point, the more steep curve, away from the control point, the curve is more flat

Let's start with a simple example (a U-shape):

Ctx.moveto (20,20); Ctx.beziercurveto (20,100,200,100,200,20); Ctx.stroke ();

For example, the first is, the second is the schematic, the curve starts from the starting point, there is a control point below, then the steeper the curve, to the second control point and the tangent of the curve position, because the 2 control points affected, the curve began to slowly flatten, because the 2 control points are just symmetrical, so to the middle point, the curve out Then continue to be affected by 2 control points, where the role of the second control point more and more, know the first control point and the tangent point of the curve position, the curve continues to be the role of the second control point, the reverse force, to the end, the amount, do not understand, well, do not understand it, remember that sentence summary of the line!

The classic example is a sine chart (with 2 Bezier curves, one positive u and one inverse u):

Ctx.beginpath (); Ctx.moveto (20,150); Ctx.beziercurveto (20,50,150,50,150,150); Ctx.stroke (); Ctx.beginpath (); Ctx.moveto (150,150); Ctx.beziercurveto (150,250,280,250,280,150); Ctx.stroke ();

Of course, three times Bezier curve do not know can draw U-shape, but any curve can be drawn, only you do not think, no painting, haha, brain hole play big!

All said painting painting, Can't always do ink painting ah, I like color, colorful color, tu, canvas is also possible, canvas and CSS3 can set the gradient, so that, see the rainbow is not far away, hehe

Let's take a look at how the CSS3 gradient is set, and then compare the canvas gradient, we all know that the gradient is divided into linear and radial gradients, and we hit compare:

Linear gradient:

. Box1 {    width:500px;     height:50px;     background: -webkit-linear-gradient (left, Red 0, #0F0 20%,rgb (51,102,255) 50%, Rgba (204,255,0,0.8) 100%);}

CSS3 can specify a color, support a variety of color formats, and can specify where the color is located, and CSS3 can also specify the direction of the gradient:

. Box1 {    width:500px;     height:50px;     background: -webkit-linear-gradient (45deg, Red 0, #0F0 20%,rgb (51,102,255) 50%, Rgba ( 204,255,0,0.8) 100%);}

The direction can be defined by the angle, and the 45 degree angle is the gradient from bottom left to right.

Radial gradient:

. Box2 {    width:300px;     height:200px;     background:-webkit-radial-gradient (red 0, #0F0 20%,rgb (51,102,255) 50%, Rgba (204,255,0,0.8) 100%) ;}

The gradient origin is centered, and the gradient color is a color gradient between hundred percent

As can be seen, the radial gradient is the center as the origin, one lap to the outside diffusion, also support custom colors, support a variety of color formats, support the specified position, but also can set the origin and gradient (round, oval):

. Box2 {    width:300px;     height:200px;     background:-webkit-radial-gradient (bottom left, ellipse,red 0, #0F0 20%,rgb (51,102,255) 50%, Rgba ( 204,255,0,0.8) 100%);}

Lower left of origin, gradient shape is ellipse

. Box2 {    width:300px;     height:200px;     background:-webkit-radial-gradient (bottom left, circle,red 0, #0F0 20%,rgb (51,102,255) 50%, Rgba (204,255,0,0.8) 100%);}

Bottom left, gradient shape is circular

The above is just a simple list of CSS3 gradient style, of course, CSS3 gradient certainly more than these, here is mainly to compare the canvas gradient style, by the way popular!

The gradient of the canvas is relatively simple, and there are not so many Huahuachangzi:

Createlineargradient (x1,y1,x2,y2) Creating a linear gradient

Parameter: X1,y1 indicates the gradient start point x2,y2 represents the gradient end point

Createradialgradient (X1,Y1,R1,X2,Y2,R2) Creating a radial gradient

Parameters: X1,y1 represents the start center coordinate of the gradient, R1 represents the radius of the start circle of the gradient x2,y2 represents the center coordinate of the gradient end, and R2 the radius of the end circle of the gradient

Gradient.addcolorstop (stop,color) specifies the color and position in the gradient object

Parameter: Stop value 0-1, which represents the position between the start and end of the gradient color for gradient colors

Note that the object to add the gradient color here is not the context, but the gradient

How to use it? See a small example of linear gradients:

A misunderstanding of this popular science:

Ctx.fillrect (50,50,200,50); var line = ctx.createlineargradient (50,50,200,50); Line.addcolorstop (0, ' Red '); Line.addcolorstop (0.2, ' #0F0 '); Line.addcolorstop (0.5, ' rgb (51,102,255) '); Line.addcolorstop ( 1, ' Rgba (204,255,0,0.8) ');

This is wrong, nothing can come out!

Supposedly, it should be the first to create an image, and then add the gradient color, the general law is so, such as painting, such as CSS, but the canvas is not the same, the focus is:canvas usually set style, must be placed in front of the drawing , how to understand this sentence?

Method of Drawing: Fill (), fillRect (), stroke (), Strokerect (), rect ()

That setting: such as text type font, font size, font color, font shadow, gradient path class such as line, rectangle, circle, background, gradient, etc.

So the correct format is:

var line = ctx.createlineargradient (50,50,200,50);        Line.addcolorstop (0, ' Red ');        Line.addcolorstop (0.2, ' #0F0 ');        Line.addcolorstop (0.5, ' rgb (51,102,255) ');        Line.addcolorstop (1, ' Rgba (204,255,0,0.8) ');                 = line ;        Ctx.fillrect (50,50,200,50);

You can see the canvas can customize the color, support a variety of color formats, support the specified location (with 0-1 of the number, similar to the percentage), compared to CSS3, I think the canvas gradient color area more accurate!

Well, since canvas can set the gradient style like CSS3, could you set the direction? How to set? Take the above code for example, we draw a picture:

The picture may be a bit of a mask, explain, the first graph shows the effect of our code above, the gradient direction is (50,50)---(200,50), is a horizontal line, indicating that the direction is from left to right gradient, if I set the coordinate direction to (50,50)--(200, 100), such as the second picture, is the gradient from the upper left to the lower right corner? Let's try it:

var line = ctx.createlineargradient (50,50,200,100); Line.addcolorstop (0, ' Red '); Line.addcolorstop (0.2, ' #0F0 '); Line.addcolorstop (0.5, ' rgb (51,102,255) '); Line.addcolorstop ( 1, ' Rgba (204,255,0,0.8) ');         = Line;ctx.fillrect (50,50,200,50);

You can see the angle is correct, the Createlineargradient 2 coordinates is to indicate the gradient direction, then the canvas's radial gradient will be the same as CSS3? Let's write a small example:

var line = ctx.createradialgradient (150,150,0,150,150,200); Line.addcolorstop (0, ' Red '); Line.addcolorstop (0.2, ' #0F0 '); Line.addcolorstop (0.5, ' rgb (51,102,255) '); Line.addcolorstop ( 1, ' Rgba (204,255,0,0.8) ');         = Line;ctx.fillrect (50,50,200,150);

As you can see, if the shape is not a square, the radial gradient circle is still a positive circle, a bit different from the CSS3 gradient mechanism (CSS3 is an ellipse, look at the CSS3 above), and the gradient area is based on two circles, let's change the area of these 2 circles to see:

var line = ctx.createradialgradient (150,150,50,150,150,100); Line.addcolorstop (0, ' Red '); Line.addcolorstop (0.2, ' #0F0 '); Line.addcolorstop (0.5, ' rgb (51,102,255) '); Line.addcolorstop ( 1, ' Rgba (204,255,0,0.8) ');         = Line;ctx.fillrect (50,50,200,150);

Compared to the above figure can be seen in 50-100 of the interval is a gradient, the other place is the end of the color fill, then the center of the corner?

var line = ctx.createradialgradient (50,50,0,50,50,200); Line.addcolorstop (0, ' Red '); Line.addcolorstop (0.2, ' #0F0 '); Line.addcolorstop (0.5, ' rgb (51,102,255) '); Line.addcolorstop ( 1, ' Rgba (204,255,0,0.8) ');         = Line;ctx.fillrect (50,50,200,150);

The effect is the same as the CSS3 style, color more accurate, if the center of the 2 circle is different, what will be the reaction?

var line = ctx.createradialgradient (50,50,0,150,150,200); Line.addcolorstop (0, ' Red '); Line.addcolorstop (0.2, ' #0F0 '); Line.addcolorstop (0.5, ' rgb (51,102,255) '); Line.addcolorstop ( 1, ' Rgba (204,255,0,0.8) ');         = Line;ctx.fillrect (50,50,200,150);

A center in the upper left corner, a center in the middle

Hey, what ghost, forget, if you want normal radial gradient, or the same center, different center is too weird, hold it!

Can the radial gradient set the ellipse like CSS3? Cough, I can only borrow a line: My concubine can't do!

Let's take a cool gradient app:

Ctx.font = "40px Microsoft Jas Black"; var line = ctx.createlineargradient (10,100,200,100); Line.addcolorstop (0, ' Red '); Line.addcolorstop (0.2, ' #0F0 '); Line.addcolorstop (0.5, ' rgb (51,102,255) '); Line.addcolorstop ( 1, ' Rgba (204,255,0,0.8) '= line;ctx.filltext ("Crazy drag cool hanging bombing days", 10,100);

Here we introduce another color-related attribute--transparent!

Globalalpha = num parameter: num value 0-1 Sets or returns the current transparency value of the drawing

A reunion asked, according to the word meaning is global transparency, then it is global? I also want to ask, let's try it:

Ctx.fillstyle = "Red"; Ctx.fillrect (50,50,100,100= 0.5= "green"; Ctx.fillrect ( 100,100,100,100= "Blue"; Ctx.fillrect (150,150,100,100);

As you can see, the first one is not transparent, and the back 2 is transparent, so if I close the path, will this effect be the same:

= "Red"; Ctx.fillrect (50,50,100,100); Ctx.closepath ();         = 0.5;         = "Green"; Ctx.fillrect (100,100,100,100); Ctx.closepath ();         = "Blue"; Ctx.fillrect (150,150,100,100); Ctx.closepath ();

The result is the same, indicating that it is "human" as its name, it is really a global, then put it into a closed path, will pollute other paths?

= 0.5= "Red"; Ctx.fillrect (50,50,100,100= "green"; Ctx.fillrect (100,100,100,100 ); Ctx.closepath ();         = "Blue"; Ctx.fillrect (150,150,100,100); Ctx.closepath ();

Horse eggs, is a serious nuclear pollution ah, penetrating force so strong? What if I just want to make the first transparent, the back opaque? What am I going to do about it?

In order to solve this problem, we need to introduce 2 methods, also is a pair of clown AH:

Context.save () Saves the state of the current environment

Context.restore () returns the previously saved path state and properties

How do you understand this pair of clown?

As you can understand: when the Save () method is set, it is equivalent to placing the subsequent drawing on a stack, isolating it, and knowing that you see Restore (), return to the original position, for example ha, like a bunch of candy, save () is a part of the candy into the box, restore () is to close the box, continue to pick up the candy, but the candy in the box will not be mixed with other candies, well, you can understand, especially note that the restore () method must have save () to work, you think Ah, there is no box candy, how can you close the box?

Let's take a look at their magical skills:

= 0.5= "Red"; Ctx.fillrect (50,50,100,100= "green"; Ctx.fillrect (100,100,100,100 ); Ctx.closepath ();         = "Blue"; Ctx.fillrect (150,150,100,100); Ctx.closepath ();

Oh, I feel the whole world is perfect in a moment! In the face of the fierce global variables, properties or methods, we can use the above to avoid them to the part of our need to infringe ( why this is to say that the infringement, will make people want to dirty ), is indeed a good skill!

Back to the Globalalpha, its usefulness is still a lot of, path, graphics, text can be set transparent, then we come to a text transparent look:

Ctx.font = "40px Microsoft Jas Black"; var line = ctx.createlineargradient (10,100,200,100); Line.addcolorstop (0, ' Red '); Line.addcolorstop (0.2, ' #0F0 '); Line.addcolorstop (0.5, ' rgb (51,102,255) '); Line.addcolorstop ( 1, ' Rgba (204,255,0,0.8) '== 0.3; Ctx.filltext ("Crazy drag cool hanging bombing days", 10,100);

Well, introduce here today, the content of the latter is more complex, need serious preparation, so it!

Canvas API, Popular canvas Basics (iii)

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.