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

如何正确设置strokeDasharray实现环形进度条按人数比例填充

环形进度条填充问题修复

你的环形进度条填充效果异常,核心问题在于SVG路径的strokeDasharray和strokeDashoffset配置错误,尤其是背景环的设置完全不符合需求,前景环也缺少起点偏移调整。

问题分析

  • 背景环(灰色)使用${fillPercentage + 1},1的strokeDasharray,会把背景切割成无数小段,无法形成完整的底色环
  • 前景环(绿色)未设置strokeDashoffset,默认从右侧开始绘制,不符合常规环形进度条的顶部起点习惯
  • 路径的比例计算逻辑正确,但缺少必要的偏移调整来匹配视觉预期

修正后的代码

const [personQuantity, setPersonQuantity] = useState(6) // 设为总人数6方便测试
const [payingFor, setPayingFor] = useState(1)
const [perPerson, setPerPerson] = useState(0)
const [activate, setActivate] = useState(false)
const subtotal = 120 // 示例总价

useEffect(() => {
  let amountPerPerson = subtotal / personQuantity
  let perPerson = amountPerPerson * payingFor
  setPerPerson(perPerson)

  setActivate(personQuantity >= payingFor && personQuantity > 2)
}, [personQuantity, payingFor, subtotal])

const fillPercentage = (payingFor / personQuantity) * 100
// 环形进度条从顶部开始的偏移值,对应环形总长度的1/4
const dashOffset = 25

return (
  <>
    <div className="h-20 w-20">
      <svg className="circular-chart" viewBox="0 0 36 36">
        {/* 背景环:完整显示,无需分割 */}
        <path
          fill="none"
          strokeWidth="4"
          className="circle-bg bg-DARK_1 stroke-white"
          d="M18 2.0845
            a 15.9155 15.9155 0 0 1 0 31.831
            a 15.9155 15.9155 0 0 1 0 -31.831"
        />
        {/* 前景环:配置正确的比例和起点偏移 */}
        <path
          strokeWidth="4"
          strokeLinecap="round"
          fill="none"
          className="circle stroke-LIGHT_GREEN_1 transition-opacity delay-150 ease-in-out"
          strokeDasharray={`${fillPercentage}, 100`}
          strokeDashoffset={dashOffset}
          d="M18 2.0845
            a 15.9155 15.9155 0 0 1 0 31.831
            a 15.9155 15.9155 0 0 1 0 -31.831"
        />
      </svg>
    </div>
  </>
)

关键改动说明

  • 背景环:移除错误的strokeDasharray,让它显示完整的环形底色
  • 前景环:添加strokeDashoffset={25},将进度条起点从右侧调整到顶部(按100比例的环形计算,25对应90度偏移)
  • 简化useEffect中的激活状态判断逻辑,保持代码简洁
  • 调整初始personQuantity为6,可直接测试1/6、3/6的比例效果

修改后,绿色部分将准确对应选中人数与总人数的比例:选中1人、总6人时填充1/6环形,选中3人时填充一半环形。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 03:09:26