如何在Angular+Primeng环形图(Doughnut Chart)内部添加文本?
实现Primeng环形图(Doughnut Chart)中心显示文本
Primeng的<p-chart>基于Chart.js封装,要实现环形图中心显示文本,需通过自定义Chart.js插件完成,以下是具体实现方案:
1. 编写中心文本自定义插件
在组件中定义Chart.js插件,利用afterDraw钩子在图表绘制完成后,在中心位置绘制目标文本:
const centerTextPlugin = { id: 'centerText', afterDraw: (chart) => { const ctx = chart.ctx; // 计算图表中心坐标 const centerX = chart.chartArea.left + chart.chartArea.width / 2; const centerY = chart.chartArea.top + chart.chartArea.height / 2; // 设置文本样式 ctx.font = 'bold 16px Arial'; ctx.fillStyle = '#333'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; // 绘制文本(可根据业务需求动态替换内容) ctx.fillText('总检查数', centerX, centerY - 10); ctx.font = '24px Arial'; const total = this.inspectionStorage.datasets[0].data.reduce((a: number, b: number) => a + b, 0); ctx.fillText(total.toString(), centerX, centerY + 15); } };
2. 配置图表选项并注册插件
修改doughnutOptions,添加插件同时调整环形空心占比,确保中心有足够空间:
this.doughnutOptions = { responsive: true, cutout: '70%', // 控制环形空心大小,范围0-100% plugins: { legend: { position: 'right', labels: { boxWidth: 17, boxHeight: 15, color: '#000000', }, }, // 注册自定义中心文本插件 centerText: centerTextPlugin }, };
3. 完整组件代码示例
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-doughnut-chart', templateUrl: './doughnut-chart.component.html' }) export class DoughnutChartComponent implements OnInit { inspectionStorage: any; doughnutOptions: any; ngOnInit(): void { const centerTextPlugin = { id: 'centerText', afterDraw: (chart) => { const ctx = chart.ctx; const centerX = chart.chartArea.left + chart.chartArea.width / 2; const centerY = chart.chartArea.top + chart.chartArea.height / 2; ctx.font = 'bold 16px Arial'; ctx.fillStyle = '#333'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; const total = this.inspectionStorage.datasets[0].data.reduce((a: number, b: number) => a + b, 0); ctx.fillText('总检查数', centerX, centerY - 10); ctx.font = '24px Arial'; ctx.fillText(total.toString(), centerX, centerY + 15); } }; this.inspectionStorage = { labels: ['Completed', 'Due', 'Pending', 'Deficient', 'Report'], datasets: [ { data: [45, 25, 15, 10, 5], // 替换为你的实际业务数据 backgroundColor: [ 'green', '#51087E', '#ffd740', 'red', '#5500FF', ], }, ], }; this.doughnutOptions = { responsive: true, cutout: '70%', plugins: { legend: { position: 'right', labels: { boxWidth: 17, boxHeight: 15, color: '#000000', }, }, centerText: centerTextPlugin }, }; } }
4. HTML代码保持不变
<p-chart type="doughnut" [data]="inspectionStorage" [options]="doughnutOptions" ></p-chart>
关键说明
cutout参数:可根据文本长度调整环形空心占比,确保中心区域足够显示内容。- 动态文本:插件中可直接读取图表数据计算动态内容(如示例中的总数统计),适配业务变化。
- 响应式适配:通过
chart.chartArea获取图表实际绘制区域坐标,保证文本始终居中,不受图表尺寸变化影响。
内容的提问来源于stack exchange,提问作者Murugesan R
相关产品推荐
相关产品推荐

