繁体   English   中英

ChartJS单击栏并更改其背景色

[英]ChartJS click on bar and change it's background color

我正在使用chartjs绘制简单的条形图。 条形图是可单击的,我注意到用户是否单击条形图。 现在,我想更改单击该条的背景以指示该条已被选中。

这可能吗?

谢谢

编辑:我添加了一个小例子。 https://jsfiddle.net/10n39cLz/1/将使用以下元素收集单击的元素: this.getElementAtEvent(e)

with the console and your element, you see that if you log your element, you will have an array with only one object (the said element). 如果花一些时间在控制台和元素上 ,就会发现如果log元素,则将有一个只有一个对象(所说元素)的数组。

该对象本身有几个子代,例如_index (您在小提琴中使用的子代)。
在这里应该开始编辑元素背景。

如果您深入_chart子项,则最终可以编辑所需的栏。

我更新了您的小提琴以查看结果: 在这里


请注意,如果将mouseleave移出元素效果将消失。

只需对active属性进行一些修改,即可获得所需的结果。

new Chart(document.getElementById("trendChart"), {
  type: 'bar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: 'rgb(124, 181, 236)'
    }]      
  },
  options:{
    onClick: function(e){
    var element = this.getElementAtEvent(e);

    // changes only the color of the active object
    this.active[0]._chart.config.data.datasets[0].backgroundColor = "red";

    if(element.length > 0){
            alert("Clicked on a bar with index: "+element[0]._index+". Now this bar should be marked as active.");
      }
    },
           scales: {
        yAxes: [{
            ticks: {
            fontColor:'#fff'
           }
        }],
                    xAxes: [{
            ticks: {
            fontColor:'#fff'
          }
         }],                    
     },
   legend:{
      display:false
    }
  }
});

通过修改保存在数组中的backgroundColor,我找到了一个非常优雅的解决方案。 可悲的是,render()还不够,因此我需要做一个update()。

希望我可以使用ES6 :-)

var backgroundColor = ['rgb(124, 181, 236)',
    'rgb(124, 181, 236)',
    'rgb(124, 181, 236)',
    'rgb(124, 181, 236)',
    'rgb(124, 181, 236)',
    'rgb(124, 181, 236)'];

var a = new Chart(document.getElementById("trendChart"), {
  type: 'bar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: backgroundColor
    }]      
  },
  options:{
    onClick: function(e){
    var element = this.getElementAtEvent(e);
            for(var i=0;i<backgroundColor.length;i++){
        backgroundColor[i] = 'rgb(124, 181, 236)';
    }
         backgroundColor[element[0]._index] = 'red';
      this.update()
    },
           scales: {
        yAxes: [{
            ticks: {
            fontColor:'#fff'
           }
        }],
                    xAxes: [{
            ticks: {
            fontColor:'#fff'
          }
         }],                    
     },
   legend:{
      display:false
    }
  }
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM