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:
var canvas = document.querySelector('#my-canvas');
var context = canvas.getContext('2d');
var gradient = context.createLinearGradient(0, 0, 200, 0); // createLinearGradient(x0, y0, x1, y1)
gradient.addColorStop (0, 'red');
gradient.addColorStop (0.25, 'yellow');
gradient.addColorStop (0.5, 'green');
gradient.addColorStop (0.75, 'blue');
gradient.addColorStop (1, 'violet');
context.fillStyle = gradient;
context.fillRect(0, 0, 200, 100); // fillRect(x, y, width, height)
Practical example
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.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<canvas id="my-canvas" width="200" height="100"></canvas>
<script>
var canvas = document.querySelector('#my-canvas');
var context = canvas.getContext('2d');
// create the linear gradient
var gradient = context.createLinearGradient(0, 0, 200, 0); // createLinearGradient(x0, y0, x1, y1)
// add colors
gradient.addColorStop (0, 'red');
gradient.addColorStop (0.25, 'yellow');
gradient.addColorStop (0.5, 'green');
gradient.addColorStop (0.75, 'blue');
gradient.addColorStop (1, 'purple');
// set the fillStyle to the gradient
context.fillStyle = gradient;
// draw filled rectangle
context.fillRect(0, 0, 200, 100); // fillRect(x, y, width, height)
</script>
</body>
</html>