[Chartjs]-How can I fix the offset of the gradient to be aligned with the chart points(chart.js)?

1👍

You need the xAxis that contains the required attributes (left, right) for creating the gradient together with the method getPixelForTick to compute the offset of the color stops.

Please take a look at your amended code below and see how it works.

new Chart('myChart', {
  type: 'line',
  plugins: [{
    afterLayout: chart => {
      let ctx = chart.chart.ctx;
      ctx.save();
      let xAxis = chart.scales['x-axis-0'];
      let gradient = ctx.createLinearGradient(xAxis.left, 0, xAxis.right, 0);
      let data = chart.data.datasets[0].data;
      let color;
      data.forEach((v, i) => {
        let x = xAxis.getPixelForTick(i) - xAxis.left;
        let offset = 1 / (xAxis.right - xAxis.left) * x;
        if (color) {
          gradient.addColorStop(offset, color);
        }
        if (i < data.length) {
          color = data[i + 1] > v ? 'green' : 'red'; 
          gradient.addColorStop(offset, color);
        }
      });
      chart.data.datasets[0].backgroundColor = gradient;
      ctx.restore();
    }
  }],
  data: {
    labels: ['21/12', '22/12', '23/12', '24/12', '25/12', '26/12', '27/12'],
    datasets: [{
      data: [20.2, 31.2, 18.4, 20.1, 15.2, 23.6, 20.1],
      label: 'example',
      fill: true
    }]
  },
  options: {
    legend: {
      display: false
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="myChart" height="90"></canvas>

Leave a comment