Parallax scrolling effects can add extra specie to your web applications, creating an engaging and interactive user experience. In this guide, we'll explore how to implement a smooth image pan effect that responds to user scrolling using Framer Motion and React.
First, ensure you have the necessary packages installed:
npm install framer-motion
import {useRef} from "react";
import { motion, useScroll, useTransform } from "framer-motion";
const ImagePan = ({ src }) => {
const img1Ref = useRef(null);
const { scrollYProgress } = useScroll({
target: img1Ref,
offset: ["start end", "end start"],
});
const position = useTransform(
scrollYProgress,
[0.15, 0.5, 1],
["50% 0%", "50% 50%", "50% 100%"]
);
return (
<motion.img
ref={img1Ref}
src={src}
className="w-full h-full object-cover"
style={{ objectPosition: position }}
alt="this is a simple image"
/>
);
};
export default ImagePan;
The heart of our parallax effect lies in tracking the scroll position relative to our image. Framer Motion's useScroll
hook makes this surprisingly simple:
const { scrollYProgress } = useScroll({
target: img1Ref,
offset: ["start end", "end start"],
});
This setup creates a value that ranges from 0 to 1 as the image moves through the viewport. The offset configuration tells our component to track the entire journey of the image from when it enters the viewport until it leaves.
This tracks the scroll progress relative to the image offset
defines when the animation starts and ends:
"start end"
: When the top of the image meets the bottom of the viewport"end start"
: When the bottom of the image meets the top of the viewportThe real magic happens in the transformation setup:
const position = useTransform(
scrollYProgress,
[0.15, 0.5, 1],
["50% 0%", "50% 50%", "50% 100%"]
);
This configuration creates three key points in our animation:
0.15
), image position is 50% 0%
(centered horizontally, top vertically)50% 50%
(centered both ways)50% 100%
(centered horizontally, bottom vertically)The result is a smooth, continuous motion that follows the user's scroll position.
Implementing the parallax effect in your project is straightforward:
function HomePage() {
return (
<div className="h-screen">
<ImagePan src="/path/to/your/image.jpg" />
</div>
);
}
checkout the results: click here
This parallax image effect is a powerful way to add visual interest to your React applications. By leveraging Framer Motion's powerful animation capabilities, we've created a smooth, scroll-based animation that can enhance your user's experience without compromising performance or complexity.
checkout the results: click here