I'm trying to animate the attributes of various SVG shapes using JavaScript and CSS transitions.
For example:
HTML:
<svg width="400" height="400">
<circle id="circle" cx="200" cy="200" r="15" stroke="none" fill="blue" />
<rect id="rect" x="100" y="100" height="30" width="30" stroke="none" fill="red" />
</svg>
<button id="button">Animate</button>
JavaScript:
document.getElementById("button").addEventListener("click", function () {
var circle = document.getElementById("circle");
var cx = 50 + Math.round(Math.random() * 300);
var cy = 50 + Math.round(Math.random() * 300);
// using 'setAttribute'
circle.setAttribute("cx", cx);
circle.setAttribute("cy", cy);
var rect = document.getElementById("rect");
var x = 50 + Math.round(Math.random() * 300);
var y = 50 + Math.round(Math.random() * 300);
// using 'setAttributeNS'
rect.setAttributeNS(null, "x", x);
rect.setAttributeNS(null, "y", y);
}, false);
CSS:
circle, rect {
-webkit-transition: all 0.7s ease-in-out;
-moz-transition: all 0.7s ease-in-out;
transition: all 0.7s ease-in-out;
}
Here's a complete JSFiddle: http://jsfiddle.net/kkhvzyjq/
In Chrome, this works beautifully. However, in Safari and Firefox, while the new attributes are applied (the shapes move), there's no transition/animation.
Is there a way to do this that works in these browsers?
animation
elements to acircle
, for example, and used JavaScript to modify thefrom
andto
attributes - it didn't work. (I.e., the animation didn't recommence each time I changed the attributes). I also tried removing old animation elements and adding new ones with newfrom
andto
attributes, but that didn't work either. In other words, I could only get SMIL animation to work when it's added at author-time, not modified dynamically during runtime. – mattstuehler Jun 23 '15 at 16:30