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

Chart.js 4.x环形图中心文本插件兼容问题及方案咨询

解决方案:Chart.js 4.x 环形图中心文本实现与类型问题修复

一、修复自定义插件的TypeScript类型错误

针对你遇到的center_text属性未定义、font需索引访问的类型问题,通过扩展Chart.js类型定义就能解决:

1. 添加自定义类型声明

在项目src目录下创建chartjs-custom-plugin.d.ts文件,写入以下类型扩展代码:

import { ChartType } from 'chart.js';

declare module 'chart.js' {
  interface PluginOptionsByType<TType extends ChartType> {
    center_text?: {
      text: string;
      font?: {
        family?: string;
        size?: number;
        weight?: string;
      };
      color?: string;
    };
  }
}

2. 编写并注册自定义中心文本插件

import { Chart } from 'chart.js';

const centerTextPlugin = {
  id: 'center_text',
  afterDraw: (chart) => {
    const opts = chart.options.plugins?.center_text;
    if (!opts?.text) return;

    const { ctx, chartArea: { width, height } } = chart;
    ctx.save();
    // 组装字体样式
    const font = `${opts.font?.weight || 'bold'} ${opts.font?.size || 16}px ${opts.font?.family || 'Arial'}`;
    ctx.font = font;
    ctx.fillStyle = opts.color || '#000';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.fillText(opts.text, width / 2, height / 2);
    ctx.restore();
  }
};

// 全局注册插件
Chart.register(centerTextPlugin);

3. 图表配置示例(类型兼容)

import { Component, OnInit } from '@angular/core';
import { Chart, ChartConfiguration } from 'chart.js';

@Component({
  selector: 'app-doughnut-chart',
  templateUrl: './doughnut-chart.component.html'
})
export class DoughnutChartComponent implements OnInit {
  chartConfig: ChartConfiguration<'doughnut'> = {
    type: 'doughnut',
    data: {
      labels: ['A', 'B', 'C'],
      datasets: [{
        data: [30, 40, 30],
        backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56']
      }]
    },
    options: {
      cutout: '70%', // 控制环形宽度,预留中心文本空间
      plugins: {
        center_text: {
          text: '总计 100',
          font: {
            size: 20,
            weight: 'bold',
            family: 'Roboto'
          },
          color: '#333'
        },
        legend: { position: 'bottom' }
      }
    }
  };

  ngOnInit(): void {
    new Chart('doughnutChart', this.chartConfig);
  }
}

二、chartjs-plugin-annotation 类型问题的正确处理

不要直接用any绕过类型检查,安装对应版本的类型定义包即可:

npm install @types/chartjs-plugin-annotation --save-dev

之后按照类型规范配置annotation插件,示例:

options: {
  plugins: {
    annotation: {
      annotations: {
        centerText: {
          type: 'text',
          x: 'center',
          y: 'center',
          content: '总计 100',
          font: { size: 20, weight: 'bold' },
          color: '#333'
        }
      }
    }
  }
}

三、无插件极简实现方案

如果不想折腾插件,直接在图表配置中添加afterDraw钩子即可:

new Chart('doughnutChart', {
  type: 'doughnut',
  data: { /* 你的数据 */ },
  options: { cutout: '70%' },
  plugins: [{
    afterDraw: (chart) => {
      const ctx = chart.ctx;
      const centerX = chart.chartArea.width / 2;
      const centerY = chart.chartArea.height / 2;
      ctx.save();
      ctx.font = 'bold 20px Roboto';
      ctx.fillStyle = '#333';
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.fillText('总计 100', centerX, centerY);
      ctx.restore();
    }
  }]
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 05:33:10