Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to animate svg rect to grow

Tags:

animation

svg

I'm trying to make an svg grow, as a basic bar chart that is growing from zero to the height of 27.5, e.g. I want it to animate from bottom to top

I tried the following code but it makes the rectangle grow from top to bottom, rather than bottom to top (0 height -> 27.5 height).

<?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/

like image 924
Ushka Avatar asked Jul 03 '15 07:07

Ushka


1 Answers

Instead of animating two attributes simultaneously, I think you'll find it much easier to use a transform attribute to get the coordinate system you wanted in the first place.

In this example, the animated <rect> elements are wrapped in the following <g> element:

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

The scale transform turns all the y coordinates upside down, and the translate transform shifts the coordinates so that y=0 is at the bottom of the SVG canvas.

<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>
like image 151
r3mainer Avatar answered Oct 07 '22 15:10

r3mainer