Home > other >  Error message in console from using chart.js
Error message in console from using chart.js

Time:08-07

function draw() {
    
    const labels = [
        'January',
        'February',
        'March',
        'April',
        'May',
        'June',
    ];

    const data = {
        labels: labels,
        datasets: [{
            label: 'test',
            backgroundColor: 'rgb(255, 99, 132)',
            borderColor: 'rgb(255, 99, 132)',
            data: [0, 10, 5, 2, 20, 30, 45],
        }]
    };

    const config = {
        type: 'doughnut',
        data: data,
        options: {}
    };



    const myChart = new Chart(
        document.getElementById('myChart'),
        config
    );


}

This is my code and i keep getting this error message:

"Uncaught Error: Canvas is already in use. Chart with ID '0' must be destroyed before the canvas with ID 'myChart' can be reused."

Apart from this error code, my chart is able to display perfectly with no problems.

CodePudding user response:

Call myChart.destroy() before creating the new Chart. First declare myChart it globally and then initialize it.

let myChart = null;
function draw() {
    
    const labels = [
        'January',
        'February',
        'March',
        'April',
        'May',
        'June',
    ];

    const data = {
        labels: labels,
        datasets: [{
            label: 'test',
            backgroundColor: 'rgb(255, 99, 132)',
            borderColor: 'rgb(255, 99, 132)',
            data: [0, 10, 5, 2, 20, 30, 45],
        }]
    };

    const config = {
        type: 'doughnut',
        data: data,
        options: {}
    };

    if(myChart !== null){
        myChart.destroy();
    }

    myChart = new Chart(
        document.getElementById('myChart'),
        config
    );

}
  • Related