How to animate svg path with jQuery/JavaScript?

1.3k views Asked by At

I'd like to animate an svg's path. I know this can be achieved with <animate>, but the animation starts only after the element is appended to some div. So I need to find another solution, but I weren't able to find any help online.

Here is the fiddle so you can take a look at what I have.

Note: Now I'd like the svg's path to stretch the svg. So at first, it is a triangle, but it needs to smoothly convert into a square that fits the svg around it.

Thank you!

// -- click the path -- //

$('path').on('click touch', function() {
  $(this).parents('svg').css({
    height: '100vh',
    width: '100vw'
  });
})
/* -- click the path -- */

* {
  margin: 0;
  padding: 0;
}

body {
  overflow: hidden; /* -- just for this example */
}

svg {
  -webkit-transition:
    height 350ms ease-in-out,
    width 350ms ease-in-out;
  transition:
    height 350ms ease-in-out,
    width 350ms ease-in-out;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- click the path -->

<svg fill="#000" xmlns="http://www.w3.org/2000/svg" version="1.0" height="200" width="200" viewBox="0 0 1024 1024">
  <path d="M0 0 L405 0 L405 635"/>
</svg>

1

There are 1 answers

0
Paul LeBeau On BEST ANSWER

SMIL animations (ie. ones using <animate>) can be made to start on a click.

<svg fill="#000" xmlns="http://www.w3.org/2000/svg" version="1.0" height="200" width="200" viewBox="0 0 1024 1024">
  <path d="M0 0 L405 0 L405 635 L405 635">
    <animate attributeName="d" dur="350ms" to="M0 0 L405 0 L405 635 L0 635"
             begin="click" fill="freeze" />
  </path>
</svg>