[Chartjs]-Add beforeDraw callback on chart JS v3

9👍

You have to create an inline plugin as documented here: https://www.chartjs.org/docs/master/developers/plugins.html

What you have done is add the callback in the options section for all the plugins which wont work.

Example of beforeDraw callback as a plugin:

const ctx = document.getElementById('myChart').getContext('2d');
const options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderWidth: 1
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderWidth: 1
      }
    ]
  },
  options: {
    plugins: {
      customPlugin: {
        consoleText: 'testText'
      }
    }
  },
  plugins: [{
    id: 'customPlugin',
    beforeDraw: (chart, args, options) => {
      let text = options.consoleText || 'fillerConsoleText';
      console.log(text)
    }
  }]
}

const chart = new Chart(ctx, options);
<canvas id="myChart"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.0/chart.js"></script>

Leave a comment