Alexander Solonik
Alexander Solonik

Reputation: 10230

How to animate an svg line from the center point?

I have the following vertical line as an svg element(made using Inkscape), now i would like to make it to draw itself from the center, instead of top to bottom or bottom to top.

    <svg
   xmlns:dc="http://purl.org/dc/elements/1.1/"
   xmlns:cc="http://creativecommons.org/ns#"
   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
   xmlns:svg="http://www.w3.org/2000/svg"
   xmlns="http://www.w3.org/2000/svg"
   xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
   xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
   width="48.136105mm"
   height="79.598999mm"
   viewBox="0 0 48.136105 79.598999"
   version="1.1"
   id="bluetoothIconSvg"
   inkscape:version="0.92.2 5c3e80d, 2017-08-06"
   sodipodi:docname="bluethood-break-apart-icon.svg">
  <g
     inkscape:label="Layer 1"
     inkscape:groupmode="layer"
     id="layer1"
     transform="translate(-33.604957,-76.75465)">
    <path
       style="fill:none;
       stroke:#000000;
       stroke-width:1px;
       stroke-linecap:butt;
       stroke-linejoin:miter;
       stroke-opacity:1"
       d="M 49.924165,76.866652 V 156.24165"
       id="path4508"
       inkscape:connector-curvature="0" />
  </g>
</svg>

Also using just a normal html element such as a <div> or a <span>, this could be achieved easily like so HERE. But i would like to achieve the same using an svg.

Upvotes: 2

Views: 551

Answers (1)

enxaneta
enxaneta

Reputation: 33024

I'm animating your path although I've removed the transformation and changed the viewBox because I wanted to see the hole path. You can use what you have.

I'm using a SMIL animation but you can use the same idea to animate it using css.

In my code 79.375 is the total length of the path. You can get the total length of path using getTotalLength().

39.69 is the half of the total length.

The main idea is this: I'm animating the stroke-dasharray from strokes = 0 gaps = 79.375 to gaps = 0 strokes = 79.375

Also I'm animating the stroke-dashoffset from="-39.69" to="0"

svg{width:50px; border:1px solid silver;}
 <svg 
   viewBox="40 70 48.136105 95"
   >
  <g>
    <path
       style="fill:none;
       stroke:#000000;
       stroke-width:1px;
       stroke-linecap:butt;
       stroke-linejoin:miter;
       stroke-opacity:1"
       d="M 49.924165,76.866652 V 156.24165"
       id="path4508"
       stroke-dasharray="79.375 0"
       stroke-dasharray="-39.69"
          >
       <animate   attributeName="stroke-dasharray"
       attributeType="XML"
       from="0 79.375" to="79.375 0" 
       dur="5s"
       repeatCount="indefinite"  /> 
       <animate   attributeName="stroke-dashoffset"
       attributeType="XML"
       from="-39.69" to="0"
       dur="5s"
       repeatCount="indefinite"  /> 
      
          </path>
  </g>
</svg>

Upvotes: 3

Related Questions