Create a linear gradient to set the fill style

var gradient = ctx.createLinearGradient(, , , );

gradient.addColorStop(, "rgba(, , , )");

gradient.addColorStop(, "rgba(, , , )");

gradient.addColorStop(, "rgba(, , , )");

gradient.addColorStop(, "rgba(, , , )");

ctx.fillStyle = gradient;

ctx.fillRect(, , , );

Show the whole gradient

Number of color stops:

Change the gradient line and color stops of the gradient to see how it affects the fillStyle of the rectangle drawn on the <canvas>. To highlight the changes, show the whole gradient. Use the number field at the bottom to change the number of color stops.

Create a linear gradient to set the stroke style

var gradient = ctx.createLinearGradient(, , , );

gradient.addColorStop(, "rgba(, , , )");

gradient.addColorStop(, "rgba(, , , )");

gradient.addColorStop(, "rgba(, , , )");

gradient.addColorStop(, "rgba(, , , )");

ctx.lineWidth = ;

ctx.strokeStyle = gradient;

ctx.strokeRect(, , , );

Show the whole gradient

Number of color stops:

Change the gradient line and color stops of the gradient to see how it affects the strokeStyle of the rectangle drawn on the <canvas>. To highlight the changes, increase the lineWidth or show the whole gradient. Use the number field at the bottom to change the number of color stops.