5

I'm trying to build a bar chart with custom caret and position on Char JS 3.3.2.

I just added beforeDraw callback in plugin but it's not called ever.

plugins: {
  beforeDraw: () => {
    console.log('before Draw!!!!');
  },
  legend: {
    display: false
  },
  tooltip: {
    intersect: false,
    position: 'myCustomPosition',
    xAlign: 'center',
    yAlign: 'bottom',
    callbacks: {
      label: function(context) {
        var label = 'value : '

        if (context.parsed.y !== null) {
          label += context.parsed.y;
        }
        return label;
      },
      title: function() {
        return null;
      }
    }
  }
}

Anyone can help me to get answer for this problem?

My Code is here -> https://codepen.io/wsjraphael/pen/NWpZOjL

Sungjoon Won
  • 51
  • 1
  • 3

1 Answers1

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>
LeeLenalee
  • 27,463
  • 6
  • 45
  • 69