Gradients

Course- HTML5 >

Gradients enable us to change from one color to another in a particular manner where the colors juxtapose with each other. We will discuss the concept of linear gradients in this chapter.

To start with, we have createLinearGradient(x1, y1, x2, y2). The gradient starts from the point (x1, y1) and extends to (x2, y2). We can create a horizontal or vertical gradient by changing the x axis and y axis parameters.

Now, we will add colors to the gradients. We will declare a linGrad variable and assign it a gradient property in the following way:

 

var linGrad = context.createLinearGradient(20, 20, 50, 70);

 

In order to deine a color to the gradient, we will use the addColorStop attribute in the following way:

 

linGrad.addColorStop(0, navy);

 

We can see that there are two parameters in the addColorStop property. The irst parameter is to be deined from 0 to 1 to indicate the extent to which the gradient color has to be applied. The second parameter is the color which is to be used. We can add innumerable colorStops as per the requirement. While we add these various colorStops, we need to change the irst parameter accordingly between the range

of 0 and 1.

Let's look at the following code to understand the gradient concept better:

<html>
<head>
<script type = "application/javascript">
function drawGrad () {
var canvas = document.getElementById("fstrd"); var context = canvas.getContext("2d");
var linGrad = context.createLinearGradient(0, 0, 100, 0); linGrad.addColorStop(0, "lime"); linGrad.addColorStop(0.5, "navy"); linGrad.addColorStop(1, "pink");
context.fillStyle = linGrad; context.fillRect(10, 10, 160, 200);
}
</script>
</head>
<body onload = "drawGrad();">
<canvas id = "fstrd" width = "200" height = "200"></canvas>
</body>
</html>

 

The output of the code would be as shown in the following screenshot:

gradiant color

We can see how the color varies and fades as well as the effect of the parameters on the canvas element. We have deined a fillStyle property and assigned it to the linGrad variable in the code. The fillStyle property fills up the rectangle according to the colors mentioned in the addColorStop attribute. We can also use strokeStyle property instead of the fillStyle property, in case we want to add colors to a rectangular outline.