我正在使用chartjs绘制一个简单的条形图。条形图是可点击的,如果用户点击了条形图,我会注意到。现在,我想要更改已单击的栏的背景,以指示此栏处于活动状态。
这个是可能的吗?
Thx
编辑:我添加了一个小示例。将使用:this.getElementAtEvent(e)收集单击的元素:https://jsfiddle.net/10n39cLz/1/
发布于 2016-07-11 21:59:14
我找到了一个非常好的解决方案,只需修改保存在数组中的backgroundColor即可。遗憾的是,一个render()还不够,因此我需要做一个update()..
顺便说一句,我希望我可以使用ES6 :-)
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
}
}
})发布于 2016-07-11 21:32:27
稍微修改一下active属性就可以得到想要的结果。
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
}
}
});https://stackoverflow.com/questions/38307501
复制相似问题