Chart JS canvas dynamic draw chart and clear using AJAX based JSON data

Chart.js  :  How to Clear canvas after drawing a chart based on the dynamic data received from AJAX based JSON response data ?

Normally  if you try to draw a new dynamic chart after an AJAX request based on the JSON data received than the the graph starts jumping around and gets fuzzy between the grid lines. This issue happens every time when the JSON data has changing datasets based on the AJAX cal request. 

To sort out this issue , you need to destroy the chart before redrawing with new dataset. 

create a global variable and use that variable while creating chart :

myChart:

and use this variable to assign chart instance, before assigning the chart instance make sure to check if any previous chart instance is available with the global variable, if exist than clear and destroy the chart distance : 
createChart: function() {
var ctx = document.getElementById(myChart); // check if any existing chart instance data is available and destroy
if(this.myChart instanceof Chart){
this.myChart.clear();
this.myChart.destroy();
} //draw new chart
this.myChart = new Chart(ctx, {
type: this.chartData.type,
data: this.chartData.data
});
}
I have taken the vue.js implementation with chart.js as the example in above scenario. 

Leave a Reply

Your email address will not be published. Required fields are marked *

thirteen + 10 =