gpt4 book ai didi

javascript - 如何使用 Chart.js 版本 3.2.1 在圆环图中添加文本

转载 作者:行者123 更新时间:2023-12-02 18:45:34 24 4
gpt4 key购买 nike

  1. 我在 HTML 中使用 Canvas,如何在圆环图中添加文本。这是我的 javascript 代码和 HTML 代码。我使用过 chart js 版本 3.2.1,所以请给出相同版本(3)的解决方案。

var overallStatsCanvasCtx = document.getElementById('pademicOverallStats');
var dataPandemicEmp = {
labels: ['Normal', 'No Mask', 'Warning', 'High Temperature'],
datasets: [{
label: "Overall Statistics",
data: ['4000', '2000', '1500', '2500'],
backgroundColor: ['#43C187', '#8FC3F0', '#FFCD5E', '#FF4800'],

}]
};
var overallStatschartOptions = {
responsive: true,
plugins: {
legend: {
display: true,
align: 'center',
position: 'bottom',
labels: {

fontColor: '#474B4F',
usePointStyle: true,

}
}
},
};
var doughnutChart = new Chart(overallStatsCanvasCtx, {
type: 'doughnut',
data: dataPandemicEmp,
options: overallStatschartOptions,


});
<canvas id="pademicOverallStats"></canvas>

最佳答案

你必须为此使用自定义插件

var data = {
labels: [
"Red",
"Blue",
"Yellow"
],
datasets: [{
data: [300, 50, 100],
backgroundColor: [
"#FF6384",
"#36A2EB",
"#FFCE56"
],
hoverBackgroundColor: [
"#FF6384",
"#36A2EB",
"#FFCE56"
]
}]
};

var promisedDeliveryChart = new Chart(document.getElementById('myChart'), {
type: 'doughnut',
data: data,
options: {
responsive: true,
plugins: {
legend: {
display: false
}
}
},
plugins: [{
id: 'text',
beforeDraw: function(chart, a, b) {
var width = chart.width,
height = chart.height,
ctx = chart.ctx;

ctx.restore();
var fontSize = (height / 114).toFixed(2);
ctx.font = fontSize + "em sans-serif";
ctx.textBaseline = "middle";

var text = "75%",
textX = Math.round((width - ctx.measureText(text).width) / 2),
textY = height / 2;

ctx.fillText(text, textX, textY);
ctx.save();
}
}]
});
<body>
<canvas id="myChart"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.2.0/dist/chart.min.js"></script>
</body>

关于javascript - 如何使用 Chart.js 版本 3.2.1 在圆环图中添加文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67486126/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com