如何将路径数据变形为 SVG 中的另一个路径数据?

How to morph a path data to another path data in SVG?

我想弄清楚为什么它不会将这个路径数据变形为另一个路径数据,我需要让它看起来像一个真正的动画。

这是我的 SMIL 代码:

    <animate xlink:href="#Barra3"  
    repeatCount="indefinite" 
    attributeName="d" 
    dur="5s"
    values="M52,346L56,346C61.523,346 66,350.477 66,356L42,356C42,350.477 46.477,346 52,346Z;
    M54,225C60.627,225 66,230.373 66,237L66,356L42,356L42,237C42,230.373 47.373,225 54,225Z;"/>

这是我的代码笔:

https://codepen.io/joannesalfa/pen/mdPBJxq 然后转到第 181 行。我正在使用 SMIL。

尝试变形 svg 中的路径时最重要的是 d 属性必须具有相同数量的命令和相同的命令。我重写了短路径,使绘制形状两侧的线的长度为 0。

M54,346
C60.627,346,66,351.373,66,358
L66,358L42,358L42,358
C42,351.373,47.373,346,54,346Z

请看:

svg{border:solid}
<svg viewBox="5 200 100 200" width="100">


  <path d="M54,346
          C60.627,346,66,351.373,66,358
          L66,358L42,358L42,358
          C42,351.373,47.373,346,54,346Z"  stroke="red" fill="gold" >

  <animate  dur='5s'
    attributeType="XML"
    attributeName='d'      
    repeatCount='indefinite'
           values="M54,225
           C60.627,225 66,230.373 66,236
           L66,356L42,356L42,236
           C42,230.373 47.373,225 54,225Z;
                                                                     
           M54,346
           C60.627,346,66,351.373,66,356
           L66,356L42,356L42,356
           C42,351.373,47.373,346,54,346Z;
                                                                                  M54,225
           C60.627,225 66,230.373 66,236
           L66,356L42,356L42,236
           C42,230.373 47.373,225 54,225Z" />
    
    </path>
</svg>

更新

OP 正在评论:

Would you mind how to rewrite the short path step by step? I find it's very confusing to me

我将采用这两条路径,并将它们分成 5 条不同颜色的路径,一条用于每个命令。请注意,我必须在每条路径的开头添加一个移动到命令 (M)。移动到的值是先前路径的最后一个点。线条,是蓝色的路径。

对于短路径,您可以在代码中看到那些蓝色路径,但在 svg 中看不到,因为它们的长度为 0。我需要那些长度为 0 的线,因为长路径中有线。

svg{width:200px;border:solid;overflow:visible; fill:none}
<svg viewBox="40 220 28 140" >
  <desc>The short path</desc>
  <path d="M54,346 C60.627,346,66,351.373,66,356" stroke="red" /> 
  <path d="M66,356 L66,356" stroke="blue" />           
  <path d="M66,356 L42,356" stroke="green" />    
  <path d="M42,356 L42,356" stroke="blue" /> 
  <path d="M42,356 C42,351.373,47.373,346,54,346" stroke="gold"/>

</svg>

<svg viewBox="40 220 28 140" >
  <desc>The long path</desc>
      <path d="M54,225 C60.627,225 66,230.373 66,237" stroke="red"/> 
      <path d="M66,237 L66,356" stroke="blue" />
      <path d="M66,356 L42,356" stroke="green" />  
      <path d="M42,356 L42,237" stroke="blue"/>
      <path d="M42,237 C42,230.373 47.373,225 54,225;" stroke="gold"/>

</svg>