如何动画svg rect成长

时间:2015-07-03 07:07:47

标签: animation svg

我正试图让svg成长,作为从零增长到27.5高度的基本条形图,例如我希望它从下到上动画

我尝试了以下代码,但它使矩形从上到下,而不是从下到上(0高度 - > 27.5高度)。

<?xml version="1.0" encoding="utf-8"?>
    <svg 
       version="1.1"
       id="MAIN"
       xmlns="http://www.w3.org/2000/svg" 
       xmlns:xlink="http://www.w3.org/1999/xlink"
       x="0px"
       y="0px"
       viewBox="0 0 1190.6 841.9" 
       enable-background="new 0 0 1190.6 841.9"
       xml:space="preserve">
           <rect
              id="barchart1" 
              x="148.8"
              y="190"
              fill="#921930"
              width="39.8"
              height="27.5">
                  <animate 
                     attributeName="height" 
                     from="0" 
                     to="27.5"
                     dur="3s"
                     fill="freeze"/>
           </rect>
    </svg>

http://jsfiddle.net/4kp5Lq53/

2 个答案:

答案 0 :(得分:19)

我认为您不会同时动画两个属性,而是会发现使用transform属性更容易获得您想要的坐标系。

在此示例中,动画<rect>元素包含在以下<g>元素中:

<g transform="scale(1,-1) translate(0,-200)">
  ...
</g>

scale转换会颠倒所有y坐标,translate转换会移动坐标,以便y=0位于SVG画布的底部。

<svg version="1.1" xmlns="http://www.w3.org/2000/svg"
     width="400" height="200" viewBox="0 0 400 200">
  <g transform="scale(1,-1) translate(0,-200)">
    <rect x="50" y="0" fill="#f00" width="100" height="100">
      <animate attributeName="height" from="0" to="100" dur="0.5s" fill="freeze" />
    </rect>
    <rect x="150" y="0" fill="#f70" width="100" height="200">
      <animate attributeName="height" from="0" to="200" dur="0.5s" fill="freeze" />
    </rect>
    <rect x="250" y="0" fill="#ec0" width="100" height="150">
      <animate attributeName="height" from="0" to="150" dur="0.5s" fill="freeze" />
    </rect>
  </g>
</svg>

答案 1 :(得分:2)

要从下到上进行动画处理,您必须同时沿y轴向上移动矩形

<rect  id="barchart1" x="148.8" y="190" fill="#921930" width="39.8" height="27.5">
    <animate attributeName="height" from="0" to="27.5" dur="3s" fill="freeze"/>
    <animate attributeName="y" from="190" to="162.5" dur="3s" fill="freeze"/>
</rect>

请参阅小提琴:http://jsfiddle.net/4kp5Lq53/2/