以中心点为起点的SVG缩放动画,而不是左上角

15

如何在SVG中使用animateTransform来使对象从中心点缩放而不是左上角?

示例:

<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100px" height="100px">
    <circle style="fill:blue;" cx="50" cy="50" r="45">
        <animateTransform attributeName="transform"
             type="scale"
             from="0 0"
             to="1 1"
             begin="0s"
             dur="1s"
             repeatCount="indefinite"
        />
    </circle>
</svg>

(Codepen: http://codepen.io/anon/pen/wKwrPg?editors=100)

输入图像描述

2个回答

17
更改比例变换以使用 additive="sum",并应用另一个变换将圆形平移至图像中心。因此,不要在图像中心定义形状,而是将其中心定义为0 0,然后使用transform属性将其平移到50, 50(您特定图像的确切中心)。
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100px" height="100px">
    <circle style="fill:blue;" cx="0" cy="0" r="45" transform="translate(50 50)">
        <animateTransform attributeName="transform"
             type="scale"
             additive="sum" 
             from="0 0"
             to="1 1"
             begin="0s"
             dur="1s"
             repeatCount="indefinite"
        />
    </circle>
</svg>

这是另一个例子,使用defsuse标签来重复使用圆形定义:

<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100px" height="100px">
    <defs>
        <circle id="def-circle" style="fill:blue;" cx="0" cy="0" r="45" />
    </defs>

    <use xlink:href="#def-circle" transform="translate(50 50)">
        <animateTransform attributeName="transform" 
        type="scale"
        additive="sum"    
        from="0 0"
        to="1 1"      
        beg="0s"
        dur="1s"
        repeatCount="indefinite" />
    </use>   
</svg>

如果不是一个圆,例如一个复杂的路径,如何定义它在中心?只需计算精确的中心点,然后先移动到那里,然后再移动到实际起始位置即可。 - Justin

3
你也可以借助CSS样式transform-origin属性来完成这个操作。
优点是你不需要计算坐标并移动你的对象。
<svg version="1.1" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
  <style>
    #logo { transform-origin: center; }
  </style>

  <g id="logo">
    <animateTransform attributeName="transform" begin="0s" type="scale" dur="2s" from="1" to=".5" repeatCount="indefinite"/>
    <circle r="8" cx="12" cy="12" />
  </g>
</svg>

#logo {
  transform-origin: center;
}
<svg version="1.1" viewBox="0 0 24 24" width="100%" height="100px" xmlns="http://www.w3.org/2000/svg">
  <g id="logo">
    <animateTransform attributeName="transform" begin="0s" type="scale" dur="2s" from="1" to=".5" repeatCount="indefinite"/>
    <circle r="8" cx="12" cy="12" />
  </g>  
</svg>

在您的特定情况下,另一种方法是动画圆形本身的半径。
<circle r="0" cx="50" cy="50">
  <animate attributeName="r" from="0" to ="10" begin="1s" dur="300ms" fill="freeze" />
</circle>

感谢 Robert Longson 提供了 这个答案


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