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.
The following approach makes use of:
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.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With