How to stop chart.js rendering over previous chart?

by haylee.mertz , in category: Javascript , 5 months ago

How to stop chart.js rendering over previous chart?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by samara , 5 months ago

@haylee.mertz 

To stop Chart.js from rendering over the previous chart, you can destroy the existing chart before rendering a new one. Here is an example code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Get the canvas element where the chart is rendered
var canvas = document.getElementById('myChart');

// Check if there is an existing chart instance
if (window.myChart) {
  window.myChart.destroy();
}

// Render a new chart
var ctx = canvas.getContext('2d');
window.myChart = new Chart(ctx, {
  // Your chart configuration options
  type: 'bar',
  data: {
    labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: [
        'red',
        'blue',
        'yellow',
        'green',
        'purple',
        'orange'
      ]
    }]
  }
});


In this code, we first check if there is an existing chart instance by checking if window.myChart exists. If so, we call the destroy() method on the chart instance to remove it from the DOM. Then we create a new chart instance and store it in window.myChart.


By following this approach, you can prevent Chart.js from rendering over the previous chart and ensure that only one chart is displayed at a time.