javascript 饼图不随Chart.js一起显示

slmsl1lt  于 2023-03-28  发布在  Java
关注(0)|答案(1)|浏览(116)

我用chart.js做了一个饼图,但它没有出现。我甚至在网上用了一个饼图脚本,它也没有出现。
请谁能读我的剧本,并告诉我,如果我有一个错误,我需要一些帮助,谢谢。

let ctx = document.getElementById('myChart').getContext('2d'); let labels = ['Pizza 🍕', 'Taco 🌮', 'Hot Dog 🌭', 'Sushi 🍣']; let colorHex = ['#FB3640', '#EFCA08', '#43AA8B', '#253D5B'];
let myChart = new Chart(ctx, {
type: 'pie',
data: {
    datasets: [{
    data: [30, 10, 40, 20],
    backgroundColor: colorHex
    }],
    labels: labels
},
options: {
    responsive: true,
    legend: {
    position: 'bottom'
    },
    plugins: {
    datalabels: {
        color: '#fff',
        anchor: 'end',
        align: 'start',
        offset: -10,
        borderWidth: 2,
        borderColor: '#fff',
        borderRadius: 25,
        backgroundColor: (context) => {
        return context.dataset.backgroundColor;
        },
        font: {
        weight: 'bold',
        size: '10'
        },
        formatter: (value) => {
        return value + ' %';
        }
    }
    }
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="myChart" width="1600" height="900"></canvas>
ugmeyewa

ugmeyewa1#

它不工作的原因是因为这条线

Document let ctx = document.getElementById('myChart').getContext('2d'); let labels = ['Pizza 🍕', 'Taco 🌮', 'Hot Dog 🌭', 'Sushi 🍣']; let colorHex = ['#FB3640', '#EFCA08', '#43AA8B', '#253D5B'];

你说Document let ctx = ...,但这是无效的JS,你需要删除Document关键字,这样你就会得到以下内容:

let ctx = document.getElementById('myChart').getContext('2d'); let labels = ['Pizza 🍕', 'Taco 🌮', 'Hot Dog 🌭', 'Sushi 🍣']; let colorHex = ['#FB3640', '#EFCA08', '#43AA8B', '#253D5B'];

如果你这样做,它会工作得很好

相关问题