ChartJs graph redraws crash on crash

I have the following code using the ChartJS library.

/*assume the tags in the right place */ <canvas id="graph1" width="300" height="300"></canvas> var ctx = $("#graph1").get(0).getContext("2d"); var myChart = new Chart(ctx).Line(graph1Generator("day")); 

... everything works fine, but after adding the next event handler to clear and redraw the same graph with different data, it crashes.

 weekButton.addEventListener("click", function(){ ctx.clearRect (0, 0, 300, 300); ctx.canvas.width = 300; ctx.canvas.height = 300; myChart = new Chart(ctx).Line(graph1Generator("week")); 

This code successfully redraws the chart with the new data, but when I hover over it, it makes some very strange β€œmemories” on the old chart that it was supposed to clear. It makes me believe that he did not clean the old one.

+7
javascript jquery charts
source share
1 answer

This is an update to your scripts. The main change (other than correcting the typo of the function name) is to add

 myChart.destroy(); 

before strings like

 myChart = new Chart(ctx).Line(...); 

The .destroy() method gets rid of registrations of event handlers, etc., so you should not see these strange "ghost diagrams" when you hover over the graph.

+7
source share

All Articles