[英]Change point color on click using ChartJS
目前,當您單擊它時,我可以更改單個點(在折線圖上)的顏色,但它會立即變回以前的顏色,我該如何防止這種情況發生?
這是我的 function:
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'類型,則會調用該函數。“ 它是“在圖表的上下文中調用並傳遞事件和一系列活動元素。” 更多文檔 。
長話代碼:
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>
更新 V3 接受的答案,也通過不使用硬編碼數據集索引使其更加靈活。
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"] }, { label: '# of Points', data: [62, 59, 33, 39, 25, 62], pointBackgroundColor: ["red", "blue", "yellow", "green", "purple", "orange"] } ] }, options: { onClick: (evt, activeElements) => { if (activeElements.length === 0) { return; } const chart = evt.chart; const elementIndex = activeElements[0].index; const datasetIndex = activeElements[0].datasetIndex; chart.data.datasets[datasetIndex].pointBackgroundColor[elementIndex] = 'white'; chart.update(); } } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js"></script> <canvas id="myChart" width="400" height="400"></canvas>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.