By creating a gradient
object and assigning it to the context before drawing the figure, the color gradient effect can be achieved. The gradient effect can be used to fill rectangle, circle, line, text, etc.
Gradients in HTML5 canvas are divided into linear gradients and radial gradients (also known as diffusion gradients). Related methods:
//Create a linear gradient
//x0: X coordinate of the start point of the gradient
//y0: Y coordinate of the starting point of the gradient
//x1: X coordinate of gradient end point
//y1: Y coordinate of gradient end point
context.createLinearGradient(x0,y0,x1,y1);
//Create a radial gradient
//X coordinate of the starting circle of the gradient
//Y coordinate of the starting circle of the gradient
//Radius of start circle
//X coordinate of the end circle of the gradient
//Y coordinate of the end circle of the gradient
//Radius of end circle
context.createRadialGradient(x0,y0,r0,x1,y1,r1);
//Increase the color and stop position in the specified gradient object
//Stop: a value between 0.0 and 1.0, indicating the position between the beginning and end of the gradient.
//Color: CSS color value displayed at the end
gradient.addColorStop(stop, color);
The gradient
object created by createlineargradient and createradialgradient
must use the addcolorstop()
method to specify different colors and where to locate the colors in the gradient
object.
Linear gradient
var canvas=document.getElementById("myCanvas");
var ctx=canvas.getContext("2d");
var gradient=ctx.createLinearGradient(0,0,170,0);
gradient.addColorStop(0,"black");
gradient.addColorStop("0.7","yellow");
gradient.addColorStop(1,"red");
ctx.fillStyle=gradient;
ctx.fillRect(20,20,160,100);
Radial gradient
var canvas=document.getElementById("myCanvas");
var ctx=canvas.getContext("2d");
var gradient=ctx.createRadialGradient(100,100,5,100,100,100);
gradient.addColorStop(0,"black");
gradient.addColorStop("0.7","yellow");
gradient.addColorStop(1,"red");
ctx.fillStyle=gradient;
ctx.fillRect(20,20,160,160);
Text color gradient example
var canvas=document.getElementById("myCanvas");
var ctx=canvas.getContext("2d");
var gradient=ctx.createLinearGradient(0,0,170,0);
gradient.addColorStop(0,"black");
gradient.addColorStop("0.7","yellow");
gradient.addColorStop(1,"red");
ctx.font="30px Verdana";
ctx.fillStyle=gradient;
ctx.fillText("Hello World!",10,70);
ctx.font="30px Verdana";
ctx.strokeStyle=gradient;
ctx.strokeText("Hello World!",10,120);