Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controlling SVG's SMIL with JavaScript

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!

like image 584
ArtPulse Avatar asked May 22 '12 14:05

ArtPulse


1 Answers

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.

like image 155
Robert Longson Avatar answered Oct 19 '22 03:10

Robert Longson