[Chartjs]-Get Value for point clicked on Pie Chart in Chart.js 3

2👍

The click event does get next to the event also a list of all the active elements and the chart, so you can use the list of active elements to get your datapoint or you can use the getElementsAtEventForMode:

var options = {
  type: 'pie',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
    }]
  },
  options: {
    onClick: (evt, el, chart) => {
      console.log('Active el list: ', chart.data.datasets[el[0].datasetIndex].label, chart.data.datasets[el[0].datasetIndex].data[el[0].index])

      let point = chart.getElementsAtEventForMode(evt, 'point', {
        intersect: true
      }, true);

      console.log('Mode point list: ', chart.data.datasets[point[0].datasetIndex].label, chart.data.datasets[point[0].datasetIndex].data[point[0].index])
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.js"></script>
</body>

Leave a comment