How to create an image trail effect with GSAP

SHARE

SIGN UP FOR THE NEWSLETTER

Your subscription could not be saved. Please try again.
Your subscription has been successful.


Code:

Javascript/GSAP

<div class="items"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/gsap.min.js"></script>


<script>
   // Define an array to store image paths
   const imagePaths = [
      "",
      "",
      "",
    //   Add more URLs as needed
    ];

    document.addEventListener("DOMContentLoaded", function () {
      const container = document.querySelector(".items");
      let imageIndex = 0; // Start index from 0
      let animationTimeout = null;
      let currentlyAnimating = false;

      function addNewItem(x, y) {
        const newItem = document.createElement("div");
        newItem.className = "item";
        newItem.style.left = `${x - 75}px`;
        newItem.style.top = `${y - 75}px`;

        const img = document.createElement("img");
        img.src = imagePaths[imageIndex]; // Use image URL from the array
        newItem.appendChild(img);
        imageIndex = (imageIndex + 1) % imagePaths.length; // Update index

        container.appendChild(newItem);
        manageItemLimit();
      }

      function manageItemLimit() {
        while (container.children.length > 20) {
          container.removeChild(container.firstChild);
        }
      }

      function startAnimation() {
        if (currentlyAnimating || container.children.length === 0) return;
        currentlyAnimating = true;
        gsap.to(".item", {
          y: 2500,
          scale: 0.5,
          opacity: 0,
          duration: 0.5,
          stagger: 1,
          onComplete: function () {
            this.targets().forEach((item) => {
              if (item.parentNode) {
                item.parentNode.removeChild(item);
              }
            });
            currentlyAnimating = false;
          },
        });
      }

      container.addEventListener("mousemove", function (event) {
        clearTimeout(animationTimeout);
        addNewItem(event.pageX, event.pageY);
        animationTimeout = setTimeout(startAnimation, 100);
      });
    });
</script>
      

CSS

.items {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 2;
}

.item {
  position: absolute;
  width: 450px;
  height: 600px;
  overflow: hidden;
}

.item img {
  width: 150%;
  height: 250%;
  object-fit: cover;
}     



Video:

SIGN UP FOR THE NEWSLETTER

Your subscription could not be saved. Please try again.
Your subscription has been successful.