gpt4 book ai didi

javascript - Chartjs : How do you toggle the visibility of charts in Ionic 4

转载 作者:行者123 更新时间:2023-12-02 22:12:38 27 4
gpt4 key购买 nike

我目前有 2 个图表 - 1 个饼图和 1 个条形图,都是使用 ChartJS 和 Ionic 4/Angular 完成的。我想要做到这一点,以便当我单击按钮时,它会在两个图表之间切换。最初,当我单击要更改的按钮时,图表会切换。但是,当我将鼠标悬停在图表上时,图表继续同时显示(就好像它们在同一 Canvas 上相互重叠一样)。

这是我的代码:

.html

<ion-content>
<ion-list-header color="light">Vertical Bar Chart</ion-list-header>
<ion-card class="welcome-card">
<ion-card-header>
<ion-card-subtitle>Number of Viewers per season for</ion-card-subtitle>
<ion-card-title>Game of Thrones</ion-card-title>
</ion-card-header>
<ion-card-content>
<canvas #barChart></canvas>
</ion-card-content>
</ion-card>

<ion-grid>
<ion-row>
<ion-col style="text-align:center;">
<ion-button (click)="viewBarChart()">Bar Chart</ion-button>
</ion-col>
<ion-col style="text-align:center;">
<ion-button (click)="viewPieChart()">Pie Chart</ion-button>
</ion-col>
</ion-row>
</ion-grid>
</ion-content>

.ts 文件

createBarChart() {
this.bars = new Chart(this.barChart.nativeElement, {
type: 'bar',
data: {
labels: ['S1', 'S2', 'S3', 'S4', 'S5', 'S6', 'S7', 'S8'],
datasets: [{
label: 'Finished Tasks',
data: [2.5, 3.8, 5, 6.9, 6.9, 7.5, 10, 17],
backgroundColor: 'rgb(38, 194, 129)', // array should have same number of elements as number of dataset
borderColor: 'rgb(38, 194, 129)',// array should have same number of elements as number of dataset
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}


viewPieChart(){
this.bars = new Chart(this.barChart.nativeElement, {
type: 'pie',
data: {
labels: ['Incomplete', 'In Progress', 'Finish', 'Overdue'],
datasets: [{
label: 'Number of Tasks',
data: this.pieChartData,
}]
}
});

this.bars.update();
}

viewBarChart(){
this.bars = new Chart(this.barChart.nativeElement, {
type: 'pie',
data: {
labels: ['Incomplete', 'In Progress', 'Finish', 'Overdue'],
datasets: [{
label: 'Number of Tasks',
data: [14, 1, 9, 2],
backgroundColor: 'rgb(38, 194, 129)',
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});

this.bars.update();
}

ionViewDidEnter(){
this.createBarChart();
}

最佳答案

添加一个函数以从 Canvas 中删除任何现有图表:

destroyChart() {
if(this.bars) {
this.bars.destroy()
}
}

在调用new Chart之前调用此函数

此外,也许可以将 this.bars 重命名为 this.currentChart

参见https://www.chartjs.org/docs/latest/developers/api.html#destroy

关于javascript - Chartjs : How do you toggle the visibility of charts in Ionic 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59511875/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com