Animating SVG images with JavaScript
Besides animating SVG images with pure CSS it is also possible to embed JavaScript code within your SVG. With JS you can use a wider range of effects and features which are not possible by just using CSS alone. You can for example dynamically populate the image with elements by simply programatically generating them. You can introduce an randomness, essentially you have the full range of JavaScript capabilities at your disposal. But there are some distinct drawbacks to that approach. Many display programs that render SVG files simply ignore JavaScript. In my opinion, using JS is for mostly suitable when your intention is, to display the image in a browser.
But browsers themeselves as well impose restriction to embedded JavaScript code for security reasons.
The JS code within the SVG file will not execute in modern browsers when you embed the file via
or <img
>
tags, but only when the image exists in its own sandboxed context. In practice you have multiple means to still run the code<object
>
- opening the SVG in a new window
- placing the JS code in the document that calls the image
- embedding it via an
tag<iframe
>- this provides a sandboxed environment for the file and allows the embedded JS code to be executed.
- making it an inline SVG file within the HTML document itself
Embedded with an <img
> tag
Resulting in a static image, without the code generating the elements and applying the styles for the animation
Embedded with an <iframe
> tag
Now the elements are generating and moving. But the <iframe
> tag does not allow you to manipulate the image itself. You can't apply a stylesheet to it or scale the size.