I am making a small interactive website using scrollmagic and GSAP to animate SVG elements.
However, when animating the y value of an element that had a rotate() transformation, the transformation was removed.
Adding the rotation into the animation did not yield the right result; the rotation was removed from the animation and then animated back in again.
Does anyone know how to preserve the rotation of an SVG element when animating other attributes in GSAP?
example code:
html:
<svg height='300px' width='500px' style='position: absolute;'>
<rect id='rect' width='200' height='75' style='fill:#888;stroke-width:2;stroke:#000' y='0' x='120' transform='rotate(45)' />
</svg>
js:
TweenMax.to('#rect', 1, {x: 100})
fiddle: https://jsfiddle.net/159phcxw/
Short answer: as Tahir suggested, just add this to your JS code:
TweenMax.set("#rect", {rotation:45});
I'd strongly recommend handling all of your transforms through GSAP because it protects you from a bunch of things like browser inconsistencies and loss of precision with rotational values beyond 360 degrees.
GSAP records transform-related values in a special _gsTransform object that's attached to the element itself; this not only boosts performance (no re-parsing of computed style matrix or matrix3d values), but also permits complete independent control of each transform component (rotation, scaleX, scaleY, x, y, skewX, skewY, etc.) regardless of timing offsets or extreme rotational values (impossible with CSS).
In your case, you were mixing transforms - you put the rotation in the attribute and then you asked GSAP to handle the translation. GSAP can actually parse matrix() values you put into the transform attribute or it can also parse any CSS transforms, but you happened to define only a rotate() which is not able to be parsed (I'll spare you the explanation).
Setting any transform-related values through GSAP gets you the best performance and compatibility, plus it's easier to look up current values inside the _gsTransform object later if you need them.