Chart.js: Bar Chart Click Events

前端 未结 8 936
梦如初夏
梦如初夏 2020-12-07 18:56

I\'ve just started working with Chart.js, and I am getting very frustrated very quickly. I have my stacked bar chart working, but I can\'t get the click \"events\" to work.<

8条回答
  •  既然无缘
    2020-12-07 19:40

    I managed to find the answer to my question by looking through the Chart.js source code.

    Provided at line 3727 of Chart.js, Standard Build, is the method .getElementAtEvent. This method returns me the "chart element" that was clicked on. There is sufficent data here to determine what data to show in a drill-down view of the dataset clicked on.

    On the first index of the array returned by chart.getElementAtEvent is a value _datasetIndex. This value shows the index of the dataset that was clicked on.

    The specific bar that was clicked on, I believe, is noted by the value _index. In my example in my question, _index would point to One in chart_config.data.labels.

    My handleClick function now looks like this:

    function handleClick(evt)
    {
        var activeElement = chart.getElementAtEvent(evt);
    

    ..where chart is the reference of the chart created by chart.js when doing:

    chart = new Chart(canv, chart_config);
    

    The specific set of data that was selected by the click can therefore be found as:

    chart_config.data.datasets[activeElement[0]._datasetIndex].data[activeElement[0]._index];
    

    And there you have it. I now have a datapoint that I can build a query from to display the data of the bar that was clicked on.

提交回复
热议问题