I'd like to use CSS transitions to animate the position of SVG elements.
However - it looks like this works on some SVG elements (e.g., rect), but not on others (e.g. text):
document.querySelector("button").onclick = function() {
var x = Math.random() * 450;
document.querySelector("rect").setAttributeNS(null, "x", x);
document.querySelector("text").setAttributeNS(null, "x", x);
}
rect {
transition: all 700ms ease-in-out;
}
text {
transition: all 700ms ease-in-out;
}
<svg width="500" height="100">
<rect x="100" y="10" width="30" height="30" fill="blue" stroke="none"/>
<text x="100" y="80" fill="red" stroke="none">Hello</text>
</svg>
<br>
<button>animate</button>
Am I doing something wrong? Is there a better way to do this? (ideally, without using JavaScript or a library like GreenSock).
You can use translation instead:
document.querySelector("button").onclick = function() {
var x = Math.random() * 250;
document.querySelector("rect").setAttributeNS(null, "transform","translate("+x+")");
document.querySelector("text").setAttributeNS(null, "transform","translate("+x+")");
}
rect {
transition: all 700ms ease-in-out;
}
text {
transition: all 700ms ease-in-out;
}
<svg width="500" height="100">
<rect x="100" y="10" width="30" height="30" fill="blue" stroke="none"/>
<text x="100" y="80" fill="red" stroke="none">Hello</text>
</svg>
<br>
<button>animate</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With