如何通过鼠标悬停和多个更新解决 Chart.js 2.0 问题?

2022-01-22 00:00:00 charts jquery javascript chart.js

Very strange, I have a Chart.js chart that I need to update dinamically. The update works fine, but if you move the mouse over the chart or click several times the button Update (Add data), the bars and the lines disappear and in the console shows this error:

Uncaught TypeError: Cannot read property 'draw' of null

Please click on the button several times, you can test it slowly or quickly. Pass the mouse over chart too after click the "Add data" button.

You can test this at: https://jsfiddle.net/s9zraysh/

How can I avoid this error?

解决方案

It is because you mixed up the functions to create a chart and add more data. Fixed it by separating them as shown below.

var canvas = document.getElementById("canvasChart");
var $chart;
function createChart(ID) {
  console.log(canvas);
  console.log(chartsParams);
  $chart = new Chart(canvas, chartsParams['myChart']);
}

function addData() {
  $chart.data.datasets.push({
    label: 'Added',
    data: [12, 32, 43, 53]
  });
  $chart.update();
}

createChart();
document.getElementById("addButton").addEventListener("click", addData);

demo here : https://jsfiddle.net/es0kt36e/2/

相关文章