rbasniak
rbasniak

Reputation: 4964

Chart.Js pie chart click

In Chart.Js v3.3.2 docs, there is this sample to get information from the item you clicked in the chart.

const chart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: {
        onClick: (e) => {
            const canvasPosition = Chart.helpers.getRelativePosition(e, chart);

            // Substitute the appropriate scale IDs
            const dataX = chart.scales.x.getValueForPixel(canvasPosition.x);
            const dataY = chart.scales.y.getValueForPixel(canvasPosition.y);
        }
    }
});

This works for charts that have axis, like bar and line charts. But Pie charts don't have axis, so this code does not work.

How can I get the index of the slice I clicked in pie charts?

Upvotes: 0

Views: 1514

Answers (2)

Salahuddin Ahmed
Salahuddin Ahmed

Reputation: 5650

May be you could try the following approach:

 options:{
    ...
    onClick: pieChartClickEvent,
    ...
}

function pieChartClickEvent(event, array){
    if(array[0]){
        //do something 
    }
    ...
}

Upvotes: 2

uminder
uminder

Reputation: 26150

Presuming you're using Chart.js version 2, this can be done as follows:

onClick: evt => {
  var elements = pieChart.getElementsAtEvent(evt);
  var index = elements[0]._index;
  console.log(index)
}

Please consult section .getElementsAtEvent(e) from Chart.js v2 documentation.

Please take a look at below runnable code and see how it works:

const pieChart = new Chart("myChart", {
  type: 'pie',
  data: {
    labels: ["Red", "Blue", "Yellow"],
    datasets: [{      
      data: [8, 5, 6],
      backgroundColor: ["#FF6384", "#36A2EB", "#FFCE56"],
    }]
  },
  options: {
    events: ['click', 'mousemove', 'touchstart', 'touchmove'],
    onClick: evt => {
      var elements = pieChart.getElementsAtEvent(evt);
      var index = elements[0]._index;
      console.log(index);
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="myChart"></canvas>

Upvotes: 2

Related Questions