[Chartjs]-Destroy chart.js bar graph to redraw other graph in same <canvas>

190๐Ÿ‘

โœ…

The correct method to use, in order to be able to draw another chart on the same canvas, is .destroy(). You must call it on the previously created chart object. You may also use the same variable for both charts.

var grapharea = document.getElementById("barChart").getContext("2d");

var myChart = new Chart(grapharea, { type: 'bar', data: barData, options: barOptions });

myChart.destroy();

myChart = new Chart(grapharea, { type: 'radar', data: barData, options: barOptions });

Straight from the docs (under Prototype Methods):

.destroy()

Use 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.

// Example from the docs
var myLineChart = new Chart(ctx, config);
// Destroys a specific chart instance
myLineChart.destroy();

It explicitly states that this method must be called before the canvas can be reused for a new chart.

.clear() is also mentioned later in the same section as the function that โ€œwill clear the chart canvas. Used extensively internally between animation frames, but you might find it useful.โ€ The chart will be alive and well after calling this method, so this is not the method to call, if you want to reuse the canvas for a brand new chart.

To be honest, though, in cases like yours, I have often used a container div to wrap my canvas and, whenever I needed to create a new chart, I placed a new canvas element in this div. I then used this newly created canvas for the new chart. If you ever come across strange behavior, possibly related to charts occupying the canvas before the current chart, have this approach in mind too.

44๐Ÿ‘

Remove the canvas after every chart call, this worked for me

$("canvas#chartreport").remove();
$("div.chartreport").append('<canvas id="chartreport" class="animated fadeIn" height="150"></canvas>');
var ctx = document.getElementById("chartreport").getContext("2d");
chartreport= new Chart(ctx, { .... });

40๐Ÿ‘

ChartJsโ€™s getChart(key) โ€“ finds the chart instance from the given key if the chart is already created.

  • If the key is a string, it is interpreted as the ID of the Canvas element for the Chart.
  • The key can also be a CanvasRenderingContext2D or an HTMLDOMElement.

Note: This will return undefined if no Chart is found. If the instance of the chart is found, it signifies that the chart must have previously been created.

// JS - Destroy exiting Chart Instance to reuse <canvas> element
let chartStatus = Chart.getChart("myChart"); // <canvas> id
if (chartStatus != undefined) {
  chartStatus.destroy();
}
//-- End of chart destroy   

var chartCanvas = $('#myChart'); //<canvas> id
chartInstance = new Chart(chartCanvas, {
  type: 'line',
  data: data
});
<!-- HTML -Line Graph - Chart.js -->
<div class="container-fluid" id="chartContainer">
  <canvas id="myChart" width="400" height="150">   </canvas>
</div>

This approach would save you from remove โ€“ create โ€“ append a Canvas element into DIV from inside JS.

16๐Ÿ‘

Maybe there was a better way, but no answers were suited to me.

document.querySelector("#chartReport").innerHTML = '<canvas id="myChart"></canvas>';

my HTML part is

<div class="col-md-6 col-md-offset-3">
     <div id="chartReport">
         <canvas id="myChart"></canvas>
     </div>
</div>

15๐Ÿ‘

For ChartJS v2.x you can use update() to update the chart data without explicitly destroying and creating the canvas.

var chart_ctx = document.getElementById("chart").getContext("2d");

var chart = new Chart(chart_ctx, {
    type: "pie",
    data: {},
    options: {}
});

$.ajax({
    ...
}).done(function (response) {
    chart.data = response;
    chart.update();
});

11๐Ÿ‘

Simple edit for 2020:

This worked for me. Change the chart to global by making it window owned (Change the declaration from var myChart to window myChart)

Check whether the chart variable is already initialized as Chart, if so, destroy it and create a new one, even you can create another one on the same name. Below is the code:

if(window.myChart instanceof Chart)
{
    window.myChart.destroy();
}
var ctx = document.getElementById('myChart').getContext("2d");

Hope it works!

6๐Ÿ‘

you can test this

 $('#canvas').replaceWith($('<canvas id="canvas" height="320px"></canvas>'));

๐Ÿ˜‰

5๐Ÿ‘

I always use only 1 graph/page. Destroy() solved the issues.

 if (
        window.myLine !== undefined
        &&
        window.myLine !== null
    ) {
        window.myLine.destroy();
    }

    window.myLine = new Chart(graphCanvasCtx, config);

4๐Ÿ‘

Here is my strategy for destroying a ChartJS chart before creating a new one, for a given canvas ID. Itโ€™s a little brute force, but gets the job done.

