ChartJs picture showing the previous graph when changing graph types

I came across a unique incident in which when the user selects from the drop-down list and the graph changes, if you view the canvas, the previous one will be displayed as a ghost in the background. I know that you can use something like graph.destroy (), but I'm not sure if this fits and where to put it.

where i update the graphics

var ctx = document.getElementById("myChart").getContext("2d"); ctx.canvas.width = 600; ctx.canvas.height = 200; function updateChart() { // ctx.canvas.destroy(); var determineChart = $("#chartType").val(); var params = dataMapMain[determineChart]; if ([params.method] == "Pie") { document.getElementById("subOption").hidden = false; document.getElementById("arrowId").hidden = false; var determineChart = $("#subOption").val(); var params = dataMapSub[determineChart]; $('#subOption').on('change', updateChart); new Chart(ctx)[params.method](params.data, options, {}); } else { document.getElementById("subOption").hidden = true; document.getElementById("arrowId").hidden = true; new Chart(ctx)[params.method](params.data, options, {}); } } $('#chartType').on('change', updateChart) updateChart(); 

enter image description here

This fiddle demonstrates the problem, hover over the chart to see the ghost.

+6
source share
1 answer

Since you are not destroying Chart instances that you no longer use, chartjs draws multiple charts in the same canvas context.

You need to have a reference to the Chart instances of new in order to be able to call destroy on them before you new another one.

Add this to your code:

 var ctx = document.getElementById("myChart").getContext("2d"); ctx.canvas.width = 600; ctx.canvas.height = 200; var chart; // assign your chart reference to this variable function updateChart() { var determineChart = $("#chartType").val(); var params = dataMapMain[determineChart]; if ([params.method] == "Pie") { document.getElementById("subOption").hidden = false; document.getElementById("arrowId").hidden = false; var determineChart = $("#subOption").val(); var params = dataMapSub[determineChart]; $('#subOption').on('change', updateChart); chart && chart.destroy(); // destroy previous chart chart = new Chart(ctx)[params.method](params.data, options, {}); } else { document.getElementById("subOption").hidden = true; document.getElementById("arrowId").hidden = true; chart && chart.destroy(); // destroy previous chart chart = new Chart(ctx)[params.method](params.data, options, {}); } } $('#chartType').on('change', updateChart) updateChart(); 

And here is the fiddle that demonstrates the fix.

+3
source

All Articles