I have an SVG animation similar to this:
function startAnimation() {
document.querySelector('#anim-width').beginElement();
}
<svg width="100" viewBox="0 0 100 100">
<rect id="box" x="10" y="10" fill="red" width="10" height="10">
<animate
id="anim-width"
attributeName="width"
from="10"
to="80"
dur="1s"
fill="freeze"
begin="click"
/>
<animate
attributeName="height"
from="10"
to="80"
begin="anim-width.end + 0s"
dur="1s"
fill="freeze"
/>
</rect>
</svg>
<br/>
<button onclick="startAnimation()">Start</button>
What I want to achieve is the red box starts from 10 by 10, when clicking the button, the width expands from 10 to 80, then the height expands to 80 after the width animation is done.
It works fine for the first playback, but when clicking the button again the height starts from 80 instead of 10, how do I reset everthing to its intial state and replay the entire animation?
I tried adding document.querySelector('#box').setAttribute('height', '10'); in the startAnimation() function but it doesn't seem to work.
I'm adding an element <set> inside the rect and I'm starting the set element inside the function function startAnimation()
The <set> element ìs a maner of setting the value of an attribute (height in this case), like an animation with duration 0.
function startAnimation() {
document.querySelector("#set").beginElement();
document.querySelector("#anim-width").beginElement();
}
<svg width="100" viewBox="0 0 100 100">
<rect id="box" x="10" y="10" fill="red" width="10" height="10">
<animate id="anim-width" attributeName="width" from="10" to="80" dur="1s" fill="freeze" begin="click" />
<animate id="anim-height" attributeName="height" from="10" to="80" begin="anim-width.end + 0s" dur="1s" fill="freeze" />
<set id="set" attributeName="height" to="10"></set>
</rect>
</svg>
<br />
<button onclick="startAnimation()">Start</button>
Another option is just to have an <animate> element that starts the animation by resetting the height.
document.querySelector("#anim-height").addEventListener("endEvent", enableButton);
function startAnimation() {
document.querySelector("#start-btn").disabled = true;
document.querySelector("#anim-start").beginElement();
}
function enableButton()
{
document.querySelector("#start-btn").disabled = false;
}
<svg width="100" viewBox="0 0 100 100">
<rect id="box" x="10" y="10" fill="red" width="10" height="10">
<animate id="anim-start" attributeName="height" to="10" dur="0.01s" fill="freeze" begin="indefinite" />
<animate id="anim-width" attributeName="width" from="10" to="80" dur="1s" fill="freeze" begin="anim-start.end + 0s" />
<animate id="anim-height" attributeName="height" from="10" to="80" begin="anim-width.end + 0s" dur="1s" fill="freeze" />
</rect>
</svg>
<br />
<button id="start-btn" onclick="startAnimation()">Start</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With