In canvas, in addition to using solid color, we can also set the fill and stroke styles to gradient: linear and radial gradients.
Linear gradient createlineargradient (x0,y0,x1,y1) returns canvasgradient
The four parameters are gradient start coordinate x, start coordinate y, end coordinate x, end coordinate Y.
The gradient fades along a line between two points.
Radial gradient createradialgradient (X0,Y0,R0,X1,Y1,R1) returns canvasgradient
Six parameters are
Start Center coordinate (x0,y0)
Start Center radius (r0)
End Point Center coordinate (x1,y1)
The center of the end radius (R1)
Both of these gradient methods return a Canvasgradient object that defines the Addcolorstop (Position,color) method.
Addcolorstop () Adds a solid color to the gradient gradient line, returning void.
Example
1 var ctx = document.queryselector (' canvas '). GetContext (' 2d '); 2 3 var grad = ctx.?? Createlineargradient (0,0,500,500); 4 5 grad.addcolorstop (0, ' green '); 6 7 grad.addcolorstop (0.5, ' yellow '); 8 9 grad.addcolorstop (1, ' Blue ');
Notice that a rectangular gradient range has been created on the canvas at this point, with coordinates of 0, 0,500,500;
But it doesn't show up, so we need to draw another shape--with the rectangle as an example.
To select the range of gradients we want to display, this redrawn rectangle needs to take the grad style.
1 ctx.fillstyle =2 ctx.fillrect (x,y,w,h);
At this point, we're going to draw the next rectangle, using the gradient that we just created.
It is not difficult to imagine that our pre-configured gradient range is actually a 500 width of the rectangle, gradient direction
is from the upper-left corner to the lower-right corner.
But where do we put this new drawing rectangle?
We can put our configured 500*500 gradient range as a piece of land, which is covered by Earth, the following is a variety of fruits. If you want to see which piece of fruit, you can draw the new rectangle where.
You can also draw a 0,0,500,500 rectangle and turn the whole piece of land straight up.
You can also draw a 0,0,50,50? rectangle, you can only see the upper left corner of green greens, because he graduated to yellow, perhaps from 50 after the start.
You can also draw a 450,450,50,50 rectangle, then you will see blue in the lower right corner.
Canvas uses gradient-linear gradient detail