Change point color on click using ChartJS

Currently, I can change the color of a single point (on a line chart) when you click on it, but it immediately returns to the previous color, how can I prevent this?

Here is 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 the same problem here https://github.com/chartjs/Chart.js/issues/2989 and apparently the guy was able to manage it, but I think the code is no longer compatible.

I am using ChartJS v2.5.0.

+4
source share
1 answer

The following approach uses:

  • pointBackgroundColor dataset, , . , white, .
  • onClick, , ", " mouseup " 'click'". " ".

docs.

:

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>

.

+4

Source: https://habr.com/ru/post/1674474/


All Articles