我试图在Chart.js中使用格式。我已经正确配置了导入,但它仍然没有显示我想要的
在我的本地电脑上不工作。我上传了相同的代码到codepen,它也不起作用。你可以在这里验证
var donutEl = document.getElementById("donut").getContext("2d");
var data = [4, 9, 5, 2];
var pieChart = new Chart(donutEl, {
type: 'doughnut',
data: {
datasets: [
{
data: [10, 20, 15, 5, 50],
backgroundColor: [ 'rgb(255, 99, 132)', 'rgb(255, 159, 64)', 'rgb(255, 205, 86)', 'rgb(75, 192, 192)', 'rgb(54, 162, 235)', ],
},
],
labels: ['Red', 'Orange', 'Yellow', 'Green', 'Blue'],
},
options: {
plugins: {
datalabels: {
formatter: (value) => {
return value + '%';
}
}
}
}
})
你知道我做错了什么吗?由于
如下所述,您需要注册插件:
Chart.register(ChartDataLabels);
生活的例子:
Chart.register(ChartDataLabels);
const donutEl = document.getElementById("donut").getContext("2d");
const data = [4, 9, 5, 2];
const pieChart = new Chart(donutEl, {
type: 'doughnut',
data: {
datasets: [{
data: [10, 20, 15, 5, 50],
backgroundColor: ['rgb(255, 99, 132)', 'rgb(255, 159, 64)', 'rgb(255, 205, 86)', 'rgb(75, 192, 192)', 'rgb(54, 162, 235)', ],
}, ],
labels: ['Red', 'Orange', 'Yellow', 'Green', 'Blue'],
},
options: {
plugins: {
datalabels: {
formatter: (value) => {
return value + '%';
}
}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.0.0/chartjs-plugin-datalabels.min.js"></script>
<div class="flexWrapper">
<canvas id="donut" width="400" height="400"></canvas>
</div>