Johan
Johan

Reputation: 2972

Multiple charts in one page - Chartjs

I tried to add multiple charts in one page, but had the error Canvas is already in use. Chart with ID '0' must be destroyed before the canvas can be reused.

After research, I read that I had to set my canvas in div because :

Detecting when the canvas size changes can not be done directly from the CANVAS element. Chart.js uses its parent container to update the canvas render and display sizes. However, this method requires the container to be relatively positioned and dedicated to the chart canvas only. Responsiveness can then be achieved by setting relative values for the container size

So I did, but I still have the same error.

//chart1
const ctx = document.getElementById('chart1').getContext('2d')
const data1 = {
    labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
    }]
}
const options1 = {
    scales: {
        y: {
            beginAtZero: true
        }
    }
}

const myChart1 = new Chart(ctx, {
    type: 'doughnut',
    data: data1,
    options: options1
})

//chart2
const ctx2 = document.getElementById('chart2').getContext('2d')
const data2 = {
    labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
    }]
}
const options2 = {
    scales: {
        y: {
            beginAtZero: true
        }
    }
}

const myChart2 = new Chart(ctx, {
    type: 'line',
    data: data2,
    options: options2
})
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>GraphJS</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js" integrity="sha512-QSkVNOCYLtj73J4hbmVoOV6KVZuMluZlioC+trLpewV8qMjsWqlIQvkn1KGX2StWvPMdWGBqim1xlC8krl1EKQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>
<body>

    <div style="width: 400px; height: 400px; margin: 0 auto 100px auto;">
        <h1 style="text-align: center;">Tier 1</h1>
        <canvas id="chart1"></canvas>
    </div>

    <div style="width: 400px; height: 400px; margin: 0 auto 100px auto;">
        <h1 style="text-align: center;">Category</h1>
        <canvas id="chart2"></canvas>
    </div>

    <script src="./index.js"></script>
</body>
</html>

Any idea where is my mistake ?

Upvotes: 2

Views: 2590

Answers (1)

Jake Peralta
Jake Peralta

Reputation: 547

You are passing ctx as a parameter for chart2, which should be ctx2. Right now both of your graphs are pointing to same document element i.e. to element with id chart1.

const myChart2 = new Chart(ctx2, {
    type: 'line',
    data: data2,
    options: options2
})

Just do this

Upvotes: 2

Related Questions