我找到了一个 Chart.js 插件,可以在 Chart.js 圆环图中间写入文本,如下所示。
我在页面上有两个 donut 。一个叫做“myChart”,一个叫做“secondChart”。如果我更改下面的代码以指向第二个图表(如果仅指向第二个图表)。
但是,如果我将其指向第一个图表,则会在两个图表中呈现。有没有办法将此插件更改为可重用函数以在页面上的多个图表上使用?
Chart.pluginService.register({
beforeDraw: function(chart) {
var width = chart.chart.width,
height = chart.chart.height,
ctx = chart.chart.ctx;
ctx.restore();
var fontSize = (height / 120).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 doughnutCenterText = {
beforeDraw: function (chart) {
var width = chart.chart.width,
height = chart.chart.height,
ctx = chart.chart.ctx;
ctx.restore();
var fontSize = (height / 120).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();
}
};
//Chart1
this.doughnutChart1 = new Chart(this.doughnutCanvas1.nativeElement, {
type: 'doughnut',
data: {
datasets: [{
data: [65, 35],
backgroundColor: [
'rgba(229, 57, 53, 1)',
'rgba(229, 57, 53, 0.2)',
],
hoverBackgroundColor: [
'rgba(229, 57, 53, 1)',
'rgba(229, 57, 53, 0.2)',
],
hoverBorderColor: [
'#fff',
'#fff'
]
}]
},
plugins: [doughnutCenterText] //Note here
});
//Chart 2
this.doughnutChart2 = new Chart(this.doughnutCanvas2.nativeElement, {
type: 'doughnut',
data: {
datasets: [{
data: [55, 45],
backgroundColor: [
'rgba(0, 137, 123, 1)',
'rgba(0, 137, 123, 0.2)',
],
hoverBackgroundColor: [
'rgba(0, 137, 123, 1)',
'rgba(0, 137, 123, 0.2)',
],
hoverBorderColor: [
'#fff',
'#fff'
]
}]
},
plugins: [doughnutCenterText] //Note here
});
关于javascript - 如何将 Chart.js 插件指向不同的圆环图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40666555/