Chartjs-How to give the same gradient chart js type bar to each datasets

1👍

It’s a bit tricky because, using to backgroundColor scriptable option (callback), this is invoked before the element dimension is completely calculated (as far as I have seen, maybe I’m wrong). Anyway, by a workaround, it could be something like in the snippet.

const ctx = document.getElementById("myChart");
const myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['January', 'Fabruary', 'March', 'April', 'May', 'June', 'July'],
        datasets: [{
            data: [50, 35, 45, 47, 21, 13, 27],
            borderWidth: 0,
            backgroundColor(context) {
              const {chart, datasetIndex, index} = context;
              const ds = chart.data.datasets[datasetIndex];
              const value = ds.data[index];
              const y = chart.scales.y.getPixelForValue(value);
              const meta = chart.getDatasetMeta(datasetIndex);
              const data = meta.data[index];
              const {x, width, base} = data;
              if (x) {
                const ctx = chart.ctx;
                const gradient = ctx.createLinearGradient(x, y, x + width, base);
                gradient.addColorStop(0, 'green');
                gradient.addColorStop(0.5, 'yellow');
                gradient.addColorStop(1, 'red');
                return gradient;
              }
            }
        }]
    },
    options: {
      plugins: {
        legend: false
      }
    }
});
.myChartDiv {
  max-width: 600px;
  max-height: 400px;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
<html>
  <body>
    <div class="myChartDiv">
      <canvas id="myChart" width="600" height="400"/>
    </div>
  </body>
</html>

Leave a comment