How to apply a linear gradient to fill in chart.js?

Member

by dana , in category: Javascript , 7 months ago

How to apply a linear gradient to fill in chart.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by arnoldo.moen , 7 months ago

@dana 

To apply a linear gradient to fill in a Chart.js chart, you can use the fill option in the dataset object. Here's a step-by-step guide on how to do this:

  1. Define your gradient color(s) using the CanvasRenderingContext2D createLinearGradient() method. For example, to create a gradient that transitions from blue to purple, you can use the following code:
1
2
3
4
var ctx = document.getElementById('myChart').getContext('2d');
var gradient = ctx.createLinearGradient(0, 0, 0, 400);
gradient.addColorStop(0, 'blue');
gradient.addColorStop(1, 'purple');


  1. Add the gradient to the fill option in your dataset object. For example:
1
2
3
4
5
6
7
8
9
var chartData = {
  labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
  datasets: [{
    label: 'Data',
    data: [10, 20, 15, 25, 30, 35],
    fill: true,
    backgroundColor: gradient
  }]
};


  1. Create your Chart.js chart as usual, passing in the chartData object. The linear gradient will now be applied to fill in the chart.


By following these steps, you can apply a linear gradient to fill in a Chart.js chart.