Home > Web Front-end > JS Tutorial > Create Beautiful Scroll Animations Using Framer Motion

Create Beautiful Scroll Animations Using Framer Motion

Mary-Kate Olsen
Release: 2024-10-31 19:02:01
Original
751 people have browsed it

Introduction

Scrolling is something we do every day on our screens, but have you ever thought about how scrolling affects user experience? In today's world, scrolling has also become a way to give your users a smooth and satisfying experience. With tools like Framer Motion, developers can turn scrolling into an engaging and visually attractive experience.

Today, we will explore different ways to animate scrolling. We will learn about the types of scroll animations and how they are used. We’ll understand the pattern so that we can add scroll animations to any of our projects or sites.

We will create animations in Next.js using Framer Motion. If you prefer to use any other framework or library, you can use that.

So, without further delay, let’s get started.

Types of Scroll Animations

There are two types of scroll animations:

  1. Scroll-linked animations: Animations that move or change based on how far you’ve scrolled, the element will update continuously as you scroll.

  2. Scroll-triggered animations: A normal animation is triggered when an element enters or leaves the viewport.

Create Beautiful Scroll Animations Using Framer Motion

With Framer motion, you can achieve both. Let’s understand both one by one.

Scroll-linked animations

Scroll-linked animations are animations where the progress or movement of an animation is directly linked up to how far the user has scrolled. In this type of animation, elements change continuously as the user scrolls.

It means if you are at point one then the animation will track you, and it will also be on point one. And, If you scroll and go to point two, the animation will follow you to that point.

Key Features

  • The animation is synchronized with the scroll progress.
  • As you scroll, the animation updates in real time based on how much you've scrolled.
  • These animations can involve moving, scaling, rotating, or changing the appearance of elements, usually using useScroll and useTransform hooks(we’ll learn about these ahead) in Framer Motion.

Scroll-triggered animation

Scroll-triggered animations happen when an element enters or leaves the specific viewport as you scroll. It means the animation starts only when the user scrolls to a specific part of the page.

So, if I am on point one and, I set a scroll-triggered animation for point three then this animation will occur at point three. This means that animation will triggered only when I reach that viewport(in this case it is point three)

To understand this, you can check this video?. Here, you’ll see when that orange element comes in a viewport means it is completely visible on the screen and then, at that time, shows a navbar.

Key Features

  • Triggered by Scroll Position: The animation is activated once a specific scroll position is reached, rather than being continuously synced with the scroll, like scroll-linked animations. This is typically achieved using conditions like whileInView or onEnter.

  • Discrete Animations: Unlike scroll-linked animations, scroll-triggered animations happen at specific moments, like when an element enters or exits the viewport. These could include fade-ins, slide-ins, or other visual effects that occur once as the user scrolls past a certain point.

  • One-Time or Repeatable Animations: Scroll-triggered animations can be set to play only once when the element first comes into view, or they can repeat whenever the element enters the viewport again, depending on the use case.

  <motion.div
    initial="hidden"
    whileInView="visible"
    viewport={{ once: true }}  // animation will occur only once
  />

Copy after login
Copy after login
Copy after login
Copy after login

What’s Next?

Now we understand these two types of scroll animations and their differences, let's start understanding the patterns used in creating these animations. This will allow you to add scroll animations to any of your projects.

First, we'll set up a project to understand this practically, and then we will create both types of animations.

Project Setup

