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

如何为SVG字母P添加沿绘制路径的渐变填充动画?

实现字母P的手绘路径填充动画

要做出贴合字母P形状的手绘填充效果,我们可以用SVG的描边动画结合遮罩来实现,既保留渐变填充,又让填充过程沿路径逐步展开。下面是修改后的完整代码,以及关键部分的说明:

<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
  <!-- 定义渐变填充和手绘遮罩 -->
  <defs>
    <!-- 从深灰到纯黑的线性渐变 -->
    <linearGradient id="pGradient" x1="0%" y1="0%" x2="100%" y2="100%">
      <stop offset="0%" stop-color="#333"/>
      <stop offset="100%" stop-color="#000"/>
    </linearGradient>
    <!-- 遮罩:用粗描边动画模拟手绘路径 -->
    <mask id="drawMask">
      <path d="M31.5294 14.2118C31.5294 18.8819 28.7623 22.9082 24.7793 24.7351C26.4612 23.3496 27.5322 21.248 27.5322 18.896C27.5322 14.7642 24.2259 11.4042 20.112 11.3205C20.0574 11.3167 20.0075 11.3167 19.9529 11.3167C19.8983 11.3167 19.8485 11.3167 19.7939 11.3205C18.2673 11.4033 17.0588 12.6663 17.0588 14.2108V28.6814C17.0588 33.4748 13.1699 37.3638 8.37646 37.3638V14.2118C8.37646 7.81928 13.5605 2.63528 19.9529 2.63528C26.3454 2.63528 31.5294 7.81928 31.5294 14.2118Z"
            stroke="#fff" stroke-width="20" stroke-linecap="round" stroke-linejoin="round"
            stroke-dasharray="120" stroke-dashoffset="120">
        <!-- 2秒内完成手绘动画,结束后保持最终状态 -->
        <animate attributeName="stroke-dashoffset" from="120" to="0" dur="2s" fill="freeze"/>
      </path>
    </mask>
  </defs>

  <!-- 应用渐变和遮罩的字母P -->
  <path d="M31.5294 14.2118C31.5294 18.8819 28.7623 22.9082 24.7793 24.7351C26.4612 23.3496 27.5322 21.248 27.5322 18.896C27.5322 14.7642 24.2259 11.4042 20.112 11.3205C20.0574 11.3167 20.0075 11.3167 19.9529 11.3167C19.8983 11.3167 19.8485 11.3167 19.7939 11.3205C18.2673 11.4033 17.0588 12.6663 17.0588 14.2108V28.6814C17.0588 33.4748 13.1699 37.3638 8.37646 37.3638V14.2118C8.37646 7.81928 13.5605 2.63528 19.9529 2.63528C26.3454 2.63528 31.5294 7.81928 31.5294 14.2118Z"
        fill="url(#pGradient)" mask="url(#drawMask)"/>
</svg>

关键修改说明

  • 渐变填充:在<defs>里定义了线性渐变,你可以修改stop-color的值来调整渐变的颜色搭配。
  • 遮罩动画:遮罩里的路径用了足够粗的白色描边(stroke-width="20"),刚好能覆盖整个字母区域。通过stroke-dasharray和stroke-dashoffset实现描边从无到有的动画,相当于逐步“解锁”填充区域。
  • 动画参数:dur="2s"控制动画时长,想快一点就改小数值,慢一点就改大;fill="freeze"让动画结束后停在填充完成的状态。
  • 路径长度:stroke-dasharray="120"是原路径的总长度,你可以用浏览器控制台执行document.querySelector('path').getTotalLength()获取更精准的数值。

调整小技巧

  • 要是遮罩的描边没完全覆盖字母,就调大stroke-width的值;
  • 想换渐变方向,修改<linearGradient>里的x1、y1、x2、y2参数就行;
  • 要让动画循环播放,给<animate>标签加repeatCount="indefinite"。

内容的提问来源于stack exchange,提问作者Mateus Henrique Oliveira dos S

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 14:24:54