Languages
[Edit]
EN

JavaScript - fill canvas with linear gradient

0 points
Created by:
Jacob
532

In this article, we would like to show you how to fill a canvas with a linear gradient using JavaScript.

Quick solution:

 

Practical example

Edit

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:

  1. 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.
  2. addColorStop() method that takes two arguments:
    • offset - a number between 0 and 1 (inclusive), representing the position of the color stop (0 is start, 1 is the end of the gradient),
    • color - CSS color value.
  3. fillStyle() method to specify the color to use inside shapes,
  4. fillRect() to draw a rectangle that is filled with the fillStyle color.

References

Edit
  1. CanvasRenderingContext2D.createLinearGradient() - Web APIs | MDN
  2. CanvasGradient.addColorStop() - Web APIs | MDN
  3. CanvasRenderingContext2D.fillStyle - Web APIs | MDN
  4. CanvasRenderingContext2D.fillRect() - Web APIs | MDN

Alternative titles

  1. JavaScript - fill HTML canvas element with gradient
  2. JavaScript - set HTML canvas element background to gradient
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - HTML5 canvas tutorial

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join