Logo

dev-resources.site

for different kinds of informations.

Pinning Images with GSAP: A Smooth Scrolling Animation in Next.js

Published at
10/14/2024
Categories
webdev
gsap
frontend
animation
Author
moostakimahamed
Categories
4 categories in total
webdev
open
gsap
open
frontend
open
animation
open
Author
15 person written this
moostakimahamed
open
Pinning Images with GSAP: A Smooth Scrolling Animation in Next.js

In this article, weโ€™ll explore how to create smooth scrolling animations by pinning images using GSAP (GreenSock Animation Platform) and its ScrollTrigger plugin. This technique enhances user experience by creating dynamic effects as users scroll through your content. Weโ€™ll use Next.js and Tailwind CSS for styling, ensuring a modern look for our project.

Table of Contents

  • Demo
  • Installation
  • Implementation
  • Conclusion

Demo

Before jumping to the explanation check out the live demo of our pinning images animation on CodeSandbox or Loom

Installation

To get started, make sure you have a Next.js application set up. (Follow Next.js Installation Documentation: https://nextjs.org/docs/getting-started/installation)

Next, Tailwind CSS: (Follow tailwind Installation Documentation/Install with next js)

Next, install the necessary packages for GSAP:
npm install gsap @gsap/react

Implementation

Now, letโ€™s create the ScrollAnimation component that will handle our pinning images animation. Hereโ€™s the complete code:

"use client";
import { useRef } from "react";
import { gsap } from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";
import { useGSAP } from "@gsap/react";

gsap.registerPlugin(ScrollTrigger); // Register Gsap Scroll Trigger Plugin

// I used freepik images link for this purpose
const imageUrls = [
  "https://img.freepik.com/free-photo/wide-angle-shot-single-tree-growing-clouded-sky-sunset-surrounded-by-grass_181624-22807.jpg?ga=GA1.1.2030075610.1697991259&semt=ais_hybrid-rr-similar",
  "https://img.freepik.com/free-photo/cascade-boat-clean-china-natural-rural_1417-1356.jpg?ga=GA1.1.2030075610.1697991259&semt=ais_hybrid-rr-similar",
  "https://img.freepik.com/free-photo/group-elephants-big-green-tree-wilderness_181624-16897.jpg?ga=GA1.1.2030075610.1697991259&semt=ais_hybrid-rr-similar",
  "https://img.freepik.com/premium-photo/blazing-sun-vast-savanna_1272857-120118.jpg?ga=GA1.1.2030075610.1697991259&semt=ais_hybrid-rr-similar",
  "https://img.freepik.com/free-photo/beautiful-shot-tree-savanna-plains-with-blue-sky_181624-21992.jpg?ga=GA1.1.2030075610.1697991259&semt=ais_hybrid-rr-similar",
];

const ScrollAnimation = () => {
  const imagesRef = useRef<any[]>([]); // Fix to store multiple refs

  useGSAP(() => {
    // Convert the current array of image references to a proper array for GSAP manipulation
    const images = gsap.utils.toArray(imagesRef.current);

    // Iterate over each image element
    images.forEach((panel: any, i: number) => {
      let scale = 1;

      // If the current image is not the last one, adjust the scale based on its index
      if (i !== images.length - 1) {
        scale = 0.9 + 0.025 * i; // Create a slight scaling effect for images based on their index
      }

      gsap.to(panel, {
        scale: scale,
        transformOrigin: "top center", // Specify the point from which the scaling transformation occurs
        ease: "none",

        // Configure the ScrollTrigger plugin for scroll-based animations
        scrollTrigger: {
          trigger: panel, // Set the current image as the trigger for the ScrollTrigger

          // Define when the animation should start based on the position of the trigger
          start: "top " + (70 + 40 * i), // Start the animation when the top of the panel is 70px down plus an offset based on index
          end: "bottom +=650px", // Define when the animation should end (bottom of the panel + 650px)
          endTrigger: ".end", // Specify the end trigger element
          pin: true, // Pin the current panel/image in place while it is being triggered
          pinSpacing: false, // Disable additional spacing around pinned elements
          scrub: true, // Enable scrub for smooth animation with scrolling
        },
      });
    });
  }, []);

  return (
    <div className="flex flex-col gap-12 mx-auto max-w-2xl py-12">
      {imageUrls.map((image, index) => (
        <div
          key={index}
          ref={(el) => (imagesRef.current[index] = el)}
          className=""
        >
          <img
            src={image}
            alt={`Image ${index + 1}`}
            className="w-full h-auto object-cover rounded-lg shadow-lg"
          />
        </div>
      ))}
      <div className="end"></div>
    </div>
  );
};

export default ScrollAnimation;
Enter fullscreen mode Exit fullscreen mode

Understanding the Code

Image References: We create an array of references using useRef to manipulate our image elements directly.
GSAP Animations: Inside the useEffect, we loop through each image and set a scale based on its index. This creates a dynamic scaling effect as the user scrolls.
ScrollTrigger Configuration: We configure ScrollTrigger for each image, specifying when the animation starts and ends, pinning the images in place while scrolling.

Using the Component

To include the ScrollAnimation component in your Next.js application, import it into your main application file (e.g., page.tsx):

import ScrollAnimation from "./ScrollAnimation";

export default function Home() {
  return (
    <main>
      <div className="h-screen w-full flex items-center justify-center bg-[#66545e]">
        <h1 className="text-2xl font-bold">Scroll Down To See The Magic</h1>
      </div>
      {/* The ScrollAnimation Component */}
      <ScrollAnimation />
      <div className="bg-[#aa6f73] h-screen w-full flex items-center justify-center">
        <h1 className="text-2xl font-bold">Pinning Image Animation End</h1>
      </div>
    </main>
  );
}
Enter fullscreen mode Exit fullscreen mode

Now run the application and boom. ๐Ÿ’ฅ ๐Ÿ’ฅ

Here is the sandbox link again: CodeSandbox

Conclusion

You now know how to pin images and create smooth scrolling animations using GSAP and ScrollTrigger in a Next.js application! This technique can greatly enhance the visual appeal of your site. Feel free to customize the images and scaling effects to match your projectโ€™s style.

If you found this article helpful, please share it on social media and leave a comment below. Happy coding! ๐Ÿ’ป๐Ÿ˜ƒ

gsap Article's
30 articles in total
Favicon
How to improve the Frontend part of the project using one button as an example :))))
Favicon
Reflections on My Coding Journey: Lessons from Recent Weeks
Favicon
Circle Cursor Js #GSAP
Favicon
"Day 7 with GSAP: Interactive Scrolling Animation with Rotating Arrows"
Favicon
GSAP ScrollTrigger animation for Upwork Client Demo
Favicon
Day 6: Text Animation with GSAP โ€“ A Split Letter Magic! ๐ŸŽจโœจ
Favicon
๐Ÿš€ Day 5: Creating a Hamburger Menu with GSAP
Favicon
Day 4: Enhancing UX with a Custom Cursor Using GSAP ๐Ÿš€๐ŸŽจ
Favicon
"Unlocking the Power of GSAP for Stunning Web Animations" ๐ŸŽจโœจ
Favicon
Preloader Animation #GSAP
Favicon
GSAP: GreenSock Animation Platform ๐Ÿš€
Favicon
Animated Carousel
Favicon
๐Ÿš€ ๐—ง๐—ต๐—ฒ๐—ฅ๐—ฒ๐—ฎ๐—น๐—›๐—ผ๐˜๐—ฒ๐—น๐˜€ ๐ŸŒŸ
Favicon
Clip-Path Circle Reveal Animation With Mouse Movement
Favicon
Getting started with Gsap!
Favicon
Todayโ€™s new knowledge #7(GSAP)
Favicon
Image Reveal Animation with HTML, CSS, and GSAP
Favicon
Easy React Animation with GSAP
Favicon
MoonAlert A CSS Animated Moon Notification Box
Favicon
Creating a Mesmerizing Moonlit Night Sky Animation with CSS
Favicon
๐Ÿš€ Motion Scape With GSAP
Favicon
Pinning Images with GSAP: A Smooth Scrolling Animation in Next.js
Favicon
Learning GSAP with a Day-to-Night Scroll Animation ๐ŸŒž๐ŸŒœ
Favicon
From Static to Stunning: Animate with GSAP
Favicon
Blurry Card with Parallax Effect ๐Ÿ’ณ
Favicon
Fun Animation using GSAP
Favicon
Future Bank Fintech Green: The Intersection of Finance and Sustainabilit
Favicon
Framer ground.
Favicon
Parallax image scroll speed with Nuxt 3 and GSAP ๐Ÿ›ฃ๏ธโœจ
Favicon
Creating Interactive Hover Effects with GSAP and SplitType

Featured ones: