一页中的多个图表 - Chartjs

Multiple charts in one page - Chartjs

我尝试在一页中添加多个图表,但出现错误 Canvas is already in use. Chart with ID '0' must be destroyed before the canvas can be reused

经过研究,我了解到我必须在 div 中设置我的 canvas 因为 :

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

我也是这样做的,但我仍然有同样的错误。

//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>

知道我的错误在哪里吗?

您将 ctx 作为图表 2 的参数传递,它应该是 ctx2。现在,您的两个图表都指向相同的文档元素,即 ID 为 chart1.

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

就这样做