Controlling SVG SMIL with JavaScript

Say I have this insect SVG. Unless otherwise possible, I want to insert it in the tags <img />or <object />.

Insect.svg now has two animations: one for walking and one for flying.

I would like to start / stop these animations, individually and from the JavaScript HTML code (or else call the built-in SVG JS function to β€œwalk” or β€œfly” from the JavaScript HTML code).

So, in the end, if during the gameplay I want my insect to fly, I can just tell him about it with JS and tell him to stop when he should no longer fly. The same thing with walking.

Is there any way to do this? I have been to Googling for the last hour and have not made any real results. I do not need IE support if this is a problem.

Thank you for your time!

+5
source share
1 answer

You can try using SMIL Animation Hyperlinking. You put the id of the animation you want to run after # in the URL. See, for example, http://www.w3.org/Graphics/SVG/Test/20061213/htmlObjectHarness/full-animate-elem-21-t.html - the URL changes when you click the mouse and starts the animation.

Otherwise, if you want to run the animation using JavaScript, it will look something like this ...

var svgDocument = document.getElementById("objectId>").getSVGDocument();
svgDocument.getElementById('<animationElementId>').beginElement();

But this will not work with the element <img>as it does not allow creating scripts.

+2
source

All Articles