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

2023-09-07 11:58:57 作者:我儿子他爸很帅

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.

flex4 鼠标悬停问题,form表单中必填项中提示英文

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/