Codrops 원본
Mastering Carousels with GSAP: From Basics to Advanced Animation
섹션 · MIT
갤러리 안에서는 화면을 벗어나거나 움직임을 멈추면 예제도 닫힙니다. 다시 재생할 때는 처음부터 시작해요.
SOURCE FILES
원본 코드 읽기
수집한 원본 소스와 실행 안내를 함께 제공합니다.
YPzJoNo/index.html
<section>
<div class="carousel" aria-label="horizontal carousel of images">
<div class="carousel-slide">
<div class="carousel-img-wrapper">
<img src="https://images.unsplash.com/photo-1659733582156-d2a11801e59f?q=50&w=1600">
</div>
</div>
<div class="carousel-slide">
<div class="carousel-img-wrapper">
<img src="https://images.unsplash.com/photo-1543362137-5df0547b039d?q=50&w=1600">
</div>
</div>
<div class="carousel-slide">
<div class="carousel-img-wrapper">
<img src="https://images.unsplash.com/photo-1631142260228-305ccb610dba?q=50&w=1600">
</div>
</div>
<div class="carousel-slide">
<div class="carousel-img-wrapper">
<img src="https://images.unsplash.com/photo-1708022766976-49ca46c0f7de?q=50&w=1600">
</div>
</div>
<div class="carousel-slide">
<div class="carousel-img-wrapper">
<img src="https://images.unsplash.com/photo-1631142260079-970258649676?q=50&w=1600">
</div>
</div>
<div class="carousel-slide">
<div class="carousel-img-wrapper">
<img src="https://images.unsplash.com/photo-1708022809820-2668e65877b9?q=50&w=1600">
</div>
</div>
</div>
<nav class="carousel-nav">
<button class="prev" tabindex="0" aria-label="Previous Slide"></button>
<button class="next" tabindex="0" aria-label="Next Slide"></button>
</nav>
<svg class="carousel-progress" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 0 0">
<path stroke="#fff" stroke-width="2" stroke-linecap="round" d=""/>
</svg>
</section>YPzJoNo/script.js
const slides = gsap.utils.toArray(".carousel-slide");
const prev = document.querySelector(".prev");
const next = document.querySelector(".next");
const pathWidth = (slides.length-1)*5 + 6
let activeSlide;
// Initial settings
gsap.set(".carousel", { overflow: "hidden", "scroll-snap-type": "none" });
gsap.set(".carousel-nav, .carousel-progress", { display: "block" });
gsap.set(".carousel-progress", { attr:{ viewBox: "-1 -1 "+(pathWidth+2)+" 2" } });
gsap.set(".carousel-progress path", { attr:{ "d": "M0,0 "+ pathWidth +",0" } });
updateProgress(0,0);
function updateProgress(index, dur){
let str = ""
for (let i=0; i<slides.length; i++){
str += (i==index) ? 6 : .5;
str += " " + 4.5 + " ";
}
gsap.to(".carousel-progress path", {
duration:(dur == null ? 0.5 : dur),
attr:{ "stroke-dasharray": str }
});
}
// create seamless horizontal loop
const loop = horizontalLoop(slides, {
paused: true, // no auto-scroll
center: true, // snap the active slide to the center
draggable: true, // requires Draggable & InertiaPlugin
onChange: (slide, index) => { // called when the active slide changes
activeSlide && activeSlide.classList.remove("active");
slide.classList.add("active");
activeSlide = slide;
updateProgress(index);
}
});
// prev / next button behavior
function arrowBtnOver(e) { gsap.to(e.target, { opacity: 0.4 }); }
function arrowBtnOut(e) { gsap.to(e.target, { opacity: 1 }); }
next.addEventListener("pointerover", arrowBtnOver);
next.addEventListener("pointerout", arrowBtnOut);
next.addEventListener("click", () => loop.next({ duration: 1, ease: "expo" }));
prev.addEventListener("pointerover", arrowBtnOver);
prev.addEventListener("pointerout", arrowBtnOut);
prev.addEventListener("click", () => loop.previous({ duration: 1, ease: "expo" }));
// center on initial slide
loop.toIndex(0, { duration: 0 });
slideImgUpdate();
// image parallax
function slideImgUpdate(){
slides.forEach( slide => {
const rect = slide.getBoundingClientRect();
const prog = gsap.utils.mapRange(-rect.width, innerWidth, 0, 1, rect.x);
const val = gsap.utils.clamp(0, 1, prog );
gsap.set(slide.querySelector(".carousel-img-wrapper"), {
scale: gsap.utils.interpolate(0.5, 1.5, gsap.utils.wrapYoyo(0, 0.5, val)),
});
gsap.set(slide.querySelector("img"), {
xPercent: gsap.utils.interpolate(0, -50, val),
scale: gsap.utils.interpolate(1.5, 0.5, gsap.utils.wrapYoyo(0, 0.5, val))
});
});
}
Observer.create({
target: ".carousel",
type: "wheel",
onLeft: (o) => {
if ( !gsap.isTweening(loop) && o.deltaX < -4 ) loop.next({ duration: 0.5, ease: "power1.inOut" })
},
onRight: (o) => {
if ( !gsap.isTweening(loop) && o.deltaX > 4 ) loop.previous({ duration: 0.5, ease: "power1.inOut" })
}
});
/*
This helper function makes a group of elements animate along the x-axis in a seamless, responsive loop.
Features:
- Uses xPercent so that even if the widths change (like if the window gets resized), it should still work in most cases.
- When each item animates to the left or right enough, it will loop back to the other side
- Optionally pass in a config object with values like draggable: true, center: true, speed (default: 1, which travels at roughly 100 pixels per second), paused (boolean), repeat, reversed, and paddingRight.
- The returned timeline will have the following methods added to it:
- next() - animates to the next element using a timeline.tweenTo() which it returns. You can pass in a vars object to control duration, easing, etc.
- previous() - animates to the previous element using a timeline.tweenTo() which it returns. You can pass in a vars object to control duration, easing, etc.
- toIndex() - pass in a zero-based index value of the element that it should animate to, and optionally pass in a vars object to control duration, easing, etc. Always goes in the shortest direction
- current() - returns the current index (if an animation is in-progress, it reflects the final index)
- times - an Array of the times on the timeline where each element hits the "starting" spot.
*/
function horizontalLoop(items, config) {
let timeline;
items = gsap.utils.toArray(items);
config = config || {};
gsap.context(() => { // use a context so that if this is called from within another context or a gsap.matchMedia(), we can perform proper cleanup like the "resize" event handler on the window
let onChange = config.onChange,
lastIndex = 0,
tl = gsap.timeline({repeat: config.repeat, onUpdate: onChange && function() {
slideImgUpdate(); // custom function added to create parallax movement on the images
let i = tl.closestIndex();
if (lastIndex !== i) {
lastIndex = i;
onChange(items[i], i);
}
}, paused: config.paused, defaults: {ease: "none"}, onReverseComplete: () => tl.totalTime(tl.rawTime() + tl.duration() * 100)}),
length = items.length,
startX = items[0].offsetLeft,
times = [],
widths = [],
spaceBefore = [],
xPercents = [],
curIndex = 0,
indexIsDirty = false,
center = config.center,
pixelsPerSecond = (config.speed || 1) * 100,
snap = config.snap === false ? v => v : gsap.utils.snap(config.snap || 1), // some browsers shift by a pixel to accommodate flex layouts, so for example if width is 20% the first element's width might be 242px, and the next 243px, alternating back and forth. So we snap to 5 percentage points to make things look more natural
timeOffset = 0,
container = center === true ? items[0].parentNode : gsap.utils.toArray(center)[0] || items[0].parentNode,
totalWidth,
getTotalWidth = () => items[length-1].offsetLeft + xPercents[length-1] / 100 * widths[length-1] - startX + spaceBefore[0] + items[length-1].offsetWidth * gsap.getProperty(items[length-1], "scaleX") + (parseFloat(config.paddingRight) || 0),
populateWidths = () => {
let b1 = container.getBoundingClientRect(), b2;
items.forEach((el, i) => {
widths[i] = parseFloat(gsap.getProperty(el, "width", "px"));
xPercents[i] = snap(parseFloat(gsap.getProperty(el, "x", "px")) / widths[i] * 100 + gsap.getProperty(el, "xPercent"));
b2 = el.getBoundingClientRect();
spaceBefore[i] = b2.left - (i ? b1.right : b1.left);
b1 = b2;
});
gsap.set(items, { // convert "x" to "xPercent" to make things responsive, and populate the widths/xPercents Arrays to make lookups faster.
xPercent: i => xPercents[i]
});
totalWidth = getTotalWidth();
},
timeWrap,
populateOffsets = () => {
timeOffset = center ? tl.duration() * (container.offsetWidth / 2) / totalWidth : 0;
center && times.forEach((t, i) => {
times[i] = timeWrap(tl.labels["label" + i] + tl.duration() * widths[i] / 2 / totalWidth - timeOffset);
});
},
getClosest = (values, value, wrap) => {
let i = values.length,
closest = 1e10,
index = 0, d;
while (i--) {
d = Math.abs(values[i] - value);
if (d > wrap / 2) {
d = wrap - d;
}
if (d < closest) {
closest = d;
index = i;
}
}
return index;
},
populateTimeline = () => {
let i, item, curX, distanceToStart, distanceToLoop;
tl.clear();
for (i = 0; i < length; i++) {
item = items[i];
curX = xPercents[i] / 100 * widths[i];
distanceToStart = item.offsetLeft + curX - startX + spaceBefore[0];
distanceToLoop = distanceToStart + widths[i] * gsap.getProperty(item, "scaleX");
tl.to(item, {xPercent: snap((curX - distanceToLoop) / widths[i] * 100), duration: distanceToLoop / pixelsPerSecond}, 0)
.fromTo(item, {xPercent: snap((curX - distanceToLoop + totalWidth) / widths[i] * 100)}, {xPercent: xPercents[i], duration: (curX - distanceToLoop + totalWidth - curX) / pixelsPerSecond, immediateRender: false}, distanceToLoop / pixelsPerSecond)
.add("label" + i, distanceToStart / pixelsPerSecond);
times[i] = distanceToStart / pixelsPerSecond;
}
timeWrap = gsap.utils.wrap(0, tl.duration());
},
refresh = (deep) => {
let progress = tl.progress();
tl.progress(0, true);
populateWidths();
deep && populateTimeline();
populateOffsets();
deep && tl.draggable && tl.paused() ? tl.time(times[curIndex], true) : tl.progress(progress, true);
},
onResize = () => refresh(true),
proxy;
gsap.set(items, {x: 0});
populateWidths();
populateTimeline();
populateOffsets();
window.addEventListener("resize", onResize);
function toIndex(index, vars) {
vars = vars || {};
(Math.abs(index - curIndex) > length / 2) && (index += index > curIndex ? -length : length); // always go in the shortest direction
let newIndex = gsap.utils.wrap(0, length, index),
time = times[newIndex];
if (time > tl.time() !== index > curIndex && index !== curIndex) { // if we're wrapping the timeline's playhead, make the proper adjustments
time += tl.duration() * (index > curIndex ? 1 : -1);
}
if (time < 0 || time > tl.duration()) {
vars.modifiers = {time: timeWrap};
}
curIndex = newIndex;
vars.overwrite = true;
gsap.killTweensOf(proxy);
return vars.duration === 0 ? tl.time(timeWrap(time)) : tl.tweenTo(time, vars);
}
tl.toIndex = (index, vars) => toIndex(index, vars);
tl.closestIndex = setCurrent => {
let index = getClosest(times, tl.time(), tl.duration());
if (setCurrent) {
curIndex = index;
indexIsDirty = false;
}
return index;
};
tl.current = () => indexIsDirty ? tl.closestIndex(true) : curIndex;
tl.next = vars => toIndex(tl.current()+1, vars);
tl.previous = vars => toIndex(tl.current()-1, vars);
tl.times = times;
tl.progress(1, true).progress(0, true); // pre-render for performance
if (config.reversed) {
tl.vars.onReverseComplete();
tl.reverse();
}
if (config.draggable && typeof(Draggable) === "function") {
proxy = document.createElement("div")
let wrap = gsap.utils.wrap(0, 1),
ratio, startProgress, draggable, dragSnap, lastSnap, initChangeX, wasPlaying,
align = () => tl.progress(wrap(startProgress + (draggable.startX - draggable.x) * ratio)),
syncIndex = () => tl.closestIndex(true);
typeof(InertiaPlugin) === "undefined" && console.warn("InertiaPlugin required for momentum-based scrolling and snapping. https://greensock.com/club");
draggable = Draggable.create(proxy, {
trigger: items[0].parentNode,
type: "x",
onPressInit() {
let x = this.x;
gsap.killTweensOf(tl);
wasPlaying = !tl.paused();
tl.pause();
startProgress = tl.progress();
refresh();
ratio = 1 / totalWidth;
initChangeX = (startProgress / -ratio) - x;
gsap.set(proxy, {x: startProgress / -ratio});
},
onDrag: align,
onThrowUpdate: align,
overshootTolerance: 0,
inertia: true,
snap(value) {
//note: if the user presses and releases in the middle of a throw, due to the sudden correction of proxy.x in the onPressInit(), the velocity could be very large, throwing off the snap. So sense that condition and adjust for it. We also need to set overshootTolerance to 0 to prevent the inertia from causing it to shoot past and come back
if (Math.abs(startProgress / -ratio - this.x) < 10) {
return lastSnap + initChangeX
}
let time = -(value * ratio) * tl.duration(),
wrappedTime = timeWrap(time),
snapTime = times[getClosest(times, wrappedTime, tl.duration())],
dif = snapTime - wrappedTime;
Math.abs(dif) > tl.duration() / 2 && (dif += dif < 0 ? tl.duration() : -tl.duration());
lastSnap = (time + dif) / tl.duration() / -ratio;
return lastSnap;
},
onRelease() {
syncIndex();
draggable.isThrowing && (indexIsDirty = true);
},
onThrowComplete: () => {
syncIndex();
wasPlaying && tl.play();
}
})[0];
tl.draggable = draggable;
}
tl.closestIndex(true);
lastIndex = curIndex;
onChange && onChange(items[curIndex], curIndex);
timeline = tl;
return () => window.removeEventListener("resize", onResize); // cleanup
});
return timeline;
}함께 쓰는 파일 3개 보기
YPzJoNo/style.css
html, body {
margin:0;
padding:0;
background:#000;
}
section {
width: 100vw;
min-height:100vh;
display: flex;
flex-direction:column;
align-items:center;
justify-content:center;
overflow:hidden;
}
.carousel {
width: 100vw;
height: 100vh;
overflow-x: auto;
scroll-snap-type: x mandatory;
display: flex;
-webkit-overflow-scrolling: touch;
}
.carousel-slide {
position:relative;
flex: 0 0 100%;
display: flex;
flex-direction:column;
justify-content: center;
align-items: center;
color: white;
scroll-snap-align: center;
}
.carousel-img-wrapper {
position:absolute;
width:100%;
height:100%;
left:0;
top:0;
overflow:hidden;
}
.carousel-slide img {
width:150%;
height:100%;
object-fit:cover;
}
.carousel-nav {
display:none; /* displayed in the JS */
position:absolute;
width:100%;
}
.carousel-nav button {
border:none;
font-size:3rem;
position:absolute;
top:50%;
aspect-ratio:1.5;
width:7vw;
max-width:75px;
height:auto;
background-color: transparent;
background-size: cover;
overflow:visible;
background-image: url( "data:image/svg+xml,%3Csvg stroke='%23ccc' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round' fill='none' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 22 15'%3E%3Cpath d='M2,11 11,2 20,11'/%3E%3C/svg%3E" );
}
.prev {
transform:translateY(-50%) rotate(-90deg);
}
.next {
transform:translateY(-50%) rotate(90deg);
right:0;
}
.carousel-progress {
display: none; /* displayed in the JS */
position: absolute;
width: 33%;
max-width: 300px;
max-height: 8px;
bottom: 3.5vh;
pointer-events: none;
opacity: 0.36;
}
/* Simplify the scroll bar appearance */
::-webkit-scrollbar {
height: 13px;
}
::-webkit-scrollbar-track {
background: transparent;
}
::-webkit-scrollbar-thumb {
border-top:6px solid #000;
background: #555;
width:50%;
}
::-webkit-scrollbar-thumb:hover {
background: #bbb;
}
@media (max-width: 500px) {
.carousel-nav button {
display:none;
}
}Original author attribution실행 안내·자료
Full-frame GSAP carousel
Original CodePen author account: creativeocean
Article author: Tom Miller
Code license: MIT under the verified Codrops downloadable-demo publisher grant.
Preserve the MIT notice and separate dependency/media credits.
Bundled dependency licenses실행 안내·자료
GSAP standard license snapshot
Source: https://gsap.com/community/standard-license/
Retrieved: 2026-09-22T04:22:49.089Z
Original distribution copyright and version headers remain in the runtime code.
Standard "No Charge" GSAP License
I. DEFINITIONS
“GSAP License” means the terms and conditions of this GSAP Software License Agreement.
"GSAP Products" means any Software made available at gsap.com (https://gsap.com) or any successor sites, including but not limited to the GSAP animation library and related plugins, tools, or extensions.
"Permitted Uses" means the implementation and/or use of GSAP Products on any website, web application, or digital interface by any person or entity (which may include, for clarity, those of companies that compete with Webflow in other areas of business).
"Prohibited Uses" means any implementation and/or use of GSAP Products in tools that allow users to build visual animations without code that encourages, induces, or materially assists in creating a solution that competes with Webflow’s visual animation building capabilities.
"Competitive Products" means any software, tool, or service that enables users to create, edit, or manage animations through a visual interface or builder similar to Webflow (https://webflow.com).
II. GRANT OF LICENSE
Subject to the terms and conditions of this GSAP License, Webflow grants you a non-exclusive, worldwide license to use, reproduce, display, and implement GSAP Products solely for Permitted Uses.
III. RESTRICTIONS
You may not:
Use any GSAP Products for any Prohibited Uses without prior written consent;
Reverse engineer any GSAP Products for the purpose of creating Competitive Products;
Remove or alter any proprietary notices or branding from GSAP Products.
IV. OWNERSHIP AND INTELLECTUAL PROPERTY
All intellectual property rights in GSAP Products, including but not limited to copyright, patents, trademarks, and trade secrets, remain the exclusive property of Webflow. This GSAP License does not transfer any ownership rights in GSAP Products to you.
V. TERMINATION
Webflow may terminate this GSAP License and revoke your access in its discretion if you fail to comply with any of these terms and conditions. Upon termination, you must cease all use of GSAP Products and destroy all copies in your possession.
VI. MISCELLANEOUS PROVISIONS
General: This GSAP License is incorporated into and subject to Webflow’s Terms of Service available here (https://webflow.com/legal/terms) ("Terms of Service"). In the event of any conflict or inconsistency between this GSAP License and the Terms of Service, the terms of this GSAP License shall govern in relation to your use of any GSAP Products.
Amendments: Webflow reserves the right to update or modify this GSAP License at any time by posting the revised terms on this website, provided that any such updates or modifications shall not result in any material degradation to the security, integrity, or functionality of any GSAP Products. You understand and agree that your continued use of any GSAP Products after such revisions to this GSAP License constitutes your acceptance of this GSAP License as revised. If you do not accept the revised GSAP License, you are prohibited from using versions of the GSAP Products released after the effective date of the revised GSAP License (as well as any updates made to previous versions). Notwithstanding, you may continue using previous versions of GSAP Products under the applicable terms licensed to you prior to the effective date of the revised GSAP License (for clarity, excluding any updates made thereto).
No Waiver: Failure of Webflow to enforce any provision of this GSAP License shall not constitute a waiver of future enforcement of that or any other provision.
FAQ
Is it acceptable for AI tools like ChatGPT, Cursor, Lovable, Webstudio, etc. to generate GSAP code?
Absolutely! AI-generated code is not a "Prohibited Use".
What if a WordPress plugin or theme or other niche tool allows users to create GSAP-driven effects through a visual interface? Is that prohibited?
We want to encourage developers to build on top of GSAP, including visual tools that don't directly compete with Webflow's rich animation-building capabilities. If you are not sure if your product might be considered a "Prohibited Use", feel free to contact us (https://gsap.com/contact) so we can talk through it!
Can I really use GSAP in commercial projects without paying anything?
Yes, really! Commercial usage is covered under the standard license. All of GSAP including the plugins that were formerly "members-only" like SplitText (https://gsap.com/docs/v3/Plugins/SplitText/) and MorphSVG (https://gsap.com/docs/v3/Plugins/MorphSVGPlugin) can be used in commercial projects at no charge. Enjoy! 💚
Effective date: April 30, 2025
Last modified date: May 30, 2025
Copyright (©) 2025, Webflow
BEHIND THE EXAMPLE
이 장면을 만드는 원리
관성 이동을 다시 잡을 때의 위치와 속도 보정
반복 입력에서 현재 의도와 전환의 종료·취소 책임을 명시합니다.
- 이 예제에서는
- horizontalLoop의 onPressInit은 현재 이동 tween을 끝내고 진행값을 보존해 drag proxy를 재정렬합니다. snap은 재정렬 직후 이동이 10px 미만이면 lastSnap과 initChangeX를 사용해 급격한 새 속도 영향을 줄입니다.
