如何在我的draw函数中实现chart.js destroy

htzpubme  于 2022-11-06  发布在  Chart.js
关注(0)|答案(1)|浏览(148)

我有一个圆环图,每次我在下拉菜单中选择不同的选项时,我都想用新的数据集更新它,但由于我的代码是在draw()函数中,所以图表总是试图一遍又一遍地绘制自己,这就是为什么我一直收到错误消息的原因:Canvas is already in use. Chart with ID '0' must be destroyed before the canvas with ID 'myChart' can be reused.
我该如何解决这个问题呢?名为stats的变量是我试图用来更新图表数据的变量。

var config = {
            type: 'doughnut',
            data: {
                labels: legend,
                datasets: [{
                    backgroundColor: ['rgb(204,0,0)', 'rgb(241,194,50)', 'rgb(41,134,204)', 'rgb(106,168,79)', 'rgb(255,62,153)'],
                    data: stats,
                }]
            },
            plugins: [hoverLabel],
            options: {
                radius: this.radius,
                hoverOffset: 30,
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    title: {
                        display: true,
                        text: "Top 5 causes of death in " + country,
                        color: 'rgb(0,0,0)',
                        align: 'center',
                        padding: 15,
                        font: {
                            size: 25
                        }
                    },
                    legend: {
                        position: 'right',
                        title: {
                            display: true,
                            color: 'rgb(0,0,0)',
                            text: 'Legend',
                            font: {
                                weight: 'bold',
                                size: 20
                            },
                        },
                        labels: {
                            color: 'rgb(0,0,0)',
                            usePointStyle: true,
                            padding: 15,
                            font: {
                                size: 15,
                                weight: 'bold'
                            }
                        }
                    }
                }

            }
        };

        let mychart = new Chart('myChart', config);

Doughnut Chart

bd1hkmkf

bd1hkmkf1#

您有两个选项,一个是通过先销毁图表来完全重新创建图表:

const config = {}; // Fill with your config opbject

let chart = Chart.getChart('myChart'); // Pass the canvas ID

if (chart) {
  chart.destroy();
}

chart = new Chart('myChart', config);

或通过更新当前图表示例:

const config = {}; // Fill with your config opbject

let chart = Chart.getChart('myChart'); // Pass the canvas ID

if (chart) {
  chart.data.labels = legend;
  chart.data.datasets[0].data = stats;
  chart.update();
} else {
  new Chart('myChart', config)
}

相关问题