create the animation of many dom elements which are launched from the bottom to top and fall in parabolic motion with the gsap library in javascript

To create an animation of many DOM elements falling in a parabolic motion using the GSAP library, first, you need to select each element and set its initial position, then apply a timeline to each one of them.

index.tsx
const elements = document.querySelectorAll('.element');
const tl = new TimelineMax();
const gravity = 1;

// set initial positions of elements
elements.forEach(element => {
  tl.set(element, {
    x: Math.random() * window.innerWidth, // random horizontal position
    y: window.innerHeight, // bottom of the screen
    scale: Math.random() * 0.5 + 0.5 // random scale between 0.5 and 1
  });
});

// animate each element individually
elements.forEach(element => {
  const x = parseInt(element.style.x);
  const y = parseInt(element.style.y);
  const vy = -1 * Math.sqrt(2 * gravity * (window.innerHeight - y)); // initial vertical velocity

  tl.to(element, {
    duration: 2,
    x: x + Math.random() * 200 - 100, // horizontal position variation
    y: window.innerHeight - Math.random() * 100, // final vertical position variation
    ease: Power1.easeOut
  });
  
  tl.to(element, {
    duration: 1,
    physics2D: {
      velocity: { y: vy },
      gravity: gravity
    },
    ease: Power1.easeIn
  });
});
1013 chars
36 lines

In the code above, we first select all the elements with the class .element and set their initial position with a random horizontal position, the bottom of the screen as the initial vertical position, and a random scale between 0.5 and 1.

Then, we loop through each element and apply two timeline animations to them. The first animation moves the element to a random horizontal position and a random final vertical position, with an ease-out easing. The second animation applies physics to the element, with an initial vertical velocity based on the initial height, and a gravity constant of 1. The easing function applied to this animation is ease-in, giving the parabolic motion effect.

By using the physics2D property of GSAP's timeline, we can apply physics-based animations with ease. The velocity object specifies the initial velocity of the element, and the gravity property is the acceleration applied to the element. In this example, we used a constant gravity acceleration, but you can modify it to fit your needs.

gistlibby LogSnag