本文详解如何在 chart.js 中安全、稳定地动态切换图表类型(折线图、柱状图、饼图),解决因数据结构不一致导致的 `cannot read properties of undefined` 错误及类型切换后渲染异常问题。
在使用 Chart.js 构建可交互式动态图表时,常见需求是:支持实时切换图表类型(line/bar/pie)并适配不同结构的数据源。但直接复用同一 config 对象并仅修改 type 字段,极易引发两类核心问题:
✅ 正确解法是:每次类型/数据变更时,完全销毁旧实例,并基于原始配置模板 + 当前数据 + 当前类型,从零构建全新配置对象。
// 基础配置模板(不含 data,仅定义样式/选项)
const configTemplate = {
type: 'line', // 占位符,后续覆盖
data: {
datasets: [
{ label: 'company1', borderColor: 'purple', backgroundColor: 'purple', fill: false },
{ label: 'company2', borderColor: 'green', backgroundColor: 'green', fill: false },
{ label: 'company3', borderColor: 'red', backgroundColor: 'red', fill: false }
]
},
options: {
responsive: true,
plugins: { legend: { display: true } }
}
};
let myChart = null;
let currentDataIndex = 0;
const dataArr = [data0, data1, data2, data3]; // 如题中定义的 data0~data3
let currentType = 'line';
function updateChart(type, data) {
const ctx = document.getElementById('canvas').getContext('2d');
// ? 关键:销毁旧实例
if (myChart) myChart.destroy();
// ? 深拷贝模板,避免污染
const config = JSON.parse(JSON.stringify(configTemplate));
config.type = type;
// ? 按类型构造 data
if (type === 'line' || type === 'bar') {
config.data.labels = data.axis;
config.data.datasets = config.data.datasets
.slice(0, data.values.length)
.map((ds, i) => ({
...ds,
data: data.values[i]?.values || []
}));
} else if (type === 'pie') {
config.data.labels = config.data.datasets.map(ds => ds.label);
config.data.datasets = [{
backgroundColor: config.data.datasets.map(ds => ds.backgroundColor),
data: data.values.map(v => v.values?.reduce((a, b) => a + b, 0) || 0)
}];
}
myChart = new Chart(ctx, config);
}
// 绑定按钮事件
$('#line').click(() => { currentType = 'line'; updateChart('line', dataArr[currentDataIndex]); });
$('#bar').click(() => { currentType = 'bar'; updateChart('bar', dataArr[currentDataIndex]); });
$('#pie').click(() => { cur
rentType = 'pie'; updateChart('pie', dataArr[currentDataIndex]); });
$('#switch').click(() => {
currentDataIndex = (currentDataIndex + 1) % dataArr.length;
updateChart(currentType, dataArr[currentDataIndex]);
});通过遵循上述模式,即可实现健壮、可维护的动态图表系统——无论数据维度如何变化、类型如何切换,都能精准还原每种视图应有的语义与形态。