HTML5 Canvas - Linear Gradient


A shape can be filled with a gradient. Before we go into the details of the code take a look at the following HTML5 and try it.

<!DOCTYPE html5>
<html>
<body>

<canvas id ="canvas1" width="300" height="200" style="border:2px solid #FF0000;">
</canvas>

<script>
var c1=document.getElementById("canvas1");
var context1=c1.getContext("2d");

context1.beginPath();
context1.rect(50,20,180,120);
context1.lineWidth=5;
context1.strokeStyle="blue";
context1.stroke();

// add linear gradient
var grd = context1.createLinearGradient(50, 100, 180, 100);
// light blue
grd.addColorStop(0, "#8ED6FF");   
// dark blue
grd.addColorStop(1, "#004CB3");
context1.fillStyle = grd;
context1.fill();

</script>

</body>
</html>



Try this example Online


Try this example online here. [ It opens in a new tab / windows, so you can come back ] and try to make some changes in start and end colors, to see how it looks like.

Congratulations !!! You have been able to draw a Linear Gradient in HTML5.

Some Explanation



Take a look at how the gradient looks like. We have added some coordinates for explanation.



We have drawn a rectangle with upper left corner at (50,20) and the lower right corner at (180,120). The steps required to produce a gradient inside this rectangle are

1. Use createLinearGradient(x,y,x1,y1) - to create a gradient along a line in shape you chose. The (x1,y1) is the coordinate of the begining of the line and (x2,y2) is the coordinate of the end of the line. In the he above example we have used the following statement

var grd = context1.createLinearGradient(50, 100, 180, 100); 


2. We need to specify the color stops along the imaginary gradient line. We generally specify 2 colors, but we can specify more than one color. We do it with the following statements.
grd.addColorStop(0, "#8ED6FF");   
grd.addColorStop(1, "#004CB3");


Color stops are placed along the imaginary line between 0 and 1, where 0 is at the starting point, and 1 is at the ending point. You could, for example place another color at the center of the gradient with something like

grd.addColorStop(1, "somecolor"); 


Finally, the following statments define and fill a linear gradient.

context1.fillStyle = grd;
context1.fill();


There are few things that you may like to note

1. Rectangle is not the only shape in which you can apply gradient. You can use it for circle, lines and even text. We encourage you to try it on a circle as an exercise.

2. The imaginary line does not need to be horizontal or vertical. It can be a slant line and the gradient will be applied along the length of the line.

3. If the coordinates of the end points of the imaginary line are outside the area of the shape gradient will be applied only for the portion inside the shape.