gsap.to()
creates an animation (technically a Tween
instance) to whatever values you define in the vars object. For example:
This is a static method for creating a Tween instance that animates to the specified destination values (from the current values). This static method can be more intuitive for some developers and shields them from potential garbage collection issues that could arise when assigning a tween instance to a persistent variable. The following lines of code produce identical results:
//returns a tween
var tween = gsap.to(obj, {duration: 1, x: 100});
//returns a timeline
var timeline = gsap.to(obj, {duration: 1, x: 100})
.to(obj2, {duration: 0.2, rotation: 90});
gsap.to(obj, {duration: 1, x: 100});
var myTween = gsap.to(obj, {duration: 1, x: 100});
Both lines above will tween the x
property of the object
to a value of 100 over the course of 1 second. They each use a slightly different syntax, both of which are valid. If you don’t need to store a reference of the tween, just use the static gsap.to( )
call.
Since the target parameter can also be an array of objects, the following code will tween the x property of obj1, obj2, and obj3 to a value of 100 simultaneously:
gsap.to([obj1, obj2, obj3], {duration: 1, x: 100});
Even though 3 objects are animating, there is still only one tween created. In order to stagger or offset the start times of each object animating, just use the stagger
property:
gsap.to([obj1, obj2, obj3], {
duration: 1,
x: 100,
stagger: 0.5 //simple stagger of 0.5 seconds
});
//or get advanced:
gsap.to([obj1, obj2, obj3], {
duration: 1,
x: 100,
stagger: {
amount: 2,
from: "center",
grid: "auto",
onComplete: myFunction //define callbacks inside the stagger to make them apply to each sub-tween
}
});
An array of keyframes can also be used. For example,
gsap.to(".class", [
{x: 100, duration: 1},
{y: 200, duration: 1, delay: 0.5}, //create a 0.5 second gap
{rotation: 360, duration: 2, delay: -0.25} //overlap by 0.25 seconds
]);
For simple sequencing, you can use the delay
special property (like gsap.to(obj, {duration: 1, x: 100, delay: 0.5})
), but it is highly recommended that you consider using a gsap.timeline
for all but the simplest sequencing tasks. It allows you to append tweens one-after-the-other and then control the entire sequence as a whole. You can even have the tweens overlap as much as you want.