如何在Doughnut环形图中心添加文本标签?附现有代码
环形图中心添加文本标签的解决方案
要在Doughnut环形图中心添加自定义文本,可通过Chart.js的自定义插件实现,以下是修改后的完整代码:
import React, { Component } from 'react'; import { Chart } from 'react-chartjs-2'; // 若使用Chart.js v3+,需引入必要的注册项(未添加过则启用下方代码) // import { Chart as ChartJS, ArcElement, Tooltip, Legend } from 'chart.js'; // ChartJS.register(ArcElement, Tooltip, Legend); // 自定义中心文本插件 const centerTextPlugin = { id: 'centerText', afterDraw: (chart) => { const ctx = chart.ctx; // 计算图表中心坐标 const centerX = chart.chartArea.left + (chart.chartArea.right - chart.chartArea.left) / 2; const centerY = chart.chartArea.top + (chart.chartArea.bottom - chart.chartArea.top) / 2; // 设置文本样式 ctx.font = 'bold 20px Arial'; ctx.fillStyle = '#495057'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; // 绘制文本:示例为数据总和,可替换为固定文本(如"总计")或其他动态内容 const total = chart.data.datasets[0].data.reduce((sum, value) => sum + value, 0); ctx.fillText(`总数: ${total}`, centerX, centerY); // 如需多行文本,可调整Y轴偏移继续绘制 // ctx.fillText('第二行内容', centerX, centerY + 25); } }; export class DoughnutChartDemo extends Component { constructor(props) { super(props); this.chartData = { labels: ['A', 'B', 'C'], datasets: [ { data: [300, 50, 100], backgroundColor: ["#FF6384", "#36A2EB", "#FFCE56"], hoverBackgroundColor: ["#FF6384", "#36A2EB", "#FFCE56"] } ] }; this.lightOptions = { plugins: { legend: { labels: { color: '#495057' } }, centerText: {} // 启用自定义插件 } }; } render() { return ( <div className="card flex justify-content-center"> <Chart type="doughnut" data={this.chartData} options={this.lightOptions} plugins={[centerTextPlugin]} // 注入自定义插件 style={{ position: 'relative', width: '40%' }} /> </div> ); } }
关键说明:
- 插件执行时机:通过
afterDraw钩子在图表绘制完成后渲染文本,避免被图表元素覆盖。 - 精准定位:利用
chart.chartArea获取图表实际绘制区域,计算出中心坐标,适配不同尺寸的图表。 - 样式与内容自定义:可按需修改字体、颜色、文本内容,支持固定文本或基于数据的动态计算内容(如示例中的数据总和)。
- 插件注入:在
Chart组件的plugins属性传入自定义插件,确保功能生效。
内容的提问来源于stack exchange,提问作者Kulothungan Senthil
相关产品推荐
相关产品推荐

