Linear Gradients in Canvas: HTML5

Lets see how linear gradients are drawn on canvas using HTML5.

Linear-Gradients-canvas-html5

In this tutorial, we take a rectangle and draw linear gradient color as it’s fill color(fillStyle).

HTML file
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
< !DOCTYPE HTML>
<html>
<head>
<title>Canvas: HTML5</title>
<meta charset="utf-8"/>
<link href="myStyle.css" rel="stylesheet" />
<script src="myScript.js"></script>
</head>
<body>
 <canvas id="myCanvas" width="250" height="250">
  Upgrade Browser
 </canvas>
 
</body>
</html>

In this HTML5 document, we have a canvas with an id of myCanvas, and 250px width and height.

CSS file
myStyle.css

1
2
3
canvas {
border: 2px dotted black;
}

We assign 2px black dotted border to the canvas present on our HTML page.

JavaScript file
myScript.js

1
2
3
4
5
6
7
var lnr                 = context.createLinearGradient(10, 10, 10, 190);
lnr.addColorStop(0, "red");
lnr.addColorStop(0.5, "blue");
lnr.addColorStop(1, "green");
 
context.fillStyle      = lnr;
context.fillRect(25, 25, 200, 200);

by using createLinearGradient() method, we specify the start and end points of the linear gradient.

using addColorStop() method we create a color gradient at each stop position. It takes 2 parameter, first being the position and the next being any valid css color string.

The value of position can range from 0.0 to 1.0

at point 0% we take red.
at point 50% we take blue.
at point 100% we take green.

Now assign lnr object to fillStyle of a rectangle which has 200px width and height.

Linear Gradients in Canvas: HTML5


[youtube https://www.youtube.com/watch?v=RlilYyjLF78]

YouTube Link: https://www.youtube.com/watch?v=RlilYyjLF78 [Watch the Video In Full Screen.]



Note: As the name suggests linear gradient changes its angle when we change its line alignment, by changing the start and end points of the line. By changing this value you can change the gradient.