如果不存在,我想用 ChartJS 创建一个折线图。如果存在,则应更新现有的。
<canvas id="myChart" ></canvas>
无论如何都存在。
出现错误: 未捕获类型错误:my_Chart.data 未定义
如何正确更新?
编辑:找到了检查图表是否存在的解决方案[此处][1]。
let my_Chart = document.getElementById('myChart');
let ctx = my_Chart.getContext('2d');
// Check if a chart instance already exists
if (!isCanvasBlank(my_Chart) ) {
// If a chart instance exists, update its data and options
alert('chart exists');
my_Chart.data.datasets = chart_datasets;
my_Chart.update();
} else {
// If a chart instance does not exist, create a new chart
alert('chart doesn´t exists' );
my_Chart = new Chart(ctx, {
type: 'line',
data: {
datasets: chart_datasets
},
options: {
scales: {
x: {
type: 'time',
time: {
unit: 'day',
unitStepSize: 1,
displayFormats: {
'day': 'dd. MMM'
},
tooltipFormat: 'dd. MMMM',
}
},
y: {
ticks: {
beginAtZero: true
}
}
}
}
});
}
function isCanvasBlank(canvas) {
return !canvas.getContext('2d')
.getImageData(0, 0, canvas.width, canvas.height).data
.some(channel => channel !== 0);
}
[1]: https://stackoverflow.com/a/17386803/15307393
我找到了解决方案:
let my_Chart = document.getElementById('myChart');
let ctx = my_Chart.getContext('2d');
// Check if a chart instance already exists
if (my_Chart.chart_instance) {
// If a chart instance exists, update its data and options
if (!isCanvasBlank(my_Chart)) {
// If the canvas is not blank, update the existing chart with new data
my_Chart.chart_instance.data.datasets = chart_datasets;
my_Chart.chart_instance.update();
}
} else {
// If a chart instance does not exist, create a new chart
my_Chart.chart_instance = new Chart(ctx, {
// chart definition here
});
}
}
// Function to check if the canvas element is blank
function isCanvasBlank(canvas) {
return !canvas.getContext('2d')
.getImageData(0, 0, canvas.width, canvas.height).data
.some(channel => channel !== 0);
}
any suggestions for improvement?