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?
Chart.js has a bug:
Chart.controller(instance)
registers any new chart in a global propertyChart.instances[]
and deletes it from this property on.destroy()
.But at chart creation Chart.js also writes
._meta
property to dataset variable:and it doesn't delete this property on
destroy()
.If you use your old dataset object without removing
._meta property
, Chart.js will add new dataset to._meta
without deletion previous data. Thus, at each chart's re-initialization your dataset object accumulates all previous data.In order to avoid this, destroy dataset object after calling
Chart.destroy()
.I couldn't get .destroy() to work either so this is what I'm doing. The chart_parent div is where I want the canvas to show up. I need the canvas to resize each time, so this answer is an extension of the above one.
HTML:
<div class="main_section" > <div id="chart_parent"></div> <div id="legend"></div> </div>
JQuery:
What we did is, before initialization of new chart, remove/destroy the previews Chart instance, if exist already, then create a new chart, for example
Hope this helps.
This is the only thing that worked for me:
If you are using chart.js in an Angular project with Typescript, the you can try the following;