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

CSS Animated Radial Graph动画后描边溢出问题求助

解决径向动画图的描边偏移问题

问题根源分析

  1. stroke-dasharray取值错误:你使用了固定值210,但正确取值应该基于圆的周长计算。圆周长公式为2πr,这里r=90,周长约为565.49px,固定值会导致动画结束时描边无法精准停在原点。
  2. 缺失动画关键帧定义:仅指定了动画名称和方向,但未定义@keyframes fill,浏览器无法解析正确的动画逻辑。
  3. 描边宽度引发的半径偏移:.front的stroke-width比.back大5px,SVG描边为居中绘制,会导致两个圆的描边视觉错位,放大偏移问题。
  4. 动画方向与逻辑不匹配:使用reverse方向但未对应正确的起始/结束状态,导致描边回退异常。

修复后的代码

CSS部分

.radial-graph-container {
  display: flex;
  justify-content: center;
  flex-direction: column;
  padding-bottom: 2.4rem;
}

.radial-graph-container .chart-container .back {
  stroke: #101114;
  stroke-width: 10;
}

.radial-graph-container .chart-container .front {
  stroke: #94d82d;
  stroke-width: 15;
  /* 周长=2*π*r=2*3.1416*87.5≈549.78px(r调整为87.5抵消stroke-width差异) */
  stroke-dasharray: 549.78;
  stroke-dashoffset: 549.78;
  transform: rotate(-90deg);
  transform-origin: center;
  animation: fill 1s forwards;
}

/* 定义从全隐藏到显示42%的动画逻辑 */
@keyframes fill {
  to {
    /* 42%完成度:dashoffset=周长*(1-0.42)=549.78*0.58≈318.87 */
    stroke-dashoffset: 318.87;
  }
}

HTML部分(仅调整front的r值)

<div class="radial-graph-container">
  <svg width="200" height="200" class="chart-container">
      <circle cx="100" cy="100" r="90" class="back" fill="none" />
      <!-- 调整r为87.5,抵消stroke-width比back大5px的居中偏移 -->
      <circle cx="100" cy="100" r="87.5" class="front" fill="none" />
      <g class="graph-center-txt">
        <text
        x="100"
        y="100"
          alignment-baseline="central"
          text-anchor="middle"
          id="percentage-social-media-usage"
        >
          42%
        </text>
      </g>
    </svg>
  <p class="graph-info-txt">
    Description Text Here
  </p>
</div>

关键修复点说明

  • 周长计算与dash设置:以实际周长作为stroke-dasharray,初始stroke-dashoffset设为周长(完全隐藏描边),动画结束时设为周长*(1-进度百分比),确保描边精准停在目标位置。
  • 半径调整:.front的r从90改为87.5,因为它的stroke-width半宽为7.5,.back的stroke-width半宽为5,87.5+7.5=95、90+5=95,让两个圆的描边外边缘对齐,避免视觉错位。
  • 动画逻辑修正:使用forwards保持动画结束状态,定义to帧对应目标进度,去掉reverse避免状态反转异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 07:30:22