Click events on Pie Charts in Chart.js

后端 未结 10 2111
失恋的感觉
失恋的感觉 2020-11-28 03:29

I\'ve got a question regard Chart.js.

I\'ve drawn multiple piecharts using the documentation provided. I was wondering if on click of a certain slice of one of the

10条回答
  •  半阙折子戏
    2020-11-28 03:43

    Using Chart.JS version 2.1.3, answers older than this one aren't valid anymore. Using getSegmentsAtEvent(event) method will output on console this message:

    getSegmentsAtEvent is not a function

    So i think it must be removed. I didn't read any changelog to be honest. To resolve that, just use getElementsAtEvent(event) method, as it can be found on the Docs.

    Below it can be found the script to obtain effectively clicked slice label and value. Note that also retrieving label and value is slightly different.

    var ctx = document.getElementById("chart-area").getContext("2d");
    var chart = new Chart(ctx, config);
    
    document.getElementById("chart-area").onclick = function(evt)
    {   
        var activePoints = chart.getElementsAtEvent(evt);
    
        if(activePoints.length > 0)
        {
          //get the internal index of slice in pie chart
          var clickedElementindex = activePoints[0]["_index"];
    
          //get specific label by index 
          var label = chart.data.labels[clickedElementindex];
    
          //get value by index      
          var value = chart.data.datasets[0].data[clickedElementindex];
    
          /* other stuff that requires slice's label and value */
       }
    }
    

    Hope it helps.

提交回复
热议问题