Controlling SVG's SMIL with JavaScript
Asked Answered
M

1

7

Let's say I have this SVG of an insect. Unless it is otherwise impossible this way, I want to insert it as <img /> or <object /> tags.

Now, the insect.svg has two animations: one for walking and other for flying.

I'd like to start/stop these animations, individually, and from the HTML's JavaScript (or otherwise call an embed SVG JS function "walk" or "fly", from the HTML JavaScript).

So, in the end, if during the gameplay I want my insect to fly, I can just inform it to do so with JS, and tell it to stop when it shouldn't fly anymore. Same with walking.

Is there any way to do this? I've been Googling for the past hour and made no real findings. I don't care about IE support if that is an issue.

Thank you for your time!

Meliorate answered 22/5, 2012 at 14:26 Comment(0)
F
4

You could try using SMIL Animation Hyperlinking. You put the id of the animation you want to start after a # on the URL. See http://www.w3.org/Graphics/SVG/Test/20061213/htmlObjectHarness/full-animate-elem-21-t.html for instance - the URL changes when the mouse is clicked and that starts the animation.

Otherwise if you want to start an animation with javascript it would go something like this...

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

But this won't work with an <img> element as that doesn't allow scripting.

Frequency answered 22/5, 2012 at 14:49 Comment(2)
getSVGDocument, sweet. So, just to be clear, the only way to interact with the SVG DOM is embedding the SVG code in HTML, right?Meliorate
Not at all, the answer above assumes you've used <object> as you requested.Frequency

© 2022 - 2024 — McMap. All rights reserved.