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

如何在ChartJS生成的Donut Chart(甜甜圈图)中间添加居中文字

Chart.js 甜甜圈图添加中心文字解决方案

你可以通过 Chart.js 的实例插件钩子直接在中心绘制文字,无需额外引入依赖,修改后的完整代码如下:

$(function () {
    /* ChartJS
     * -------
     * Here we will create a few charts using ChartJS
     */

    //-------------
    //- DONUT CHART -
    //-------------
    // Get context with jQuery - using jQuery's .get() method.
    var donutChartCanvas = $('#donutChart').get(0).getContext('2d')
    var donutData        = {
      
      datasets: [
        {
          data: [70,30],
          backgroundColor : ['green','red'],
        }
      ]
    }

    var donutOptions     = {
      maintainAspectRatio : false,
      responsive : true,
    }

    //Create pie or douhnut chart
    // You can switch between pie and douhnut using the method below.
    var donutChart = new Chart(donutChartCanvas, {
      type: 'doughnut',
      data: donutData,
      options: donutOptions,
      // 新增插件配置绘制中心文字
      plugins: [{
        id: 'centerText',
        afterDraw: function(chart) {
          const ctx = chart.ctx;
          const centerX = chart.width / 2;
          const centerY = chart.height / 2;
          
          ctx.restore();
          // 自定义文字样式
          ctx.font = 'bold 26px sans-serif';
          ctx.textAlign = 'center';
          ctx.textBaseline = 'middle';
          ctx.fillStyle = '#333';
          // 自定义显示内容,可根据需求修改
          const showText = `${chart.data.datasets[0].data[0]}%`;
          ctx.fillText(showText, centerX, centerY);
          ctx.save();
        }
      }]
    });
});
  • 如果需要调整文字大小、颜色,直接修改ctx.font、ctx.fillStyle的参数即可
  • 如果需要显示其他自定义内容,直接替换showText变量的赋值逻辑即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 04:27:03