当图表的标题位于顶部且标签位于圆环图右侧时,如何使用react-chartjs-2.js 和 Typescript 将文本放入圆环图中。到目前为止我找到的解决方案似乎不适用于侧面的标签或 React/TS。
这就是我现在拥有的:
...
setOptions({
responsive: true,
plugins: {
legend: {
position: 'right',
rtl : true,
labels: {
usePointStyle: true,
pointStyle: 'circle',
}
},
title: {
display: true,
text: 'Title',
font: {
size: 25,
}
}
},
});
setPlugins ({
id: "tooltipLine",
beforeDraw: function(chart) {
var width = chart.width,
height = chart.height,
ctx = chart.ctx;
ctx.restore();
var fontSize = (height / 160).toFixed(2);
ctx.font = fontSize + "em sans-serif";
ctx.textBaseline = "top";
var text = "Foo-bar",
textX = Math.round((width - ctx.measureText(text).width) / 2),
textY = height / 2;
ctx.fillText(text, textX, textY);
ctx.save();
}
})
<Doughnut id="pieChart" data={data} options={options} plugins={[plugins] as any}/>
但这只是使文本位于整个画布的中间,而不是甜甜圈的中间。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
const plugins = [{ beforeDraw: function(chart) { var width = chart.width, height = chart.height, ctx = chart.ctx; ctx.restore(); var fontSize = (height / 160).toFixed(2); ctx.font = fontSize + 'em sans-serif'; ctx.textBaseline = 'top'; // Draw "Total" on the first line var text1 = 'Total'; var textX1 = Math.round((width - ctx.measureText(text1).width) / 2); var textY1 = height / 2.5; ctx.fillText(text1, textX1, textY1); // Draw the number on the second line var text2 = totalStatusCountRef.current; var textX2 = Math.round((width - ctx.measureText(text2).width) / 2); var textY2 = height / 1.9; ctx.fillText(text2, textX2, textY2); ctx.save(); } }];