Chartjs-Unexpected behavior with chart.js

1👍

You need to destroy the existing chart before creating the new one. So something like

var ctx = document.getElementById("canvas").getContext("2d");
if (window.myBar)
   window.myBar.destroy();
...

You could also do a similar thing by updating the points and calling update(), but destroy() is easier by far.


Fiddle – https://jsfiddle.net/jzq5umfm/


Note : while removing the existing canvas element and adding a new one would also seemingly work (as mentioned in your comment and the previous version of your question), with responsive: true, Chart.js cycles through all created instances of the graph to resize them, resulting in a console error for each responsive graph that has been created and removed but not destroyed.

For responsive: false you won’t see console errors but you’d still have references to those unused instances.

Leave a comment