且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-10-28 23:16:22

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

The most important when trying to morph a path in svg is thast the d attribute hes to have the same number of commands and the same commands. I've rewritten the short path so that the lines drawing the sides of the shape have a length = 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)的位置.移至的值是上一条路径的最后一点.线条是蓝色的路径.

I'm taking both those paths and I'm breaking them in 5 paths of different colors, one for every command. Please note that I had to add a move to command (M) at the beginning of each path. The value for the move to is the last point of the previous path. The lines, are the blue paths.

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

For the short path you can see those blue paths in the code but not in the svg because their length is 0. I needed those 0 length lines because you have lines in the long path.

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>