Summary -
In this topic, we described about the Linear Gradient Method with detailed example.
Linear gradients are described by an imaginary line which describes the path of the gradient. createLinearGradient( ) method used to create a linear gradient in HTML5 Canvas. Once we've built gradient, we can add colors using the addColorStop() property.
The path of the linear gradient moves from the beginning point to the ending point of the imaginary line defined with createLinearGradient( ).
Color spots are placed along the imaginary line somewhere between 0 and1, where 0 is at the beginning point, and 1 is at the ending point.
Syntax -
var gradient = object.reateLinearGradient(x0, y0, x1, y1);
The following table describes the parameter values of the linear gradient method -
Parameter | Description |
---|---|
x0 | The x-coordinate of the beginning point of the gradient |
y0 | The y-coordinate of the beginning point of the gradient |
x1 | The x-coordinate of the ending point of the gradient |
y1 | The y-coordinate of the ending point of the gradient |
Example -
The below example describes about the liner gradient method.
<!DOCTYPE html>
<html
<body>
<canvas id="myCanvas" width="300" height="200"
style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
// Create gradient
var grd = ctx.createLinearGradient(0,10,200,10);
grd.addColorStop(0,"red");
grd.addColorStop(1,"white");
// Fill with gradient
ctx.fillStyle = grd;
ctx.fillRect(15,10,150,70);
</script>
</body>
</html>
Output -
Browser Support
The following browsers with versions in the table indicates the initial browser version that completely supports the createLinearGradient( ) method -
Method | Chrome | Edge | Firefox | Safari | Opera |
---|---|---|---|---|---|
createLinearGradient() | Yes | 9.0 and above | Yes | Yes | Yes |