[Chartjs]-ChartJs canvas showing previous graph when changing Graph types

5👍

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.

Leave a comment