Chart.js创建折线图遇Canvas占用错误且折线不显示
解决Chart.js折线图的两个问题:Canvas重复使用错误与折线不显示
问题1:Canvas已被使用的错误
错误提示:Uncaught Error: Canvas is already in use. Chart with ID '0' must be destroyed before the canvas with ID 'myChart' can be reused
- 原因:脚本重复执行(比如页面热重载、脚本多次加载)时,会在同一个canvas元素上创建多个Chart实例,引发资源冲突。
- 修复方式:创建新实例前,先检查是否已有实例存在,若存在则销毁:
// 销毁已有实例(如果存在) if (window.myChart) { window.myChart.destroy(); }
问题2:折线不显示
- 原因1:数据集字段名错误,你在
datasets里用了dota作为数据字段,但Chart.js要求必须用data,导致无法识别数据。 - 原因2:数据为字符串类型,Chart.js需要数值类型才能正确绘制折线。
- 修复方式:将
dota字段改为data,并把字符串数据转为数字。
修改后的完整JavaScript代码
const ctx = document.getElementById("myChart").getContext("2d"); const labels = [ "2002", "2003", "2004", ]; const dota = { labels, datasets: [ { data: [3, 1, 2], // 改为data字段,使用数字类型 label: "OK", }, ], }; const config = { type: 'line', data: dota, options: { responsive: true, }, }; // 先销毁已有实例避免冲突 if (window.myChart) { window.myChart.destroy(); } const myChart = new Chart(ctx, config); // 将实例挂载到window,方便后续销毁 window.myChart = myChart;
额外注意
你的HTML中Chart.js是通过type="module"引入的,而script.js是普通脚本,可能存在模块作用域问题。如果仍有加载异常,可以把script.js也改为模块类型:
<script type="module" src="script.js"></script>
内容的提问来源于stack exchange,提问作者TOUSHIF HOSSAIN
相关产品推荐
相关产品推荐

