How to reset a chart of chart.js?

Member

by daisha , in category: Javascript , 8 months ago

How to reset a chart of chart.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by wilmer.lemke , 8 months ago

@daisha 

To reset a chart in Chart.js, you can use the destroy() method on the chart instance. Here's an example of how you can reset a Chart.js chart:

  1. First, store a reference to the chart instance when you create the chart:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        // chart data
    },
    options: {
        // chart options
    }
});


  1. To reset the chart, you can call the destroy() method on the chart instance:
1
myChart.destroy();


  1. After destroying the chart, you can reinitialize it with new data and options:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
var newChartData = {
    labels: ['A', 'B', 'C', 'D', 'E'],
    datasets: [{
        data: [10, 20, 30, 40, 50],
        // new datasets
    }]
};

var newChartOptions = {
    // new chart options
};

myChart = new Chart(ctx, {
    type: 'bar',
    data: newChartData,
    options: newChartOptions
});


With these steps, you can reset a Chart.js chart by destroying the existing instance and creating a new one with updated data and options.