Let's start by setting up our Next.js project with all the necessary dependencies. I am going to use StalkBlitz for this project but you can use VSCode too. Although all the steps I’ll tell you from the VSCode perspective so you can follow the steps.

  1. Create a new Next.js project with TypeScript:

    npx create-next-app@latest
    
    Copy after login
    Copy after login
    Copy after login

    On installation, you'll see the following prompts:

       What is your project named? my-app
       Would you like to use TypeScript? No / Yes
       Would you like to use ESLint? No / Yes
       Would you like to use Tailwind CSS? No / Yes
       Would you like to use `src/` directory? No / Yes
       Would you like to use App Router? (recommended) No / Yes
       Would you like to customize the default import alias (@/*)? No / Yes
       What import alias would you like configured? @/*
    
    
    Copy after login
    Copy after login
    Copy after login
  2. Install Framer Motion

      npm install framer-motion
    
    Copy after login
    Copy after login
    Copy after login
  3. Clean up default files.
    Remove the default code in app/page.tsx. We’ll start from scratch to focus on our scroll animations. The file should look like this.

        'use client';
    
          export default function Home() {
    
              return (
               <div>
    
               </div>
             );
           }
    
    
    Copy after login
    Copy after login
  4. Start the Development Server

      <motion.div
        initial="hidden"
        whileInView="visible"
        viewport={{ once: true }}  // animation will occur only once
      />
    
    
    Copy after login
    Copy after login
    Copy after login
    Copy after login

Create Scroll Animation

Now that our project is set up, we can create both types of scroll animations one by one. You can start writing code directly in app/page.tsx file or create a separate component and import all of them in app/page.tsx file.

Creating Scroll-Linked Animation

There are several examples of scroll-linked animation:

  • Scroll Progress Bar: A circular or linear progress bar that fills up as the user scrolls down the page.

  • Parallax Scrolling: Background images or elements move at different speeds relative to the foreground, creating a depth effect as you scroll.

  • Fade-In Elements: Content fades into view as the user scrolls.

  • Scale Transformations: Elements gradually increase or decrease in size based on scroll progress. etc.

Let’s create some animations. While creating any scroll-linked animation you'll frequently use these methods and hooks from framer motion.

  1. Scroll Progress Detection (useScroll): Tracks the user's scroll position, typically returning a value from 0 to 1 that represents the progress down the page.

    npx create-next-app@latest
    
    Copy after login
    Copy after login
    Copy after login
  2. Transforming Scroll Data (useTransform): Maps the scroll position to specific animation properties like opacity, scale, or position. Use this to trigger animations like fading, moving, rotating, scaling, or color changes during the scroll.

       What is your project named? my-app
       Would you like to use TypeScript? No / Yes
       Would you like to use ESLint? No / Yes
       Would you like to use Tailwind CSS? No / Yes
       Would you like to use `src/` directory? No / Yes
       Would you like to use App Router? (recommended) No / Yes
       Would you like to customize the default import alias (@/*)? No / Yes
       What import alias would you like configured? @/*
    
    
    Copy after login
    Copy after login
    Copy after login
  3. Animating with Motion Elements: Wrap target elements with motion.div (or any motion component) and link the animation to the scroll progress.

      npm install framer-motion
    
    Copy after login
    Copy after login
    Copy after login
  4. Transitions: Apply smooth transitions to make animations feel fluid and natural.

        'use client';
    
          export default function Home() {
    
              return (
               <div>
    
               </div>
             );
           }
    
    
    Copy after login
    Copy after login
  5. Initial and Final States: Use initial, animate, or style props to define how elements look initially, and control their final states with useTransform or animations linked to scrollYProgress.

        npm run dev
    
    Copy after login

Scroll Progress Bar

We'll start by creating a scroll progress bar. To do this, open your text editor, create a new component, and begin writing code in it.

   const { scrollYProgress } = useScroll();
Copy after login

Here we used:

  • useScroll: Provides the scroll position as a normalized value between 0 and 1.

  • useTransform: Maps the scroll progress to the specific value ranges we need, whether it's for the stroke dasharray of the progress circle or any other transformation we want to apply.

  • motion Components: We use Framer Motion's motion.circle to animate the stroke length in real-time based on scrolling.

Dynamic Scaling Text Animation

In this example, we will create a scroll-linked dynamic scaling effect for a text element using Framer Motion.

  1. Tracking Scroll Progress: Similar to the progress bar, we use useScroll() to get the current scroll progress of the page. The scrollYProgress value ranges from 0 at the top to 1 when fully scrolled.

      <motion.div
        initial="hidden"
        whileInView="visible"
        viewport={{ once: true }}  // animation will occur only once
      />
    
    
    Copy after login
    Copy after login
    Copy after login
    Copy after login
  2. Transforming the Scroll Value to Control Scale: We use useTransform() to convert the scroll progress into a scale value that changes dynamically as the user scrolls. In this case, we map the scrollYProgress from [0, 0.5, 1] to scale values [1, 2, 1], it means the text will grow from its original size, double in size at the middle of the scroll, and shrink back as you reach the bottom.

    npx create-next-app@latest
    
    Copy after login
    Copy after login
    Copy after login
  3. Animating the Text Element: Inside the motion.h1 component, we will use the scaleValue to the style property to smoothly animate the text scaling effect based on the scroll position. The text will "grow" and "shrink" as the user scrolls.

       What is your project named? my-app
       Would you like to use TypeScript? No / Yes
       Would you like to use ESLint? No / Yes
       Would you like to use Tailwind CSS? No / Yes
       Would you like to use `src/` directory? No / Yes
       Would you like to use App Router? (recommended) No / Yes
       Would you like to customize the default import alias (@/*)? No / Yes
       What import alias would you like configured? @/*
    
    
    Copy after login
    Copy after login
    Copy after login
  4. Styling the Section: The text is centered within a full-screen section that has a background gradient to add visual appeal. The background creates a smooth gradient from purple to indigo, making the dynamic text stand out more.

      npm install framer-motion
    
    Copy after login
    Copy after login
    Copy after login

Concepts Used:

  • useScroll: We use this hook again to track the page’s scroll progress, which serves as the trigger for the animation.

  • useTransform: Here, we map the scroll progress to scale values, making the text grow or shrink smoothly during the scroll event.

  • motion Components: The motion.h1 the component is animated in real-time, with the scale dynamically adjusted as the scroll value changes.

We again used the same concepts. useScroll useTransform and motion. So, this is the part of scroll-linked. Now let’s create some scroll-triggered animations.

Creating Scroll-Triggered Animation

Scroll-triggered animation doesn't stick to work with a few examples. You can link scroll animation to specific components of the page. For example, I have a landing page with two elements and a div containing some text. Currently, there are no animations on the page, but I want to add animations that activate when the viewport comes into view.

Create Beautiful Scroll Animations Using Framer Motion

For this, we will use scroll-triggered animations. As we learned earlier, scroll-triggered animations occur when a particular viewport comes into view. So, let’s add Framer Motion elements to this code.

  <motion.div
    initial="hidden"
    whileInView="visible"
    viewport={{ once: true }}  // animation will occur only once
  />

Copy after login
Copy after login
Copy after login
Copy after login
  1. We import motion from framer-motion

  2. The entire component is wrapped in a section element, it has some basic styling.

  3. The which is the first motion div. It contains the main content (a heading and paragraph). It uses initial and whileInView to create a scroll-triggered animation:

    initial={{ opacity: 0, y: 50 }}: Initially, the box is invisible (opacity: 0) and positioned 50 pixels down (y: 50).
    whileInView={{ opacity: 1, y: 0 }}: When the user scrolls it into view, it becomes fully visible (opacity: 1) and moves to its normal position (y: 0).
    transition={{ duration: 0.8, ease: 'easeOut' }}: The transition takes 0.8 seconds and eases out smoothly.

    The content inside is styled with Tailwind classes, giving it padding, a background with 90% opacity, shadow, rounded corners, and a max width.

  4. After that, we have a second motion div (Top-to-Bottom Animated Text). This animates some text that moves down from the top of the screen:

    initial={{ y: -100, opacity: 0 }}: The text starts 100 pixels above its normal position and is invisible.
    whileInView={{ y: 0, opacity: 1 }}: When it comes into view, it moves to its normal position and becomes fully visible.
    transition={{ delay: 0.5, duration: 0.8 }}: There's a 0.5-second delay before the animation starts, giving a staggered effect.

The final output will look like this.

Conclusion

That’s it for today’s blog. We cover 2 types of animations with some methods used while creating these animations like: useScroll useTransition whileInView initial and final states and things like that.

All the code with more animation samples I have added in my StalkBliz project. You can check it out here and view more sample scroll animations with code. If you want to explore more props, methods, and examples of scroll animations, you can check out Framer Motion’s scroll docs here.

Thanks for reading this blog. If you learned something from it, please like and share it with your friends and community. I write blogs and share content on JavaScript, TypeScript, Open Source, and other web development-related topics. Feel free to follow me on my socials. I'll see you in the next one. Thank You :)

  • Twitter
  • LinkedIn
  • GitHub

The above is the detailed content of Create Beautiful Scroll Animations Using Framer Motion. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template