[Chartjs]-ChartJS remove previous chart when making new one

1👍

You indeed need to use .destroy() method to remove any previous instance of chart before making a new one.

Perhaps, you were using the .destroy() method in an inappropriate manner, which made it non-effective.

Here­‘s how you could properly remove / destroy any previous instance of chart, before creating a new one …

var meta = barGraph && barGraph.data && barGraph.data.datasets[0]._meta;
for (let i in meta) {
   if (meta[i].controller) meta[i].controller.chart.destroy();
}

affix the above code before initiating your chart

note: barGraph must be a global variable.

ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩

var barGraph;

function init(str) {
   $.ajax({
      url: "https://istack.000webhostapp.com/json/" + str + ".json",
      method: "GET",
      success: function(data) {
         console.log(data);
         var label = ['aanwezig', 'afwezig'];
         var aanwezigheid = [];
         for (var i in data) {
            aanwezigheid.push(data[i].aanwezig, data[i].afwezig);
         }
         var chartdata = {
            labels: label,
            datasets: [{
               backgroundColor: ['rgba(0, 65, 140, 0.8)', 'rgba(215, 165, 0, 0.8)'],
               borderColor: 'rgba(0, 0, 0, 0)',
               hoverBackgroundColor: ['rgba(0, 65, 140, 1)', 'rgba(215, 165, 0, 1)'],
               hoverBorderColor: 'rgba(200, 200, 200, 0)',
               data: aanwezigheid
            }]
         };
         var option = {responsive: false};
         
         // destroy previous chart
         var meta = barGraph && barGraph.data && barGraph.data.datasets[0]._meta;
         for (let i in meta) {
            if (meta[i].controller) meta[i].controller.chart.destroy();
         }
         
         // make new chart
         var ctx = $("#mycanvas");
         barGraph = new Chart(ctx, {
            type: 'pie',
            data: chartdata,
            options: option
         });
      },
      error: function(data) {
         console.log(data);
      }
   });
}
body{overflow:hidden}button{margin-left: 45px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<button onclick="init('t1')">Dataset 1</button>
<button onclick="init('t2')">Dataset 2</button><br>
<canvas id="mycanvas" height="180"></canvas>

Leave a comment