我在网页上显示一个圆环图,其中chart.js在圆环的中心有一些文字。问题是在同一页面上添加多个dounghnut图表时。中心文本在所有图表上重叠。
结果如下所示doughnut chart with overlapping text
这是一个小提琴:https://jsfiddle.net/jaklar/ng1y18yo/1/
HTML code:
`
<table>
<tr>
<td><canvas id="myChart1" width="150" height="150"></canvas></td>
<td><canvas id="myChart2" width="150" height="150"></canvas></td>
</tr>
<table>
`
的javascript
var data = {
labels: [
"Red",
"Blue"
],
datasets: [
{
data: [100, 100],
backgroundColor: [
"#FF6384",
"#36A2EB"
],
hoverBackgroundColor: [
"#FF6384",
"#36A2EB"
]
}]
};
var promisedDeliveryChart = new Chart(document.getElementById('myChart1'), {
type: 'doughnut',
data: data,
options: {
responsive: true,
cutoutPercentage: 75,
legend: {
display: false
}
}
});
Chart.pluginService.register({
beforeDraw: function(chart) {
var width = chart.chart.width,
height = chart.chart.height,
ctx = chart.chart.ctx;
ctx.restore();
var fontSize = (height / 114).toFixed(2);
ctx.font = fontSize + "em sans-serif";
ctx.textBaseline = "middle";
var text = "100%",
textX = Math.round((width - ctx.measureText(text).width) / 2),
textY = height / 2;
ctx.fillText(text, textX, textY);
ctx.save();
}
});
var data = {
labels: [
"Red",
"Blue"
],
datasets: [
{
data: [300, 0],
backgroundColor: [
"#FF6384",
"#36A2EB"
],
hoverBackgroundColor: [
"#FF6384",
"#36A2EB"
]
}]
};
var promisedDeliveryChart = new Chart(document.getElementById('myChart2'), {
type: 'doughnut',
data: data,
options: {
responsive: true,
cutoutPercentage: 75,
legend: {
display: false
}
}
});
Chart.pluginService.register({
beforeDraw: function(chart) {
var width = chart.chart.width,
height = chart.chart.height,
ctx = chart.chart.ctx;
ctx.restore();
var fontSize = (height / 114).toFixed(2);
ctx.font = fontSize + "em sans-serif";
ctx.textBaseline = "middle";
var text = "9%",
textX = Math.round((width - ctx.measureText(text).width) / 2),
textY = height / 2;
ctx.fillText(text, textX, textY);
ctx.save();
}
});
答案 0 :(得分:0)
第98行替换为以下内容:实际文本正确,但X和Y坐标相同,因此重叠。我在这里增加了Y轴,所以它下降了(如果要保持上侧,请减小Y轴的值),而X则使它们相同,因此它们都从同一位置开始。
ctx.fillText(text,textX,textY + 25);