How to solve a Chart.js 2.0 issue with mouseover a

2019-03-04 02:52发布

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?

1条回答
我想做一个坏孩纸
2楼-- · 2019-03-04 03:03

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/

查看更多
登录 后发表回答