[英]How to destroy a canvas using Id and add new canvas to the same id
我正在使用 Chart.js 使用折線圖和條形圖。 我有兩個選項來顯示他們的數據:按鈕點擊前和按鈕點擊后。 這兩種情況都運行良好。 但問題是,無論何時單擊按鈕並將鼠標光標懸停在上圖上,它都會顯示舊數據(所有時間)。
預期結果:圖表不應再包含以前的數據,而是顯示新數據,用戶可以毫無問題地與其進行交互。
實際結果:圖表顯示新數據,但如果用戶將鼠標懸停在圖表上,它會在原始數據和新數據之間來回閃爍
這是代碼
顯示圖表
<div ngDraggable class="col-lg-4 my-2 drag-block" *ngFor="let selectedItem of selectedKpi" (edge)="checkEdge($event)"
[bounds]="myBounds" [inBounds]="inBounds">
<mat-card>
<mat-card-header>
<mat-card-title>
<h5>{{selectedItem}}</h5>
</mat-card-title>
</mat-card-header>
<mat-card-content>
<canvas id="{{selectedItem}}">{{chart}}</canvas>
</mat-card-content>
</mat-card>
</div>
打字稿代碼:
this.selectedKpi = ["Clicks", "Orders", "Revenue", "Impressions"];
drawChart(kpi, divId, chartType, isFilled, data, labels, backgroundColor, borderColor) {
setTimeout(function () {
const canvas = <HTMLCanvasElement>document.getElementById(divId);
const ctx = canvas.getContext('2d');
this.element = document.getElementById(divId) as HTMLElement;
this.element.style.destroy;
this.chart = new Chart(ctx, {
type: chartType,
data: {
labels: labels,
datasets: [{
tension: 0,
label: kpi,
data: data,
fill: isFilled,
backgroundColor: backgroundColor,
borderWidth: 2,
pointBorderColor: borderColor,
pointRadius: 4,
borderJoinStyle: 'miter',
}]
},
options: {
responsive: true,
maintainAspectRatio: true,
scales: {
xAxes: [{
gridLines: {
display: true,
lineWidth: 1
}
}],
yAxes: [{
gridLines: {
display: true,
lineWidth: 1
}
}]
},
tooltips: {
mode: 'x',
callbacks: {
labelColor: function (tooltipItem, charts) {
return {
borderColor: borderColor,
backgroundColor: borderColor
};
},
labelTextColor: function (tooltipItem, charts) {
return '#3e95cd';
}
}
}, legend: {
display: false
}, emptyOverlay: {
fillStyle: 'rgba(74, 100, 100, 0.04)',
fontColor: 'rgba(0, 0, 0, 1)',
fontStrokeWidth: 0
}
}
});
}, 100);
}
請指導我如何銷毀畫布並使用其 ID 重新繪制它。
我也創建了一個 stackblitz 演示。 以下是網址。
在更新圖表時,這是一個非常常見的問題。 請在updateCharts(buttonClick: string)
方法的開頭添加以下代碼。
Chart.helpers.each(Chart.instances, function (instance) {
instance.destroy();
});
它將在更新之前銷毀所有先前的圖表實例。 我希望這是你所期待的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.