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

如何实现SVG从上到下红-蓝连续循环渐变(修正弹跳效果)

实现SVG线性渐变的垂直连续循环动画

要实现颜色从底部消失后从顶部重新出现的连续循环效果,你需要动画渐变的位置/偏移量,而非直接切换颜色(这会导致弹跳效果)。以下是两种可行的实现方案:

方案1:动画渐变停止点的offset属性

通过调整两个颜色停止点的偏移量,模拟渐变整体向下滚动的效果:

<svg width="300px" height="500px" viewBox="0 0 180 336">
  <rect x="80" y="50" width="20" height="100" fill="none" stroke="url(#grad)" stroke-linecap="round" stroke-linejoin="round" stroke-width="20"/>
   <defs>
      <linearGradient id="grad" x1="0%" y1="0%" x2="0%" y2="100%">
         <stop offset="0%" stop-color="red">
            <animate 
              attributeName="offset" 
              dur="3s" 
              repeatCount="indefinite" 
              values="-100%;0%" 
              calcMode="linear"
            />
         </stop>
         <stop offset="100%" stop-color="blue">
            <animate 
              attributeName="offset" 
              dur="3s" 
              repeatCount="indefinite" 
              values="0%;100%" 
              calcMode="linear"
            />
         </stop>
       </linearGradient>
   </defs>
</svg>

关键说明:

  • 不再动画stop-color,而是让红色停止点从-100%移动到0%,蓝色停止点从0%移动到100%
  • calcMode="linear"确保动画匀速移动,消除弹跳感
  • 动画循环时,红色会从矩形顶部重新出现,蓝色到达底部后也会从顶部补充,实现无缝滚动

方案2:动画渐变的y1/y2属性

直接移动整个渐变区域的位置,效果更直观:

<svg width="300px" height="500px" viewBox="0 0 180 336">
  <rect x="80" y="50" width="20" height="100" fill="none" stroke="url(#grad)" stroke-linecap="round" stroke-linejoin="round" stroke-width="20"/>
   <defs>
      <linearGradient id="grad" x1="0%" y1="0%" x2="0%" y2="100%">
         <stop offset="0%" stop-color="red"/>
         <stop offset="100%" stop-color="blue"/>
         <animate 
           attributeName="y1" 
           dur="3s" 
           repeatCount="indefinite" 
           values="0%;100%" 
           calcMode="linear"
         />
         <animate 
           attributeName="y2" 
           dur="3s" 
           repeatCount="indefinite" 
           values="100%;200%" 
           calcMode="linear"
         />
       </linearGradient>
   </defs>
</svg>

关键说明:

  • 让渐变的垂直范围从0%~100%移动到100%~200%,模拟整体向下滚动
  • 动画循环时,渐变顶部的颜色会重新进入矩形区域,实现连续循环效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 20:51:12