EN
JavaScript - fill canvas with linear gradient
0 points
In this article, we would like to show you how to fill a canvas with a linear gradient using JavaScript.
Quick solution:
xxxxxxxxxx
1
var canvas = document.querySelector('#my-canvas');
2
var context = canvas.getContext('2d');
3
4
var gradient = context.createLinearGradient(0, 0, 200, 0); // createLinearGradient(x0, y0, x1, y1)
5
6
gradient.addColorStop (0, 'red');
7
gradient.addColorStop (0.25, 'yellow');
8
gradient.addColorStop (0.5, 'green');
9
gradient.addColorStop (0.75, 'blue');
10
gradient.addColorStop (1, 'violet');
11
12
context.fillStyle = gradient;
13
14
context.fillRect(0, 0, 200, 100); // fillRect(x, y, width, height)
In this section, we present a practical example of how to fill the HTML canvas element with a rainbow gradient.
In this solution we use:
createLinearGradient()
method to create a linear gradient. The method takes four arguments:x0
- the starting point on the x-axis,y0
- the starting point on the y-axis,x1
- the ending point on the x-axis,y1
- the ending point on the y-axis.
addColorStop()
method that takes two arguments:- offset - a number between
0
and1
(inclusive), representing the position of the color stop (0
is start,1
is the end of the gradient), - color - CSS color value.
- offset - a number between
fillStyle()
method to specify the color to use inside shapes,fillRect()
to draw a rectangle that is filled with thefillStyle
color.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<canvas id="my-canvas" width="200" height="100"></canvas>
5
<script>
6
7
var canvas = document.querySelector('#my-canvas');
8
var context = canvas.getContext('2d');
9
10
// create the linear gradient
11
var gradient = context.createLinearGradient(0, 0, 200, 0); // createLinearGradient(x0, y0, x1, y1)
12
13
// add colors
14
gradient.addColorStop (0, 'red');
15
gradient.addColorStop (0.25, 'yellow');
16
gradient.addColorStop (0.5, 'green');
17
gradient.addColorStop (0.75, 'blue');
18
gradient.addColorStop (1, 'purple');
19
20
// set the fillStyle to the gradient
21
context.fillStyle = gradient;
22
23
// draw filled rectangle
24
context.fillRect(0, 0, 200, 100); // fillRect(x, y, width, height)
25
26
</script>
27
</body>
28
</html>