I came across a unique incident in which when a user chooses from a drop down and the graph changes if you scan across the canvas the previous will show up like a ghost in the background. I know you can use something like graph.destroy() but I am not sure if that is appropriate and where to put it.
code where I update graphs
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();
This fiddle demonstrates the issue, hover over the chart to see the "ghost".
Because you are not destroying the instances of Chart
that you are no longer using, chartjs is drawing multiple charts into the same canvas context.
You need to have a reference of the Chart
instances you new
up to be able to call destroy
on them before you new
up 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 a fiddle that demonstrates the fix.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With