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

如何将Chart.js饼图下半部分指定标签旋转180度以提升可读性

实现Chart.js饼图指定标签旋转180度

要让饼图下半部分的「Communities and Social」「Culture and Heritage」「Learning and Skills」「Personal Finance」四个标签旋转180度,你可以通过chartjs-plugin-labels插件的自定义渲染逻辑来实现,以下是修改后的完整代码:

修改后的JavaScript代码

$(document).ready(function() {
  var data = {
    datasets: [{
      data: [125, 125, 125, 125, 125, 125, 125, 125],
      backgroundColor: ["#FE4D42","#FFD405","#58E152","#00D59F","#8B7DFF","#E85FED","#F71663","#4F94FF"]
    }],
    labels: [
      "Arts and Creativity",
      "Careers and Employment",
      "Communities and Social",
      "Culture and Heritage",
      "Learning and Skills",
      "Personal Finance",
      "Self-Environment",
      "Wellbeing"
    ]
  };
    
  var labels_url = {
    "Arts and Creativity" : "arts-and-creativity",
    "Careers and Employment" : "careers-and-employment",
    "Communities and Social" : "communities-and-social",
    "Culture and Heritage" : "culture-and-heritage",
    "Wellbeing" : "health",
    "Learning and Skills" : "learning-and-skills",
    "Personal Finance" : "personal-finance",
    "Self-Environment" : "self-environment"
  };

  // 定义需要旋转180度的标签
  const rotateLabels = [
    "Communities and Social",
    "Culture and Heritage",
    "Learning and Skills",
    "Personal Finance"
  ];
  
  var canvas = document.getElementById("myChart");
  var ctx = canvas.getContext("2d");
  var myNewChart = new Chart(ctx,{
    type: 'pie',
    data: data,
    options: {
      legend: {
          display: false, 
      },
      plugins: {
        labels: {
          render: function(args) {
            const label = args.label;
            const fontColor = args.fontColor;
            const fontSize = args.fontSize;
            const x = args.x;
            const y = args.y;

            ctx.font = `${fontSize}px Arial`;
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';

            if (rotateLabels.includes(label)) {
              // 保存当前画布状态
              ctx.save();
              // 旋转180度
              ctx.rotate(Math.PI);
              // 调整文本位置,适配旋转后的坐标系
              ctx.fillStyle = fontColor;
              ctx.fillText(label, -x, -y);
              // 恢复画布状态,避免影响其他元素
              ctx.restore();
            } else {
              // 正常绘制标签
              ctx.fillStyle = fontColor;
              ctx.fillText(label, x, y);
            }
            return ''; // 返回空字符串,覆盖插件默认绘制逻辑
          },
          arc: true,
          fontColor:["#FF7805","#0854A3","#14A400","#048A7D","#502788","#F200F2","#FF0068","#000962"],
          fontSize: 18,
          position: 'outside'
        }
      }
    }
  });

  canvas.onclick = function(evt) {
    var activePoints = myNewChart.getElementsAtEvent(evt);
    if (activePoints[0]) {
      var chartData = activePoints[0]['_chart'].config.data;
      var idx = activePoints[0]['_index'];

      var label = chartData.labels[idx];
      var value = chartData.datasets[0].data[idx];

      var url = "https://www.maximiseme.co.uk/" + labels_url[label];
      console.log(url);
      window.location.href = url;
    }
  };
});

HTML代码

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
<script src="https://cdn.jsdelivr.net/gh/emn178/chartjs-plugin-labels/src/chartjs-plugin-labels.js"></script>

<canvas id="myChart"></canvas>

关键修改说明

  • 新增rotateLabels数组,明确标记需要旋转的标签集合
  • 重写render函数,接管标签绘制逻辑:
    • 对目标标签,通过画布的save()/restore()方法隔离旋转操作,避免影响其他元素
    • 旋转后调整文本坐标,适配反转后的坐标系
    • 返回空字符串覆盖插件默认的标签绘制行为,防止重复渲染

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 08:03:20