How to highlight single bar in bar chart using Chartjs

非 Y 不嫁゛ 提交于 2021-02-11 07:08:26

问题


In one html page, I have a select menu (a,b,c,d) and a bar chart (bar a,b,c,d). What I want to do is to highlight the corresponding bar in the bar chart that is selected in the select menu.


回答1:


You can attach the logic to your onchange handler

document.getElementById("mySelect").onchange = highlightBar.bind(document.getElementById("mySelect"));

and if you want to call it programmatically (say, if you have an initial value set)

document.getElementById("mySelect").onchange();

Here's the logic for highlighting the bars. Note that you need to consider the fact that the tooltip functionality also manipulates fill colors and stroke colors.

function highlightBar(s) {
    // this clears off any tooltip highlights
    myBarChart.update();
    myBarChart.activeElements = [];

    // reset any coloring because of selection
    myBarChart.datasets.forEach(function(dataset) {
        dataset.bars.forEach(function (bar) {
            if (bar.selected) {
                bar.fillColor = bar.selected.fillColor;
                bar.strokeColor = bar.selected.strokeColor;
                delete bar.selected;
            }
        })
    });

    var index = myBarChart.scale.xLabels.indexOf(this.value);
    myBarChart.datasets.forEach(function (dataset) {
        var selectedBar = dataset.bars[index];

        // store the current values
        selectedBar.selected = {
            fillColor: selectedBar.fillColor,
            strokeColor: selectedBar.strokeColor
        }

        // now set the color
        selectedBar.fillColor = "red";
        selectedBar.strokeColor = "red";
    });

    myBarChart.update();
}

If however, you don't have tooltips enabled, it becomes a whole lot simpler and you don't need some of the above logic.


Working Fiddle - http://jsfiddle.net/39owabm0/198/



来源:https://stackoverflow.com/questions/32154202/how-to-highlight-single-bar-in-bar-chart-using-chartjs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!