How to add gradient instead of solid color fill with JavaScript Chart.js 3?

Sometimes, we want to add gradient instead of solid color fill with JavaScript Chart.js 3.

In this article, we’ll look at how to add gradient instead of solid color fill with JavaScript Chart.js 3.

How to add gradient instead of solid color fill with JavaScript Chart.js 3?

To add gradient instead of solid color fill with JavaScript Chart.js 3, we can set the backgroundColor property of the dataset object to a canvas gradient object.

For instance, we write:

<canvas id="myChart" width="400" height="400"></canvas>

to add the canvas element.

Then we write:

const ctx = document.getElementById('myChart');

const gradient = ctx.getContext('2d').createLinearGradient(0, 0, 0, 400);
gradient.addColorStop(0, 'rgba(250,174,50,1)');
gradient.addColorStop(1, 'rgba(250,174,50,0)');

const myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      fill: true,
      backgroundColor: gradient,
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      y: {
        beginAtZero: true
      }
    },
  }
});

to add a line chart with the area between the x-axis and the line filled in.

We set fill to true to enable the fill.

Then we set backgroundColor to gradient to add the gradient fill.

We call createLinearGradient to create the gradient.

And we call addColorStop to add the gradient colors.

Conclusion

To add gradient instead of solid color fill with JavaScript Chart.js 3, we can set the backgroundColor property of the dataset object to a canvas gradient object.