admin管理员组文章数量:1389897
I have a scroll-based animation in a React component using Framer Motion. It animates a set of cards (motion.div
) as the user scrolls down. However, the issue I'm facing is that on certain desktop resolutions, the animation doesn't complete properly because there's not enough height to scroll fully.
Here's the working demo with code: .jsx
I'm currently using hardcoded breakpoints (THRESHOLDS.SNAP, THRESHOLDS.MOVE_UP, etc.) to trigger different animation states, but this approach isn't flexible enough for all screen sizes.
import { useMemo } from "react";
import { motion } from "framer-motion";
import { useSmoothScroll } from "./useSmoothScroll";
import { useViewport } from "./useViewport";
// Define the card data and animation constants
const CARDS = ["Consult.ai", "Translate.ai", "Read.ai", "Flip.ai"];
const THRESHOLDS = { MOVE_UP: 90, MOVE_LEFT: 250, SNAP: 330 };
const GAPS = { DESKTOP: 260, MOBILE: 180 };
const MOVEMENTS = {
MOVE_UP: CARDS.map((_, index) => -100 * (CARDS.length - 1 - index)),
MOVE_LEFT: [-100, -330, -550, -760],
MOVE_BOTTOM: [300, 200, 100, 0],
};
const SIZES = {
INITIAL: { width: "10rem", height: "16rem" },
EXPANDED: { width: "30rem", height: "45rem" },
};
export default function CardTransition() {
const scrollY = useSmoothScroll();
const { width: viewportWidth } = useViewport();
const animatedCards = useMemo(() => {
const gap = viewportWidth < 768 ? GAPS.MOBILE : GAPS.DESKTOP;
return CARDS.map((_, index) => {
const initialX = (index - (CARDS.length - 1) / 2) * gap;
const moveUp =
scrollY > THRESHOLDS.MOVE_UP ? MOVEMENTS.MOVE_UP[index] : 0;
let moveLeft =
scrollY > THRESHOLDS.MOVE_LEFT ? MOVEMENTS.MOVE_LEFT[index] : 0;
if (viewportWidth < 768) moveLeft /= 1.5;
const animate =
scrollY > THRESHOLDS.SNAP
? {
left: 0,
width: SIZES.EXPANDED.width,
height: SIZES.EXPANDED.height,
bottom: MOVEMENTS.MOVE_BOTTOM[index],
}
: { x: initialX + moveLeft, y: moveUp };
return { key: index, initialX, animate };
});
}, [scrollY, viewportWidth]);
return (
<div className="min-h-[140vh] w-full relative flex items-center justify-center bg-gray-100">
<div className="w-full h-full flex items-center justify-center">
{animatedCards.map(({ key, initialX, animate }) => (
<motion.div
key={key}
className="absolute bottom-60 w-40 h-64 bg-green-800 text-white flex items-center justify-center text-lg font-semibold shadow-lg rounded-xl"
style={{ zIndex: CARDS.length - key }}
initial={
scrollY > THRESHOLDS.SNAP ? { x: 0, y: 0 } : { x: initialX, y: 0 }
}
animate={animate}
transition={{ type: "spring", stiffness: 60, damping: 15 }}
>
{CARDS[key]}
</motion.div>
))}
</div>
</div>
);
}
版权声明:本文标题:reactjs - How to Make a Scroll-Based Framer Motion Animation Work Across All Desktop Resolutions? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744565279a2613006.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论