Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change point color on click using ChartJS

Currently I'm able to change the color of an individual point (on a line chart) when you click on it but it changes back immediately to previous color, how can I prevent this?

Here's my function:

var options = {
  onClick: function(e){
    var element = this.getElementAtEvent(e);
    if (element.length > 0) {
      element[0]._view.backgroundColor = '#FFF';
      this.update();
    }
}

I found this same issue here https://github.com/chartjs/Chart.js/issues/2989 and apparently the guy was able to manage it but I think that code is no longer compatible.

I'm using ChartJS v2.5.0.

like image 443
Ramon Avatar asked Apr 10 '17 12:04

Ramon


Video Answer


1 Answers

The following approach makes use of:

  • the pointBackgroundColor dataset property, an array which will hold the current colors of points. When a point is clicked, the associated array value will be changed to white and the chart will be updated.
  • the onClick chart option, a function that is "called if the event is of type 'mouseup' or 'click'." It is "called in the context of the chart and passed the event and an array of active elements."

More at the docs.

Long story code:

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [72, 49, 43, 49, 35, 82],
      pointBackgroundColor: ["red", "blue", "yellow", "green", "purple", "orange"]
    }]
  },
  options: {
    onClick: function(evt, activeElements) {
      var elementIndex = activeElements[0]._index;
      this.data.datasets[0].pointBackgroundColor[elementIndex] = 'white';
      this.update();
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>

And a fiddle to play with.

like image 178
xnakos Avatar answered Sep 27 '22 21:09

xnakos