I'm using Chartjs to display a Line Chart and this works fine:
// get line chart canvas
var targetCanvas = document.getElementById('chartCanvas').getContext('2d');
// draw line chart
var chart = new Chart(targetCanvas).Line(chartData);
But the problem occurs when I try to change the data for the Chart. I update the graph by creating a new instance of a Chart with the new data points, and thus reinitializing the canvas.
This works fine. However, when I hover over the new chart, if I happen to go over specific locations corresponding to points displayed on the old chart, the hover/label is still triggered and suddenly the old chart is visible. It remains visible while my mouse is at this location and disappears when move off that point. I don't want the old chart to display. I want to remove it completely.
I've tried to clear both the canvas and the existing chart before loading the new one. Like:
targetCanvas.clearRect(0,0, targetCanvas.canvas.width, targetCanvas.canvas.height);
and
chart.clear();
But none of these have worked so far. Any ideas about how I can stop this from happening?
I had huge problems with this
First I tried
.clear()
then I tried.destroy()
and I tried setting my chart reference to nullWhat finally fixed the issue for me: deleting the
<canvas>
element and then reappending a new<canvas>
to the parent containerMy specific code (obviously there's a million ways to do this):
Complementing Adam's Answer
With Vanilla JS:
I had the same problem here... I tried to use destroy() and clear() method, but without success.
I resolved it the next way:
HTML:
Javascript:
It works perfect to me... I hope that It helps.
Using CanvasJS, this works for me clearing chart and everything else, might work for you as well, granting you set your canvas/chart up fully before each processing elsewhere:
This worked very well for me
Use .destroy this to destroy any chart instances that are created. This will clean up any references stored to the chart object within Chart.js, along with any associated event listeners attached by Chart.js. This must be called before the canvas is reused for a new chart.
This worked for me. Add a call to clearChart, at the top oF your updateChart()