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

Chart.js Doughnut Chart 渲染异常:半环形配置未达预期效果

半环形Doughnut Chart实现方案

问题根源

  • circumference参数取值错误:Chart.js中该参数代表环形总绘制弧度,完整圆形取值为2 * Math.PI,半环形仅需设置为1 * Math.PI即可。你之前尝试的60 * Math.PI远大于合法取值范围,会导致图表重复绘制引发样式错乱。
  • rotation参数取值错误:该参数代表环形起始绘制角度,默认值为-0.5 * Math.PI(对应正上方12点钟位置),弧度按顺时针方向递增。要实现0°到180°的上半环形,需要将起始点调整到左侧9点钟位置,对应取值为-1 * Math.PI,你之前设置的1 * Math.PI起始点在正下方6点钟位置,无法得到预期的上半环效果。

修正后代码

import React from 'react';
import { Doughnut } from 'react-chartjs-2';

const data = {
  labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
  datasets: [
    {
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
        'rgba(75, 192, 192, 0.2)',
        'rgba(153, 102, 255, 0.2)',
        'rgba(255, 159, 64, 0.2)',
      ],
      borderColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
        'rgba(75, 192, 192, 1)',
        'rgba(153, 102, 255, 1)',
        'rgba(255, 159, 64, 1)',
      ],
      borderWidth: 1,
    },
  ],
};

const DoughnutChart = () => (
  <>
    <div className='header'>
      <h1 className='title'>Doughnut Chart</h1>
    </div>
    <Doughnut data={data} options={{
      rotation: -1 * Math.PI,
      circumference: 1 * Math.PI
    }} />
  </>
);

export default DoughnutChart;

如果需要实现下半环形(180°到360°的下半圆),将rotation调整为0即可,circumference保持1 * Math.PI不变。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 15:09:01