目前,我可以在单击某个点(折线图)时更改它的颜色,但它会立即变回以前的颜色,我该如何防止这种情况发生?
这是我的功能:
var options = {
onClick: function(e){
var element = this.getElementAtEvent(e);
if (element.length > 0) {
element[0]._view.backgroundColor = '#FFF';
this.update();
}
}
我在这里发现了同样的问题 https://github.com/chartjs/Chart.js/issues/2989显然这个人能够管理它,但我认为该代码不再兼容。
我正在使用 ChartJS v2.5.0。
最佳答案
下面的方法利用了:
pointBackgroundColor
数据集属性,一个保存点当前颜色的数组。单击某个点时,关联的数组值将更改为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>
关于javascript - 使用 ChartJS 单击更改点颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43323152/