I am trying to animate an svg <path>
element. The initial <path>
element has L(lineto)
commands whereas the <path>
that I'm trying to animate it to has C(cubic-bezier curve)
commands. I've tried animating it but it doesn't really transition between the two paths. Is something like this possible?
<svg>
<path id="path" d="M0,50 L25,40 L50,60 L75,40 L100,60 L125,40 L150,50" fill="none" stroke-width="2" stroke="#000" />
<animate xlink:href="#path"
attributeName="d"
dur="3s"
from="M 0 50 L 25 40 L 50 60 L 75 40 L 100 60 L 125 40 L 150 50"
to="M 0 80 C 25 55 50 55 75 80 C 100 105 125 105 150 80"
repeatCount="indefinite" />
</svg>
As you found out, path data animations need to list the exact same sequence of commands and points to work. That said, you can divide a path into as many segments as you need, and a cubic bezier can describe a straight line if its control points are positioned in a straight line. For your example to work, you need to
- rewrite each
L
segment as aC
segment - divide each
C
segment into threeC
segments so that the curve is unchanged
Both tasks are best performed with a grafical editor like Inkscape that has appropriate tools.
<svg>
<path id="path" d="M0,50 L25,40 L50,60 L75,40 L100,60 L125,40 L150,50" fill="none" stroke-width="2" stroke="#000" />
<animate xlink:href="#path"
attributeName="d"
dur="3s"
from="M 0,50
C 12.5,45 12.5,45 25,40
37.5,50 37.5,50 50,60
62.5,50 62.5,50 75,40
87.5,50 87.5,50 100,60
112.5,50 112.5,50 125,40
137.5,45 137.5,45 150,50"
to="M 0,80
C 8.33333,71.6667 16.6667,66.1111 25,63.3333
33.3333,60.5556 41.6667,60.5556 50,63.3333
58.3333,66.1111 66.6667,71.6667 75,80
83.3333,88.3333 91.6667,93.8889 100,96.6667
108.333,99.4444 116.667,99.4444 125,96.6667
133.333,93.8889 141.667,88.3333 150,80"
repeatCount="indefinite" />
</svg>
来源:https://stackoverflow.com/questions/52222405/svg-path-animation-from-lineto-to-cubic-bezier-curve-command