[英]Update Chart.js plugin
是否可以使用chart.update()
更新chart.js插件?
我嘗試了以下方法,但似乎插件沒有更新。
let myChart;
function drawChart(chart) {
const ctx = document.getElementById("my-chart");
if (!myChart) {
myChart = new Chart(ctx, {
type: 'scatter',
data: chart.data,
options: chart.option,
plugins: chart.plugin
});
} else {
myChart.data = chart.data;
myChart.options = chart.option;
myChart.plugins = chart.plugin;
myChart.update();
}
}
任何想法將不勝感激,謝謝。
我還嘗試在圖表更新之前重新提供插件,但沒有被調用。 因此,我修改了我的插件以獲取調用更改圖表更新的@Input()
組件變量。
請看我的例子——我必須在圓環圖的中間顯示總百分比。 為此,我需要在afterDraw
事件中調用一個插件。 我做了2個改變:
我用箭頭 function 替換了插件中的 function 關鍵字,這樣我就可以使用this
關鍵字來使用 class 變量。
然后我在我的插件中使用this.total
來獲得我想要顯示的總百分比。 所以在圖表更新期間——我的新總數(總數是@Input()
變量)將自動更新。
if (!this.doughnutChart && this.doughnut) {
let ctx = this.doughnut.nativeElement.getContext("2d");
if (ctx) {
this.doughnutChart = new Chart(ctx, {
// The type of chart we want to create
type: 'doughnut',
// The data for our dataset
data: {
labels: this.labels,
datasets: [{
data: this.dataArray,
backgroundColor: this.colorsArray
}]
},
// Configuration options go here
options: this.chartOptions,
// Plugin property will help to place total count
// at the center of the doughnut after chart is rendered
plugins: [{
id: this.canvasId + '_plugin',
afterDraw: (chart) => { // Using arrow function here
chart.ctx.fillStyle = 'black'
chart.ctx.textBaseline = 'middle'
chart.ctx.textAlign = 'center'
chart.ctx.font = '17px Verdana'
// Using this.total here
chart.ctx.fillText(this.total + '%',
chart.canvas.clientWidth / 2,
(chart.canvas.clientHeight / 2) + (titlePadding * 7 + 2 - bottomPadding))
}
}]
});
}
}
else if (this.doughnutChart) {
// Update the chart
this.doughnutChart.data.datasets[0].backgroundColor = this.colorsArray;
this.doughnutChart.update();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.