Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start a svg animation onclick event

This following code works fine when an initial begin time is provided for the animation of the SVG polygon. But I can't figure out how to trigger it via javascript/jquery without providing a begin time to "vbanim" animation.

$('button').click(function() {
  $('#v-b').beginElement();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click to draw</button>
<svg width="100px" height="100px" preserveAspectRatio="false" viewBox="0 0 500 800">
  <polygon points="20,20 490,20 490,780 20,780" stroke="black" fill="transparent" stroke-width="2" id="v-b" stroke-dasharray="3000"/>
  <animate xlink:href="#v-b" attributeName="stroke-dashoffset" from="3000" to="0" dur="2s" begin="indefinite" fill="freeze" id="vbanim"/>
  <animate xlink:href="#v-b" attributeName="fill" from="transparent" to="rgba(130,130,130,0.6)" dur="1s" begin="vbanim.end" fill="freeze"/>
</svg>

I need the stroke-dashoffset and the fill animation to occur only after the button has been clicked and prior that, the SVG shouldn't be visible at all. Thanks for the help.

like image 484
Sidzler Avatar asked Jan 18 '18 08:01

Sidzler


People also ask

How do you trigger an onclick animation?

On the Animations tab, in the Advanced Animation group, click Animation Pane. In the Animation Pane, select the animation that you want to trigger. In the Advanced Animation group, click Trigger, point to On Click of, and select the object that you want to trigger the animation.

Can you animate SVG with CSS?

Adding classes to the SVG allows CSS to select the individual shapes within the image. This means you can animate different shapes of the image at different times, creating a more complex effect.


1 Answers

The preferred working solution using beginElement() to indefinitely start the animation when an event is generated.

Note- beginElement() function works only with native javascript/ not Jquery.

$('button').click(function() {
  document.getElementById('vbanim').beginElement();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click to draw</button>
<svg width="100px" height="100px" preserveAspectRatio="false" viewBox="0 0 500 800">
  <polygon points="20,20 490,20 490,780 20,780" stroke="black" fill="transparent" stroke-width="0" id="v-b" stroke-dasharray="3000" />
  <animate class="anim1" xlink:href="#v-b" attributeName="stroke-dashoffset" from="3000" to="0" dur="2s" begin="indefinite" fill="freeze" id="vbanim"/>
  <animate class="anim2" xlink:href="#v-b" attributeName="fill" begin="vbanim.end" from="transparent" to="rgba(130,130,130,0.6)" dur="1s"  fill="freeze"/>
  <animate class="anim3" xlink:href="#v-b" attributeName="stroke-width" from="0" to="10" dur="0.2s" begin="vbanim.begin" fill="freeze" id=""/>
</svg>
like image 128
Sidzler Avatar answered Oct 27 '22 15:10

Sidzler