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

Angular 2中如何在ng2-charts环形图内部添加文本?

在ng2-charts环形图中心添加文本的解决方案

要在ng2-charts的环形图(doughnut chart)中心添加自定义文本(比如"15$"),我们需要利用其底层依赖Chart.js的自定义绘制能力,以下是具体实现步骤:

1. 修改组件代码,添加图表配置选项

在你的ChartbalanceComponent中,新增图表的options配置,通过回调函数在图表绘制完成后,在中心位置绘制目标文本:

import { Component, OnInit } from '@angular/core';
// 可选:导入Chart类型以获得更好的代码提示
import { ChartOptions } from 'chart.js';

@Component({ 
  selector: 'app-chartbalance', 
  templateUrl: './chartbalance.component.html', 
  styleUrls: ['./chartbalance.component.css'] 
}) 
export class ChartbalanceComponent implements OnInit { 
  constructor() { } 
  ngOnInit() { } 

  public doughnutChartType: string = "doughnut"; 
  public doughnutChartData: number[] = [40, 40, 20]; 
  public doughnutChartLabels: string[] = ["ETH", "LTC", "XRP"];

  // 新增图表配置选项
  public doughnutChartOptions: ChartOptions = {
    responsive: true,
    maintainAspectRatio: false, // 按需调整,保持图表比例
    plugins: {
      legend: {
        position: 'bottom', // 图例位置可自定义
      },
    },
    animation: {
      onComplete: function() {
        const chart = this.chart;
        const ctx = chart.ctx;
        // 设置文本对齐方式为中心
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        // 计算图表中心坐标
        const centerX = (chart.chartArea.left + chart.chartArea.right) / 2;
        const centerY = (chart.chartArea.top + chart.chartArea.bottom) / 2;
        
        // 绘制中心文本
        ctx.font = 'bold 24px Arial'; // 自定义字体样式
        ctx.fillStyle = '#333'; // 自定义文本颜色
        ctx.fillText('15$', centerX, centerY);
      }
    }
  };
}

2. 修改HTML模板,绑定配置选项

在<canvas>标签中添加[options]属性,将我们定义的配置传入图表:

<div align="center"> 
  <label style="font-size: 19px;">Chart</label> 
  <canvas 
    baseChart 
    [data]="doughnutChartData" 
    [labels]="doughnutChartLabels" 
    [chartType]="doughnutChartType"
    [options]="doughnutChartOptions"
  > 
  </canvas> 
</div>

额外优化说明

  • 你可以根据需求调整文本的字体大小、颜色、样式(修改ctx.font、ctx.fillStyle等属性即可)。
  • 如果图表数据会动态更新,不用担心,图表重新渲染时文本会自动重新绘制。
  • 若需要在多个图表中复用该功能,可以抽离成自定义插件:
// 自定义中心文本插件
const centerTextPlugin = {
  id: 'centerText',
  afterDraw: (chart) => {
    const ctx = chart.ctx;
    const centerX = (chart.chartArea.left + chart.chartArea.right) / 2;
    const centerY = (chart.chartArea.top + chart.chartArea.bottom) / 2;
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.font = 'bold 24px Arial';
    ctx.fillStyle = '#333';
    ctx.fillText('15$', centerX, centerY);
  }
};

// 然后在options中注册插件
public doughnutChartOptions: ChartOptions = {
  plugins: {
    legend: { position: 'bottom' },
    centerText: centerTextPlugin // 注册自定义插件
  }
};

内容的提问来源于stack exchange,提问作者Nguyenhuyen_AG

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:41:17