I am using the Chart.js library to draw a bar graph, it is working fine, but now I want to destroy the bar graph and make
I'm using Chart.js 2.7.2 as of right now. In my app, I'm creating multiple charts and needed a way to access them to properly "replace" their data and fix the "old chart" showing on hover. None of the answers I've tried worked right.
Here's a way to manage this with one or multiple charts:
Store charts in global
var charts=[]; // global
Function to create charts
function createChart(id, type, labels, data)
{
// for multiple datasets
var datasets=[];
data.forEach(function(set) {
datasets.push({
label: set.label,
data: set.data
});
});
var config = {
type: type,
data: {
labels: labels,
datasets: datasets
}
};
if(typeof charts[id] == "undefined") // see if passed id exists
{
// doesn't, so create it
charts[id]= new (function(){
this.ctx=$(id); // canvas el
this.chart=new Chart(this.ctx, config);
})();
console.log('created chart '+charts[id].chart.canvas.id);
}
else
{
charts[id].chart.destroy(); // "destroy" the "old chart"
charts[id].chart=new Chart(charts[id].ctx, config); // create the chart with same id and el
console.log('replaced chart '+charts[id].chart.canvas.id);
}
// just to see all instances
Chart.helpers.each(Chart.instances, function(instance){
console.log('found instance '+instance.chart.canvas.id)
})
}
For each of your canvas elements like:
Use the function to create/replace the chart
createChart('#thiscanvasid', 'bar', json.labels, json.datasets);