I create an object, chartsByCanvasId, that keeps track of a mapping from canvas idโ€™s to the associated ChartJS objects, and Iโ€™ll just check that object for any existing ChartJS object to destroy before creating a new one.

Take a look here:


// Helper object and functions

const chartsByCanvasId = {};

const destroyChartIfNecessary = (canvasId) => {
    if (chartsByCanvasId[canvasId]) {
        chartsByCanvasId[canvasId].destroy();
    }
}

const registerNewChart = (canvasId, chart) => {
    chartsByCanvasId[canvasId] = chart;
}

Then, this is how you can destroy a Chart if it exists

destroyChartIfNecessary(canvasId);
const myChart = new Chart(ctx, config);
registerNewChart(canvasId, myChart);

Note that after creating a chart, we immediately "register" it with registerNewChart(). This registration step is important, because that is how destroyChartIfNecessary() is going to know that a ChartJS object already exists for a given canvas id.

Nice thing about this strategy, is that it works even if there are many charts on your page, because it keeps track of ChartJS objects by canvas ID.

2๐Ÿ‘

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:

<canvas id="thiscanvasid"></canvas>

Use the function to create/replace the chart

createChart('#thiscanvasid', 'bar', json.labels, json.datasets);

2๐Ÿ‘

Change new chart variable fromโ€ฆ

var yourChart= new Chart(ctx1).Line(barChartData1, {animation: false});

TO

window.yourChart= new Chart(ctx1).Line(barChartData1, {animation: false});

Then

if(window.yourChart!= null)
{
 window.yourChart.destroy();
}

var doc1 = document.getElementById("stockPrice");
var ctx1 = doc1.getContext("2d");
window.yourChart = new Chart(ctx1).Bar(barChartData1, {animation: false});

1๐Ÿ‘

Change this:

var myChart = new Chart(ctx, {...

to

if(window.myChartAnything != undefined)

window.Anything.destroy();

window.Anything = new Chart(ctx, {...

This rocks on my webpage.

0๐Ÿ‘

In order to solve this problem I have used jQueryโ€™s add() and remove() methods, to clear the canvas. I am removing the component and before drawing it again I am appending the canvas again with the same id using jQueryโ€™s append() method.

redraw(){

 $("#myChart").remove();// removing previous canvas element
 //change the data values or add new values for new graph
 $("#chart_box").after("<canvas id='myChart'></canvas>");
 // again adding a new canvas element with same id
 generateGraph();// calling the main graph generating function 

}

0๐Ÿ‘

Create a global object:

window['chart-' + chartId] = new Chart(...);

Access and destroy to procced with redraw:

if ( window['chart-' + chartId] != undefined ) {
    window['chart-' + chartId].destroy();
}

0๐Ÿ‘

This will resolve the issue where your chart becomes slower while updating it several times on multiple ajax calls:

Just add this code before initiating your chart:

    $('.chartjs-size-monitor').each(function(){
      $(this).remove();
    })
    var grapharea = document.getElementById("barChart").getContext("2d");

0๐Ÿ‘

I got the same problem, I have removed the canvas element and recreated canvas element and then again rendered with some delay.

var element = document.getElementById("canvasId");

element.parentNode.removeChild(element);

var canv =  document.createElement("canvas");

canv.setAttribute("id","canvasId");

canv.style.height = "20vw"; // give height and width as per the requirement

canv.style.width = "20vw"; 

setTimeout(()=>{
 var grapharea = document.getElementById("canvasId").getContext("2d");
},500)

0๐Ÿ‘

I managed to find a solution that it works with destroy method and allow reuse of the canvas without deleting and recreating it, and at the same time itโ€™s the less resources consumer.

First, declare var chart as global and create a boolean to check if the js is loaded

var chart;
var graphScriptLoaded = false;

Next part is nice, because it load the js just when the graph is needed, saving time loading the page, and at the same time it allows you to understand if itโ€™s first execution or not.

//load graph just when needed and destry existing istances
if (!Boolean(graphScriptLoaded)) {
  loadScript('https://cdn.jsdelivr.net/npm/chart.js@2.8.0', function(){
    graphScriptLoaded = true;
    chart=graphs_init(i_arr, spent_arr);
  });
} else {
  chart.destroy();
  chart=graphs_init(i_arr, spent_arr);
}

Then, in the function that create the graph, simply return chart var

var chart = new Chart(ctx, {
[.....]
});
return chart;

Function "loadscript" is customized and based on this answer:
How do I include a JavaScript file in another JavaScript file?

and here it is:

    function loadScript(url, callback){

    var script = document.createElement("script")
    script.type = "text/javascript";

    if (script.readyState){  //IE
        script.onreadystatechange = function(){
          if (script.readyState == "loaded" || script.readyState == "complete"){
                script.onreadystatechange = null;
                callback();
          }
        };
    } else {  //Others
        script.onload = function(){
          callback();
        };
    }

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}

It works like a charm.

0๐Ÿ‘

for me it seemed to work like below with core javascript (assuming chart min js already loaded):

const data = {
    labels : graphDataLabels,
        datasets: [{
            label: 'Sentiment Intensity Distribution',
            data: dataValues, //[300, 50, 100],
            backgroundColor: [
                "#0D5265",
                "#32DAC8",
                "#FF8300"
            ],
            hoverOffset: 4
        }]
    };
    const config = {
        type: 'pie',
        data: data
    };
    var ctx = document.getElementById('pieChart').getContext('2d');
    if(ctx.pieChart){
        pieChart = null;
    }else{
        pieChart = new Chart(ctx, config);
    }

0๐Ÿ‘

If you have many charts on one page them building a data structure to save lists of existing charts is complicated. Itโ€™s easier in chart.js 3.5.0 to test to see if the chart canvas is already used or not. No separate data structures required:

// Chart may previously have been shown or not, so the chart may need creating or updating. 
// Vue messes with the DOM, so you can't just "update" the chart as per the docs.
var canv = this.$refs['canvas'];
const oldChart = Chart.getChart(canv);
if (typeof oldChart !== 'undefined') {
    oldChart.destroy();
}
new Chart(canv.getContext('2d'), this.config);

0๐Ÿ‘

I donโ€™t know how many hours I gave to handle this problem.

Letโ€™s assume your html contains that

<div id="soner" class="card-body customerDonutChart">
<canvas id="customerDonutChart" style="min-height: 250px; height: 250px; max-height: 250px; max-width: 100%;"></canvas> 
</div>

Watch out the <div id="soner" part which is necessary to overcome the problem.

function myChartJsCaller()
{
   document.getElementById("soner").innerHTML = '<canvas id="customerDonutChart" style="min-height: 250px; height: 250px; max-height: 250px; max-width: 100%;"></canvas>';

  // here is important, your ctx = blabla must be below after changing innerHTML
  let ctx = document.getElementById(selector);
  .
  .
}

0๐Ÿ‘

I have a slightly different approach to this.
first in my js i have defined one map like below.

var chartContext = new Map();

And i insert one key value pair when i populate this chart like this value being chart object it self and key being id of that canvas.

 chartContext.set(chartid, chartObject);

after this when i need to repopulate / rerender same canvas again, I do following.

if (chartContext.has(chartid)) {
        tempchartContext = chartContext.get(chartid);
        if (tempchartContext instanceof Chart) {
            tempchartContext.destroy();
        }
    }

By this way old chart context is destroyed.

and after making new chart i call following code to update same canvas again

0๐Ÿ‘

Iโ€™m using Angular for this example and found it easy by doing the following

import Chart, { ChartConfiguration } from 'chart.js/auto';
export class ReportsComponent implements OnInit {
    chart1: Chart;

    ngOnInit(): void {
       this.initGraphs(); // logic for creating your charts
       this.drawGraphs(data) // populate the chart and update graph
    }
    
    initGraphs(){
      this.chart1= new Chart(...)
    }

    drawGraphs(data){ // just an example of how you might populate your chart
      for (const total of Object.values(data.gender)) {
        this.chart1.data.datasets[0].data.push(+total);
      }

      this.chart1.update(); // to override the default empty datasets on the chart config
    }

    onUpdate(){
       const filteredData = {...} // this would be the new data you want to show
       this.chart1.destroy();
       this.initGraphs();
       this.drawGraphs(filteredData);
    }
}

So yes you use the .destroy() to destroy any chart instances that are created. But you have to create the chart again for it to be rendered on your screen

-1๐Ÿ‘

This works for me in angular

removeHTML() {

    let chart = <HTMLCanvasElement>document.getElementById("myChart"); 
    let chart2 = <HTMLCanvasElement>document.getElementById("myChart2"); 

    if(chart){
       chart.remove()
    }

    if(chart2){
      chart2.remove()
    }


}


ngOnDestroy(): void {

    this.removeHTML();
}

Leave a comment