[英]ChartJS click on bar and change it's background color
我正在使用chartjs繪制簡單的條形圖。 條形圖是可單擊的,我注意到用戶是否單擊條形圖。 現在,我想更改單擊該條的背景以指示該條已被選中。
這可能嗎?
謝謝
編輯:我添加了一個小例子。 https://jsfiddle.net/10n39cLz/1/將使用以下元素收集單擊的元素: this.getElementAtEvent(e)
with the console and your element, you see that if you log
your element, you will have an array with only one object (the said element). 如果花一些時間在控制台和元素上 ,就會發現如果log
元素,則將有一個只有一個對象(所說元素)的數組。
該對象本身有幾個子代,例如_index
(您在小提琴中使用的子代)。
在這里應該開始編輯元素背景。
如果您深入_chart
子項,則最終可以編輯所需的欄。
我更新了您的小提琴以查看結果: 在這里 。
mouseleave
移出元素,效果將消失。
只需對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
}
}
});
通過修改保存在數組中的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
}
}
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.