Chart.js: Bar Chart Click Events

前端 未结 8 934
梦如初夏
梦如初夏 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:43

    You can use onClick like this.

    var worstCells3GBoxChart = new Chart(ctx, {
                    type: 'bar',
                    data: {
                        labels: lbls,
                        datasets: [{
                            label: 'Worst Cells by 3G',
                            data: datas,
                            backgroundColor: getColorsUptoArray('bg', datas.length),
                            borderColor: getColorsUptoArray('br', datas.length),
                            borderWidth: 1
                        }]
                    },
                    options: {
                        legend: {
                            display: false
                        },
                        scales: {
                            yAxes: [{
                                ticks: {
                                    beginAtZero: true
                                }
                            }]
                        },
                        onClick: function (e) {
                            debugger;
                            var activePointLabel = this.getElementsAtEvent(e)[0]._model.label;
                            alert(activePointLabel);
                        }
                    }
                });
    
    0 讨论(0)
  • 2020-12-07 19:49

    I had the same problem with multiple datasets, and used this workaround:

    var clickOnChart = function(dataIndex){
        ...
    }
    var lastHoveredIndex = null;
    var chart_options = {
        ...
        tooltips: {
            ...
            callbacks: {
                label: function(tooltipItem, chart) {
                    var index = tooltipItem.datasetIndex;
                    var value  = chart.datasets[index].data[0];
                    var label  = chart.datasets[index].label;
    
                    lastHoveredIndex = index;
    
                    return value + "€";
                }
            }
        },
        onClick:function(e, items){
            if ( items.length == 0 ) return; //Clicked outside any bar.
    
            clickOnChart(lastHoveredIndex);
        }
    }
    
    0 讨论(0)
提交回复
热议问题