首页 > 解决方案 > 单击echart条形图时如何突出显示条形?

问题描述

我使用 echarts 库创建了一个条形图。如何在用户单击条形图时突出显示条形图,或者在单击条形图时应用条形边框?

有没有办法在栏触发点击事件时突出显示栏?

标签: javascriptgraphecharts

解决方案


是的,有一种方法可以在单击时突出显示条。

当点击事件被触发时,您可以从参数中获取被点击的确切数据(单条),然后您只需要改变这些数据的颜色(例如,降低alpha)就可以达到'highlight'的目的。

并且不要同时忘记其他数据(未点击)的恢复颜色。

检查这个演示

let echartsObj = echarts.init(document.querySelector('#canvas'));


option = {


    grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
    },
    xAxis: [{
        type: 'category',
        data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],

    }],
    yAxis: [{
        type: 'value'
    }],
    series: [{
        name: '直接访问',
        type: 'bar',
        barWidth: '60%',
        data: [{
            value: 10,
            itemStyle: {
                color: 'hsl(200,60%,45%)'
            }
        }, {
            value: 52,
            itemStyle: {
                color: 'hsl(200,60%,45%)'
            }
        }, {
            value: 200,
            itemStyle: {
                color: 'hsl(60,60%,45%)'
            }
        }, {
            value: 334,
            itemStyle: {
                color: 'hsl(150,60%,45%)'
            }
        }, {
            value: 390,
            itemStyle: {
                color: 'hsl(220,60%,45%)'
            }
        }, {
            value: 330,
            itemStyle: {
                color: 'hsl(200,60%,45%)'
            }
        }, {
            value: 220,
            itemStyle: {
                color: 'hsl(150,60%,45%)'
            }
        }]
    }]
};

echartsObj.setOption(option)

echartsObj.on('click', function(params) {
    console.log(params)
    option.series[0].data.forEach((data, index) => {
        if (index === params.dataIndex) {
            if (!data.isChecked) {
                data.itemStyle.color = getHighLightColor(data.itemStyle.color);
                data.isChecked = true;
            }
        } else {
            if (data.isChecked) {
                data.itemStyle.color = getOrigColor(data.itemStyle.color);
                data.isChecked = false;
            }

        }
    })
    echartsObj.setOption(option)
});


function getHighLightColor(color) {
    return color.replace(/(\d+)%\)/, (...args) => {
        return 20 + Number(args[1]) + '%)'
    });
}


function getOrigColor(highlightColor) {
    return highlightColor.replace(/(\d+)%\)/, (...args) => {
        return Number(args[1]) - 20 + '%)'
    });
}
    <html>
      <header>
        <script src="https://cdn.bootcss.com/echarts/4.1.0.rc2/echarts-en.min.js"></script>
      </header>
      <body>
      <div id="canvas" style="width: 100%; height: 200px">

</div>
      </body>
    </html>


推荐阅读