如何使用Chart.js突出显示条形图中的单个条形图 [英] How to highlight single bar in bar chart using Chartjs

查看:88
本文介绍了如何使用Chart.js突出显示条形图中的单个条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个html页面中,我有一个选择菜单(a,b,c,d)和一个条形图(a,b,c,d条).我要做的是在选择菜单中选中的条形图中突出显示相应的条形.

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.

推荐答案

您可以将逻辑附加到onchange处理程序

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.

工作小提琴- http://jsfiddle.net/39owabm0/198/

这篇关于如何使用Chart.js突出显示条形图中的单个条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