Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
498 views
in Technique[技术] by (71.8m points)

html - Toggle SVG animation effect when click the button

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

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

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...