Chart.js文本框输入数据仅加载一次,点击按钮图表不更新问题求助
问题原因
你每次触发graphGraph函数时,都会在同一个canvas元素上创建全新的Chart.js实例,旧实例没有被销毁的情况下,canvas会被多个实例占用,导致新的配置无法生效,图表就不会更新。同时原代码没有将输入的字符串转为数值,也可能存在非数字输入导致的渲染异常。
方案1:先销毁旧实例再创建新实例(改法最简单)
修改你的JS代码如下:
// 全局变量存储chart实例 let myChart = null; function graphGraph() { let R = Number(document.getElementById("RedVal").value) || 0; let B = Number(document.getElementById("BlueVal").value) || 0; let Y = Number(document.getElementById("YellowVal").value) || 0; let G = Number(document.getElementById("GreenVal").value) || 0; let P = Number(document.getElementById("PurpleVal").value) || 0; let O = Number(document.getElementById("OrangeVal").value) || 0; // 已有实例先销毁 if(myChart) { myChart.destroy(); } let ctx = document.getElementById('myChart').getContext('2d'); myChart = new Chart(ctx, { type: 'bar', data: { labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'], datasets: [{ label: '# of Votes', data: [R, B, Y, G, P, O], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { y: { beginAtZero: true } } } }); }
方案2:复用已有实例更新数据(性能更优)
如果图表类型、样式配置、标签都不需要改动,仅需要更新数据,优先用这种方案,不需要每次重建实例:
let myChart = null; function graphGraph() { let R = Number(document.getElementById("RedVal").value) || 0; let B = Number(document.getElementById("BlueVal").value) || 0; let Y = Number(document.getElementById("YellowVal").value) || 0; let G = Number(document.getElementById("GreenVal").value) || 0; let P = Number(document.getElementById("PurpleVal").value) || 0; let O = Number(document.getElementById("OrangeVal").value) || 0; const newData = [R, B, Y, G, P, O]; let ctx = document.getElementById('myChart').getContext('2d'); if(!myChart) { // 第一次调用时才创建实例 myChart = new Chart(ctx, { type: 'bar', data: { labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'], datasets: [{ label: '# of Votes', data: newData, backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { y: { beginAtZero: true } } } }); } else { // 后续调用直接更新数据再触发渲染 myChart.data.datasets[0].data = newData; myChart.update(); } }
内容的提问来源于stack exchange,提问作者w4dd325
相关产品推荐
相关产品推荐

