Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm a SVG beginner so please bear with me.

Basically, I wish to animate a triangle to move from top to bottom when click and move from bottom to top if click again.

My problem is now I can only move a triangle from top to bottom by clicking it. Can anyone suggest a solution to this issue? Any guidance would be appreciated.

<svg viewBox="0 0 24 24" preserveAspectRatio="none">
  <polygon points="2,-5  12,6  22,-5" fill="#000">
    <animate attributeName="points" attributeType="XML"
         from="2,-5  12,6  22,-5"  to="2,0  12,11  22,0"
         begin="click" dur="0.5s"
         fill="freeze">
    </animate>
  </polygon>
</svg>

Or click this link: jsfiddle

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
478 views
Welcome To Ask or Share your Answers For Others

1 Answer

I think that it's not possible with basic svg animate elements, you will need javascript.
(Actually there is what R.Longson proposed in comment)

A dirty way could consist to add a second animate, which will make your element animate to the original step, and trigger the right animate.beginElement() method on click of your <polygon>.

But you will need to keep a reference of the current state you are in, so in the following example, I added a big_state property to the polygon object.

 var poly = document.querySelector('polygon');
 poly.onclick = function() {
   var anims = this.querySelectorAll('animate');
   anims[+!!this.big_state].beginElement();
   this.big_state = !this.big_state;
 }
<svg viewBox="0 0 24 24" preserveAspectRatio="none">
  <script type="text/ecmascript" xlink:href="FakeSmile-master/smil.user.js" />
  <polygon points="2,-5  12,6  22,-5" fill="#000">
    <animate attributeName="points" attributeType="XML" from="2,-5  12,6  22,-5" to="2,0  12,11  22,0" begin="indefinite" dur="0.5s" fill="freeze" id="bigger" />
    <animate attributeName="points" attributeType="XML" from="2,0  12,11  22,0" to="2,-5  12,6  22,-5" begin="indefinite" dur="0.5s" fill="freeze" id="smaller" />
  </polygon>
</svg>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...