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

如何使用stroke dasharray实现带分段虚线的SVG圆形进度条?

圆形进度条分段虚线实现方案

我一直在尝试复刻目标圆形进度条,但卡在了实现线条间分段虚线的环节,求解决方案。

目标效果

目标进度条设计

当前已实现效果

当前进度条实现效果

当前代码

<CircularProgressbar
  value={value}
  text={`${roundedValue}%`}
  circleRatio={0.75}
  styles={buildStyles({
    rotation: 1 / 2 + 1 / 8,
    strokeLinecap: "butt",
    trailColor: "#eee",
  })}
/>

解决方案

要实现目标图中的分段虚线轨迹,核心是利用SVG的strokeDasharray和strokeDashoffset属性,针对进度条的轨迹(trail)进行样式配置:

  1. 确定分段数量:观察目标图,轨迹被分成了8段等长的虚线,以此为例配置。
  2. 配置轨迹样式:在buildStyles中添加trailStyle,设置strokeDasharray定义虚线的段长和间隔,用strokeDashoffset调整起始位置,确保和进度条的旋转角度对齐。

修改后的代码如下:

<CircularProgressbar
  value={value}
  text={`${roundedValue}%`}
  circleRatio={0.75}
  styles={buildStyles({
    rotation: 1 / 2 + 1 / 8,
    strokeLinecap: "butt",
    trailColor: "#eee",
    // 配置分段虚线轨迹
    trailStyle: {
      // 8段虚线:每段线长和间隔各占总轨迹长度的12.5%
      strokeDasharray: "12.5% 12.5%",
      // 偏移半个间隔,让虚线起始点和进度条旋转角度对齐
      strokeDashoffset: "6.25%",
    },
    // 确保进度条主体为实线
    pathStyle: {
      strokeDasharray: "none",
    },
  })}
/>

说明

  • strokeDasharray: "12.5% 12.5%":总轨迹长度按8段拆分,每段线和间隔各占1/8(12.5%),保证分段均匀。
  • strokeDashoffset: "6.25%":进度条旋转角度为1/2 + 1/8(对应225度),偏移半个间隔可让虚线起始位置完美对齐轨迹起点。
  • 若需调整分段数量,只需修改百分比:比如10段就设置strokeDasharray: "10% 10%",strokeDashoffset: "5%"。

内容的提问来源于stack exchange,提问作者Dragoș Axinte

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 18:43:20