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

Chart.js饼图:如何让数据标签相对扇区固定不偏移?

解决Chart.js饼图旋转时数据标签无法随扇区固定的问题

问题出在你给datalabels.rotation设置了固定数值数组——当饼图整体旋转时,这些固定值不会同步跟随扇区的角度变化,导致标签和对应扇区错位。

要让标签和扇区保持相对位置,需要把rotation改成动态计算的函数,基于扇区自身的中心角度加上你想要的自定义偏移量,这样饼图旋转时,标签会跟着扇区同步调整角度。

修改后的代码如下:

// 把原来的固定旋转值抽成偏移量数组,方便维护
const labelOffsets = [-60, -10, 45, 90, -35, 12, 75];

const myChart = new Chart(wheel, {
  plugins: [ChartDataLabels],
  type: "pie",
  data: {
    labels: chartData.options.map((elem) => elem.title),
    datasets: [
      {
        backgroundColor: pieColors,
        data: data,
        borderWidth: 0,
      },
    ],
  },
  options: {
    responsive: true,
    animation: { duration: 1 },
    plugins: {
      tooltip: false,
      legend: { display: false },
      datalabels: {
        color: chartData.options.map((elem) => elem.text_color),
        font: {
          family: "Poppins",
          size: 13,
          weight: "bold",
          lineHeight: 1.3,
          style: "oblique",
        },
        // 动态计算旋转角度:扇区中心角度 + 自定义偏移量
        rotation: function(context) {
          // 获取当前扇区的中心角度
          const sectorAngle = context.element._model.angle;
          // 取对应索引的偏移量
          const offset = labelOffsets[context.dataIndex];
          // 返回最终旋转角度,确保标签和扇区相对位置固定
          return sectorAngle + offset;
        },
        textAlign: "center",
        formatter: function (value, context) {
          const dataIndex = context.dataIndex;
          return chartData.options[dataIndex].title.toUpperCase();
        },
      },
    },
    border: {
      display: true,
      borderColor: "#c66e16",
    },
  },
});

关键说明:

  • context.element._model.angle会返回当前扇区的中心角度,这个值会随饼图整体旋转动态更新
  • 你原来的固定旋转值现在作为相对偏移量,叠加在扇区角度上,确保标签始终保持你想要的相对于扇区的倾斜角度
  • 不管饼图怎么旋转,标签都会跟着对应扇区同步转动,不会出现错位

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 19:32:53