Chartjs-ChartJS updating values in beforeDraw

0👍

You should not hardCode the values in your plugin, instead you can use the options object of your plugin i which you can set and update the values when you update the chart data:

const data = {
  labels: ['Mon', 'Tue', 'Wed', 'Thu'],
  datasets: [{
    label: 'Old Data',
    data: [18, 12, 6, 9],
    backgroundColor: [
      'rgba(255, 26, 104, 0.2)',
      'rgba(54, 162, 235, 0.2)',
      'rgba(255, 206, 86, 0.2)'
    ],
    borderColor: [
      'rgba(255, 26, 104, 1)',
      'rgba(54, 162, 235, 1)',
      'rgba(255, 206, 86, 1)'
    ],
    borderWidth: 1
  }]
};

const canvasBackgroundColor = {
  id: 'canvasBackgroundColor',
  beforeDraw(chart, args, opts) {

    const {
      ctx,
      chartArea: {
        top,
        bottom,
        left,
        right,
        width
      },
      scales: {
        x,
        y
      }
    } = chart;

    ctx.save();

    ctx.fillStyle = 'rgba(255, 26, 104, 0.2';
    ctx.fillRect(left, y.getPixelForValue(opts.pinkMax), width, y.getPixelForValue(opts.pinkMin) - y.getPixelForValue(opts.pinkMax));

    ctx.fillStyle = 'rgba(55, 126, 104, 0.2';
    ctx.fillRect(left, y.getPixelForValue(opts.greyMax), width, y.getPixelForValue(opts.greyMin) - y.getPixelForValue(opts.greyMax));
    ctx.restore();

  }
}

const config = {
  type: 'line',
  data,
  options: {
    scales: {
      y: {
        beginAtZero: true
      }
    },
    plugins: {
      canvasBackgroundColor: {
        pinkMax: 18,
        pinkMin: 14,
        greyMax: 14,
        greyMin: 0
      }
    }
  },
  plugins: [canvasBackgroundColor]
};

const myChart = new Chart(
  document.getElementById('myChart'),
  config
);

function updateChart() {
  myChart.data.labels = ['Jan', 'March', 'April', 'May'];
  myChart.data.datasets[0].label = ['New Data'];
  myChart.data.datasets[0].data = [1, 2, 3, 4];

  myChart.options.plugins.canvasBackgroundColor.pinkMax = 4;
  myChart.options.plugins.canvasBackgroundColor.pinkMin = 2;
  myChart.options.plugins.canvasBackgroundColor.greyMax = 2;
  myChart.options.plugins.canvasBackgroundColor.greyMin = 0;

  myChart.update();
};
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="myChart"></canvas>
<button onClick="updateChart()">Update</button>

Leave a comment