You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PrimeNG Doughnut环形图内部放置文本

在PrimeNG Doughnut环形图内部添加文本

PrimeNG的<p-chart>基于Chart.js实现,要在环形图中心添加文本,可通过自定义Chart.js插件来完成,具体实现如下:

实现步骤

  • 修改doughnutOptions,添加自定义插件,通过beforeDraw钩子在画布上绘制中心文本
  • 计算环形图的中心坐标,设置文本的样式、内容

完整代码示例

组件类代码

this.data = {
  labels: ['a', 'b', 'c', 'd', 'e'],
  datasets: [
    {
      data: [20, 30, 15, 25, 10], // 填充实际数据,否则环形图无法显示
      backgroundColor: ['green', '#51087E', '#ffd740', 'red', '#5500FF'],
    },
  ],
};

this.doughnutOptions = {
  responsive: true,
  plugins: {
    legend: {
      position: 'right',
    },
    // 自定义插件配置:可灵活修改文本内容和样式
    customCenterText: {
      text: '中心文本',
      color: '#333',
      fontSize: 16,
      fontWeight: 'bold'
    },
    // 注册绘制钩子
    beforeDraw: (chart) => {
      const centerTextConfig = chart.config.plugins.customCenterText;
      if (centerTextConfig) {
        const ctx = chart.ctx;
        // 获取环形图中心坐标
        const centerX = chart.getDatasetMeta(0).data[0].x;
        const centerY = chart.getDatasetMeta(0).data[0].y;
        
        // 设置文本样式
        ctx.font = `${centerTextConfig.fontWeight} ${centerTextConfig.fontSize}px Arial`;
        ctx.fillStyle = centerTextConfig.color;
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        
        // 绘制文本
        ctx.fillText(centerTextConfig.text, centerX, centerY);
      }
    }
  },
};

模板代码

<p-chart type="doughnut" [data]="data" [options]="doughnutOptions"></p-chart>

关键说明

  • 必须确保datasets.data数组有实际数值,否则环形图无法渲染,也无法获取中心坐标
  • 若需要多行文本,可多次调用ctx.fillText()并调整centerY的偏移量(比如centerY + 20)
  • 文本内容支持动态绑定,可替换为变量或计算值

内容的提问来源于stack exchange,提问作者Joshna J.U

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 21:24:27