最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ChartJS click on bar and change it's background color - Stack Overflow

programmeradmin3浏览0评论

I'm using chartjs to paint a simple bar chart. The bar chart is clickable and I notice if the user clicks on a bar. Now I'd like to change the background of the bar that has been clicked to indicate that this bar is actively selected.

Is this possible?

Thx

Edit: I've added a small example. / The clicked element will be collected using: this.getElementAtEvent(e)

I'm using chartjs to paint a simple bar chart. The bar chart is clickable and I notice if the user clicks on a bar. Now I'd like to change the background of the bar that has been clicked to indicate that this bar is actively selected.

Is this possible?

Thx

Edit: I've added a small example. https://jsfiddle/10n39cLz/1/ The clicked element will be collected using: this.getElementAtEvent(e)

Share Improve this question edited Jul 11, 2016 at 13:00 Christian asked Jul 11, 2016 at 12:54 ChristianChristian 7,42912 gold badges57 silver badges90 bronze badges 3
  • 1 You can change the background color of an element via element[0]._chart.config.data.datasets[0].backgroundColor = "rgb(255,255,255)";. Note that this works only till you select the second one but you should be able to find out how to reset the color to the original one. I don't know if it's the intended way to do it like this but thats what I got to work through your fiddle. – KRONWALLED Commented Jul 11, 2016 at 13:22
  • Thanks, but unfortunately this also colors the rest of the bars on refresh as it is only one series of data.. :-/ – Christian Commented Jul 11, 2016 at 13:29
  • 1 Yep saw it right now too. I will check if I'm able to get it to work and edit this post. – KRONWALLED Commented Jul 11, 2016 at 13:32
Add a ment  | 

3 Answers 3

Reset to default 7

I found a pretty elegant solution By just modifying the backgroundColor saved within an array. Sadly a render() wasn't enough, therefor I need to do an update()..

Wish I could use ES6 by the way :-)

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
    }
  }
})

If you spend some time playing 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).

This object has itself several children, such as _index (what you used in your fiddle).
This is where you should start editing your element background.

If you go very deep inside the _chart child, you can finally edit the bar you want.

I updated your fiddle to see the result : here it is.


Note that the effect will disappear if you mouseleave out of the element.

A little modification of the active property should give you the desired result.

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
    }
  }
});
发布评论

评论列表(0)

  1. 暂无评论