我知道有几个答案,但似乎这个有点不同。我需要更改甜甜圈图,将第一个和最后一个四舍五入。因此,在我的示例中,黑色(第一个数据集)只会在开头(一侧)四舍五入,而灰色(最后一个但一个)将在末尾四舍五入,如图所示。
当然,这是 Chart.js 的最新版本(v3)。
我在这里使用了一些代码:Chart.js Donut with rounded edges and text centered
也许使用自定义图表会更好,但我什至无法做到这一点。
到目前为止,这是我的代码。只对第一个数据集进行四舍五入,不幸的是它的两边。
Chart.defaults.elements.arc.borderWidth = 0;
Chart.defaults.elements.arc.roundedCornersFor = 0;
Chart.defaults.elements.arc.hoverBorderColor = 'white';
Chart.defaults.datasets.doughnut.cutout = '85%';
var doughnutChart = document.getElementById('doughnutChart');
if(doughnutChart) {
new Chart(doughnutChart, {
type: 'doughnut',
// The data for our dataset
data: {
labels: [
'Label 1',
'Label 2',
'Label 3',
'Label 4'
],
datasets: [{
label: 'My First Dataset',
data: [22, 31, 26, 19],
backgroundColor: [
'#000000',
'#ffff00',
'#aaaaaa',
'#ff0000'
]
}]
},
plugins: [
{
afterUpdate: function(chart) {
if (chart.options.elements.arc.roundedCornersFor !== undefined) {
var arc = chart.getDatasetMeta(0).data[chart.options.elements.arc.roundedCornersFor];
arc.round = {
x: (chart.chartArea.left + chart.chartArea.right) / 2,
y: (chart.chartArea.top + chart.chartArea.bottom) / 2,
radius: (arc.outerRadius + arc.innerRadius) / 2,
thickness: (arc.outerRadius - arc.innerRadius) / 2,
backgroundColor: arc.options.backgroundColor
}
}
},
afterDraw: (chart) => {
if (chart.options.elements.arc.roundedCornersFor !== undefined) {
var {ctx, canvas} = chart;
var arc = chart.getDatasetMeta(0).data[chart.options.elements.arc.roundedCornersFor];
var startAngle = Math.PI / 2 - arc.startAngle;
var endAngle = Math.PI / 2 - arc.endAngle;
ctx.save();
ctx.translate(arc.round.x, arc.round.y);
ctx.fillStyle = arc.round.backgroundColor;
ctx.beginPath();
ctx.arc(arc.round.radius * Math.sin(startAngle), arc.round.radius * Math.cos(startAngle), arc.round.thickness, 0, 2 * Math.PI);
ctx.arc(arc.round.radius * Math.sin(endAngle), arc.round.radius * Math.cos(endAngle), arc.round.thickness, 0, 2 * Math.PI);
ctx.closePath();
ctx.fill();
ctx.restore();
}
}
}
]
});
}
.container {
width: 400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.3.2/chart.min.js"></script>
<div class="container">
<canvas id="doughnutChart"></canvas>
</div>