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

vue-chartjs环形图中间添加文本:仅作用于环形图的问题求助

解决Vue Chart.js环形图仅内部添加文本的问题

我来帮你搞定这个问题~你现在遇到的核心问题是全局注册了Chart插件,导致所有图表都被这个文本绘制逻辑影响了。要让文本只出现在当前环形图里,我们可以把插件改成局部实例,只给这个环形图单独使用,而不是全局注册。

修改后的完整代码

//*** Doughnut chart ***//
import { Doughnut } from "vue-chartjs";
import Chart from "chart.js";

export default {
  extends: Doughnut,
  data: () => ({
    chartdata: {
      labels: ["Cambodia", "Thailand", "Vietnam", "Laos"],
      datasets: [
        { 
          label: "Data One", 
          backgroundColor: ["#a3c7c9", "#889d9e", "#647678", "#f87979"], // 补全了你漏写的#号
          data: [91, 3, 3, 3] 
        }
      ]
    },
    // 定义局部插件:只给当前环形图用的文本绘制逻辑
    centerTextPlugin: {
      beforeDraw: function(chart) {
        const width = chart.chart.width;
        const height = chart.chart.height;
        const ctx = chart.chart.ctx;
        ctx.restore();
        const fontSize = (height / 114).toFixed(2);
        ctx.font = `${fontSize}em sans-serif`;
        ctx.textBaseline = "middle";
        // 从图表配置里取要显示的文本值,更灵活
        const text = chart.config._config.centerTextValue;
        const textX = Math.round((width - ctx.measureText(text).width) / 2);
        const textY = height / 2;
        ctx.fillText(text, textX, textY);
        ctx.save();
      }
    },
    options: {
      legend: { display: false },
      responsive: true,
      maintainAspectRatio: false,
      // 只给当前图表挂载这个局部插件
      plugins: {
        centerText: this.centerTextPlugin
      },
      // 自定义属性:传递要显示的中心文本值
      centerTextValue: 880
    }
  }),
  mounted() {
    // 直接渲染即可,不需要额外调用方法注册插件
    this.renderChart(this.chartdata, this.options);
  }
};
//*** end Doughnut chart ***//

关键修改说明

  • 取消全局插件注册:把原来Chart.pluginService.register的全局逻辑改成了局部插件对象centerTextPlugin,彻底避免影响其他图表
  • 局部挂载插件:在当前图表的options里新增plugins配置,只让这个环形图加载文本插件
  • 优化传参逻辑:新增自定义属性centerTextValue传递文本值,代替原来的方法传参,逻辑更清晰
  • 修复小bug:补全了你原代码里backgroundColor最后一个颜色值漏写的#号

这样修改后,只有这个环形图会在内部显示中心文本,其他Chart.js图表完全不受影响~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 07:47:42