SVG动画路径的d属性

28

能否使用SVG来动画化<path>d属性?

我可以使用八条贝塞尔曲线绘制一个菱形和一个圆作为路径:

<html>
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
    <script>
      jQuery(function($){
        var a = 50;

        var draw = function(b, c, d, e, f){
          return [
            'M', a, 0, 

            'C', b, c, ',', d, e, ',', f, f,
            'C', e, d, ',', c, b, ',', 0, a,

            'C', -c, b, ',', -e, d, ',', -f, f,
            'C', -d, e, ',', -b, c, ',', -a, 0,

            'C', -b, -c, ',', -d, -e, ',', -f, -f,
            'C', -e, -d, ',', -c, -b, ',', 0, -a,

            'C', c, -b, ',', e, -d, ',', f, -f,
            'C', d, -e, ',', b, -c, ',', a, 0,
          ].join(' ');
        };

        $('#diamond').attr({ d: draw( 5*a/6,          a/6,                    2*a/3,         a/3,            a/2 ) });
        $('#circle' ).attr({ d: draw(     a, a*Math.PI/12, (2 + 1/Math.sqrt(2))*a/3, a*Math.PI/6, a/Math.sqrt(2) ) });
      });
    </script>
  </head>
  <body>
    <svg width="200" height="200">
      <g transform="translate(100,100)">
        <path id=diamond fill="blue" stroke="black"/>
      </g>
    </svg>
    <svg width="200" height="200">
      <g transform="translate(100,100)">
        <path id=circle fill="red" stroke="black"/>
      </g>
  </body>
</html>

我想要动画地实现从一个状态转换到另一个状态。

我可以在JavaScript中模拟这个过程(只需在特定时间线性插值贝塞尔曲线参数),但我想知道是否有一种用SVG实现的方法。

(圆形和菱形只是一个示例 - 实际上,我想在两个由相同数量的贝塞尔曲线构成的任意立体物体之间进行过渡动画)。

1个回答

31

可以实现。这里有很多关于动画化路径元素d的例子:http://hoffmann.bplaced.net/svgtest/index.php?in=attributes#pathd,其中包括贝塞尔曲线的动画。你应该能够根据你的具体用例进行调整。

这是没有弧形标志动画的path15。大弧形标志只能为0或1,因此线性动画化它没有太多意义。

<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="400px" height="400px" viewBox="-500 100 1500 1500">
<path id="p1"
    d="M 100 100 A 200 400 30 1 0 600 200 a 300 100 45 0 1 -300 200"
    stroke="blue" fill="none"
    stroke-width="4" />
<animate xlink:href="#p1"
    attributeName="d"
    attributeType="XML"
    from="M 100 100 A 200 400 30 1 0 600 200 a 300 100 45 0 1 -300 200"
        to="M 300 600 A 300 400 -20 1 0 400 200 a 200 600 -50 0 1 100 400"
    dur="10s"
    fill="freeze" />
        
</svg>
 


1
我只看到了转换,不知道如何使用它们执行插值(就像我可以在JavaScript中做的那样)。 - rampion
1
看起来我有点过早发言了。在我的浏览器(FF8)中似乎尚不支持所有动画:[path15](http://hoffmann.bplaced.net/svgtest/path15.svg)只是从一种状态闪烁到另一种状态,而[path16](http://hoffmann.bplaced.net/svgtest/path16.svg)可以平稳转换。 - rampion
1
path15 尝试将大弧标志从 0 动画到 1。如果您保持标志相同的值,它将插值得很好。 - Robert Longson
2
不使用已被弃用且浏览器支持不佳的SMIL,是否可以进行路径动画?我的意思是使用样式进行动画-这可行吗? - Qwertiy
1
@Qwertiy 对于路径动画,你可能需要查看snap.svgGreenSock,如此处所建议。关于snap.svg的入门资料可以在这里找到。 - Tim Malone
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接