Chart.js Error: “Canvas is already in use. Chart …must be destroyed before the canvas can be reused”

when using jQuery to call webapi to obtain bubble chart data and draw bubble chart with chart.js in the test web page, if you click the display chart button twice, an error of “uncaught error: canvas is already in use. Chart with ID ‘0’ must be destroyed before the canvas can be reused.” will be reported.


from the error prompt, it should be that the canvas used to draw the bubble chart has been occupied, and there will be a conflict when using it to draw the graph again. Find two ways to solve this problem from chart.js official website and online

Call the chart.Destroy() function

The destroy function is introduced in the API help document of chart.js official website. This function is used to destroy the chart instance, clear the saved references in the object and the associated event listener. This function must be used before re using canvas to draw new graphics.
this article adds detection code before creating a new chart instance. If the mybubblechart object is already an instance of chart type, call the destroy function to destroy the instance

					if(myBubbleChart instanceof Chart)
                    {
                        myBubbleChart.destroy();
                    }
                    
                    myBubbleChart = new Chart(bubbleCanvas, {
                    type: "bubble",
                    data: data1,
                    options: []
                });

Clear/add canvas with jquery

Another way of learning as like as two peas in 2 is to remove the canvas element from jQuery before you create the chart instance, and then add the same canvas element, which is shown below:

            $('#bubbleChart').remove();
            $('#chartDiv').append('<canvas id="bubbleChart"></canvas>');

the above two methods support repeatedly clicking the display chart button to generate a bubble chart

Read More: