Skip to content

feat: add scroll-based-velocity-images component #621

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions config/docs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,12 @@ export const docsConfig: DocsConfig = {
items: [],
label: "",
},
{
title: "Scroll Velocity Images",
href: `/docs/components/scroll-based-velocity-images`,
items: [],
label: "New",
},
],
},
{
Expand Down
39 changes: 39 additions & 0 deletions content/docs/components/scroll-based-velocity-images.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
---
title: Scroll Velocity Images
date: 2025-04-05
description: A component that displays images scrolling with velocity that changes based on scroll speed.
author: nilesh0700
published: true
---

<ComponentPreview name="scroll-based-velocity-images-demo" />

## Installation

<Tabs defaultValue="cli">
<TabsList>
<TabsTrigger value="cli">CLI</TabsTrigger>
<TabsTrigger value="manual">Manual</TabsTrigger>
</TabsList>
<TabsContent value="cli">

```bash
npx shadcn@latest add "https://magicui.design/r/scroll-based-velocity-images"
```

</TabsContent>
<TabsContent value="manual">
<Steps>
<Step>Copy and paste the following code into your project.</Step>
<ComponentSource name="scroll-based-velocity-images" />
</Steps>
</TabsContent>
</Tabs>

## Props

| Prop | Type | Default | Description |
| --------------- | ------------------------------------------------------------------ | ------- | --------------------------------------------------------------- |
| defaultVelocity | `number` | `5` | The base speed of animation in pixels per second |
| numRows | `number` | `2` | The number of rows of images to display |
| images | `Array<{src: string, alt: string, width: number, height: number}>` | `[]` | Array of image objects with source, alt text, width, and height |
29 changes: 29 additions & 0 deletions registry.json
Original file line number Diff line number Diff line change
Expand Up @@ -1324,6 +1324,19 @@
}
]
},
{
"name": "scroll-based-velocity-images",
"type": "registry:ui",
"title": "Scroll Images Velocity",
"description": "A component that displays a list of images with a scroll based velocity effect.",
"files": [
{
"path": "registry/magicui/scroll-based-velocity-images.tsx",
"type": "registry:ui",
"target": "components/magicui/scroll-based-velocity-images.tsx"
}
]
},
{
"name": "magic-card-demo",
"type": "registry:example",
Expand Down Expand Up @@ -3260,6 +3273,22 @@
}
]
},
{
"name": "scroll-based-velocity-images-demo",
"type": "registry:example",
"title": "Scroll Velocity Images Demo",
"description": "Example showing a list of images with a scroll based velocity effect.",
"registryDependencies": [
"https://magicui.design/r/scroll-based-velocity-images"
],
"files": [
{
"path": "registry/example/scroll-based-velocity-images-demo.tsx",
"type": "registry:example",
"target": "components/scroll-based-velocity-images-demo.tsx"
}
]
},
{
"name": "utils",
"type": "registry:lib",
Expand Down
30 changes: 30 additions & 0 deletions registry/example/scroll-based-velocity-images-demo.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { VelocityScrollImages } from "@/registry/magicui/scroll-based-velocity-images";

export default function ScrollBasedVelocityImagesDemo() {
return (
<VelocityScrollImages
defaultVelocity={5}
numRows={2}
images={[
{
src: "/showcase/aomni.png",
alt: "Image 1",
width: 380,
height: 214,
},
{
src: "/showcase/infisical.png",
alt: "Hero Image 2",
width: 380,
height: 214,
},
{
src: "/showcase/million.png",
alt: "Hero Image 3",
width: 380,
height: 214,
},
]}
/>
);
}
170 changes: 170 additions & 0 deletions registry/magicui/scroll-based-velocity-images.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
"use client";

import {
motion,
useAnimationFrame,
useMotionValue,
useScroll,
useSpring,
useTransform,
useVelocity,
} from "motion/react";
import React, { useEffect, useRef, useState } from "react";
import Image from "next/image";

import { cn } from "@/lib/utils";

interface VelocityScrollImagesProps
extends React.HTMLAttributes<HTMLDivElement> {
defaultVelocity?: number;
className?: string;
numRows?: number;
images: {
src: string;
alt: string;
width: number;
height: number;
}[];
}

interface ParallaxImagesProps extends React.HTMLAttributes<HTMLDivElement> {
images: {
src: string;
alt: string;
width: number;
height: number;
}[];
baseVelocity: number;
containerRef: React.RefObject<HTMLDivElement>;
}

export const wrap = (min: number, max: number, v: number) => {
const rangeSize = max - min;
return ((((v - min) % rangeSize) + rangeSize) % rangeSize) + min;
};

function ParallaxImages({
images,
baseVelocity = 100,
containerRef,
...props
}: ParallaxImagesProps) {
const baseX = useMotionValue(0);
const { scrollY } = useScroll({
container: containerRef,
});
const scrollVelocity = useVelocity(scrollY);
const smoothVelocity = useSpring(scrollVelocity, {
damping: 50,
stiffness: 400,
});

const velocityFactor = useTransform(smoothVelocity, [0, 1000], [0, 5], {
clamp: false,
});

const [repetitions, setRepetitions] = useState(1);
const rowRef = useRef<HTMLDivElement>(null);
const imagesRef = useRef<HTMLDivElement>(null);

useEffect(() => {
const calculateRepetitions = () => {
if (rowRef.current && imagesRef.current) {
const containerWidth = rowRef.current.offsetWidth;
const imagesWidth = imagesRef.current.offsetWidth;
const newRepetitions = Math.ceil(containerWidth / imagesWidth) + 2;
setRepetitions(newRepetitions);
}
};

calculateRepetitions();

window.addEventListener("resize", calculateRepetitions);
return () => window.removeEventListener("resize", calculateRepetitions);
}, [images]);

const x = useTransform(baseX, (v) => `${wrap(-100 / repetitions, 0, v)}%`);

const directionFactor = React.useRef<number>(1);
useAnimationFrame((t, delta) => {
let moveBy = directionFactor.current * baseVelocity * (delta / 1000);

if (velocityFactor.get() < 0) {
directionFactor.current = -1;
} else if (velocityFactor.get() > 0) {
directionFactor.current = 1;
}

moveBy += directionFactor.current * moveBy * velocityFactor.get();

baseX.set(baseX.get() + moveBy);
});

return (
<div ref={rowRef} className="w-full overflow-hidden" {...props}>
<motion.div className="inline-flex" style={{ x }}>
{Array.from({ length: repetitions }).map((_, i) => (
<div
key={i}
ref={i === 0 ? imagesRef : null}
className="flex gap-4 px-2"
>
{images.map((image, imgIndex) => (
<div
key={`${i}-${imgIndex}`}
className="relative h-[214px] w-[380px] shrink-0 overflow-hidden rounded-lg"
>
<Image
src={image.src}
alt={image.alt}
width={image.width}
height={image.height}
className="h-full w-full object-cover"
/>
</div>
))}
</div>
))}
</motion.div>
</div>
);
}

export function VelocityScrollImages({
defaultVelocity = 5,
numRows = 2,
images,
className,
...props
}: VelocityScrollImagesProps) {
const containerRef = useRef<HTMLDivElement>(null);

// Use a fallback animation when there's no scroll
const [hasScrolled, setHasScrolled] = useState(false);

useEffect(() => {
const handleScroll = () => {
setHasScrolled(true);
};

window.addEventListener("scroll", handleScroll, { passive: true });
return () => window.removeEventListener("scroll", handleScroll);
}, []);

return (
<div
ref={containerRef}
className={cn("relative w-full", className)}
{...props}
>
{Array.from({ length: numRows }).map((_, i) => (
<ParallaxImages
key={i}
images={images}
baseVelocity={defaultVelocity * (i % 2 === 0 ? 1 : -1)}
containerRef={containerRef}
/>
))}
</div>
);
}
17 changes: 17 additions & 0 deletions registry/registry-examples.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1696,4 +1696,21 @@ export const examples: Registry["items"] = [
},
],
},
{
name: "scroll-based-velocity-images-demo",
type: "registry:example",
title: "Scroll Velocity Images Demo",
description:
"Example showing a list of images with a scroll based velocity effect.",
registryDependencies: [
"https://magicui.design/r/scroll-based-velocity-images",
],
files: [
{
path: "registry/example/scroll-based-velocity-images-demo.tsx",
type: "registry:example",
target: "components/scroll-based-velocity-images-demo.tsx",
},
],
},
];
14 changes: 14 additions & 0 deletions registry/registry-ui.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1242,4 +1242,18 @@ export const ui: Registry["items"] = [
},
],
},
{
name: "scroll-based-velocity-images",
type: "registry:ui",
title: "Scroll Images Velocity",
description:
"A component that displays a list of images with a scroll based velocity effect.",
files: [
{
path: "registry/magicui/scroll-based-velocity-images.tsx",
type: "registry:ui",
target: "components/magicui/scroll-based-velocity-images.tsx",
},
],
},
];