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

基于SVG的弧形分数条添加渐变颜色时形状崩溃问题求助

解决SVG弧形进度条添加线性渐变时形状崩溃的问题

问题原因

默认情况下,SVG的linearGradient使用objectBoundingBox作为gradientUnits,这会将渐变拉伸到目标元素的矩形包围盒中。对于弧形路径来说,这种拉伸会导致渐变方向与弧形路径不匹配,进而出现显示异常(也就是你说的“形状崩溃”)。

解决方案

通过在SVG中定义linearGradient时指定gradientUnits="userSpaceOnUse",直接基于SVG的用户坐标系设置渐变的起始和结束点,让渐变贴合弧形的路径走向。同时调整渐变的坐标,使其匹配弧形的起点和终点方向。

修改后的完整代码

CSS

.progress-wrapper {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: space-around;
}

path {
  stroke-linecap: round;
}

.grey {
  stroke: #e5e5e5;
  stroke-width: 3px;
}

.green {
  stroke: url(#arcGradient); /* 引用定义好的渐变 */
  stroke-width: 9px;
  stroke-dasharray: 248;
  stroke-dashoffset: 240;
  /* adjust last number for variance */
  &.red-09 {
    stroke-dashoffset: 50;
  }
}

HTML

<div class="progress-wrapper">
  <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="37 -5 120 100" width="120" height="100">
    <!-- 定义线性渐变 -->
    <defs>
      <linearGradient id="arcGradient" gradientUnits="userSpaceOnUse" x1="55" y1="90" x2="140" y2="35">
        <stop offset="0%" stop-color="#4CAF50" />
        <stop offset="100%" stop-color="#2196F3" />
      </linearGradient>
    </defs>
    <path class="grey" d="M55,90
             A55,55 0 1,1 140,90"
          style="fill:none;"/>
    <path class="green red-09" d="M55,90
             A55,55 0 1,1 140,90"
          style="fill:none;"/>
  </svg>
</div>

说明

  • gradientUnits="userSpaceOnUse" 确保渐变坐标基于SVG的用户坐标系,而非元素的包围盒。
  • 渐变的x1,y1对应弧形的起点(55,90),x2,y2对应弧形的终点上方位置(140,35),这样渐变方向会贴合弧形的走向。你可以根据需求调整渐变的起止颜色和坐标,实现不同的渐变效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 22:05:57