03스프링 오버슛으로 되돌아오는 카드
기준 속도에 못 미치면 카드가 스프링 오버슛으로 원래 자리로 되돌아온다.
쓰임설문 카드 넘기기 실패 상태
SPRING_STIFFNESSSPRING_DAMPINGSWIPE_STACK_DEPTH_SCALE

<main class="stage">
<div class="es is-demo" id="es">
<p class="es__caption">스프링 오버슛으로 되돌아오는 카드</p>
<div class="es__scene" id="esScene">
<div class="es__peek" id="esPeek" aria-hidden="true"></div>
<div class="es__card" id="esCard" tabindex="0" role="group" aria-roledescription="스와이프 카드">
<p class="es__label" id="esLabel">주말 카페</p>
</div>
<button class="es__btn es__btn--nope" id="esNope" type="button" aria-label="싫어요">✕</button>
<button class="es__btn es__btn--like" id="esLike" type="button" aria-label="좋아요">♥</button>
</div>
<p class="es__status" id="esStatus" aria-live="polite">대기 중</p>
</div>
</main>@use "../../../../site/static/demo-tokens" as *;
// 값 하나: 해제 속도가 SPRING_FLING_VELOCITY_MIN 에 못 미치면 스프링(강성·감쇠)을 적분해
// 오버슛하며 원래 자리로 되돌아온다. 뒤 카드는 SWIPE_STACK_DEPTH_SCALE 만큼 줄어 비친다.
$duration: $dur-loop;
$easing: $ease-elastic;
$color: $subject-ink;
@include stage($stage-ink);
.es { display: grid; gap: $sp-2; justify-items: center; width: 100%; }
.es__caption { margin: 0; font-size: 12px; font-weight: 600; color: $subject-cream; }
.es__scene {
position: relative;
width: 220px;
height: 190px;
display: grid;
place-items: center;
}
.es__peek {
position: absolute;
width: 160px;
height: 180px;
border-radius: $r-card;
background: linear-gradient(160deg, $subject-lilac, $subject-blue);
opacity: .7;
}
.es__card {
position: relative;
width: 160px;
height: 180px;
border-radius: $r-card;
background: linear-gradient(160deg, $subject-mint, $subject-sky);
box-shadow: $shadow-raised;
display: grid;
place-items: center;
touch-action: none;
cursor: grab;
will-change: transform;
}
.es__card:active { cursor: grabbing; }
.es__card:focus-visible { outline: 2px solid $subject-blue-light; outline-offset: 3px; }
.es__label { margin: 0; font-size: 14px; font-weight: 700; color: $subject-ink; padding: 0 $sp-3; text-align: center; }
.es__btn {
position: absolute;
bottom: $sp-3;
width: 34px;
height: 34px;
border-radius: $r-pill;
border: 0;
background: $stage-paper;
box-shadow: $shadow-press;
font-size: 15px;
line-height: 1;
cursor: pointer;
display: grid;
place-items: center;
z-index: 2;
}
.es__btn--nope { left: $sp-3; color: $error; }
.es__btn--like { right: $sp-3; color: $subject-blue-deep; }
.es__btn:focus-visible { outline: 2px solid $subject-blue-light; outline-offset: 2px; }
.es__status { margin: 0; font-size: 11px; color: $subject-cream; font-weight: 600; }
@media (max-width: 340px) {
.es { gap: $sp-2; }
.es__scene { width: 150px; height: 108px; }
.es__peek { width: 78px; height: 92px; }
.es__card { width: 78px; height: 92px; }
.es__label { font-size: 10px; padding: 0 $sp-1; }
.es__btn { width: 22px; height: 22px; font-size: 11px; bottom: $sp-1; }
.es__btn--nope { left: $sp-1; }
.es__btn--like { right: $sp-1; }
}
@media (prefers-reduced-motion: reduce) {
.es__card { transition: none; }
}html, body {
margin: 0;
overflow: hidden;
}
.stage {
box-sizing: border-box;
min-height: 100vh;
display: grid;
place-items: center;
margin: 0;
background: #17141a;
font-family: -apple-system, "Segoe UI", "Noto Sans KR", sans-serif;
padding: clamp(8px, 4vw, 24px);
}
.es {
display: grid;
gap: 8px;
justify-items: center;
width: 100%;
}
.es__caption {
margin: 0;
font-size: 12px;
font-weight: 600;
color: #fff7e6;
}
.es__scene {
position: relative;
width: 220px;
height: 190px;
display: grid;
place-items: center;
}
.es__peek {
position: absolute;
width: 160px;
height: 180px;
border-radius: 16px;
background: linear-gradient(160deg, #b9a0ff, #2f6df6);
opacity: 0.7;
}
.es__card {
position: relative;
width: 160px;
height: 180px;
border-radius: 16px;
background: linear-gradient(160deg, #4cd4a6, #6ec8ff);
box-shadow: 0 14px 24px rgba(23, 20, 26, 0.32);
display: grid;
place-items: center;
touch-action: none;
cursor: grab;
will-change: transform;
}
.es__card:active {
cursor: grabbing;
}
.es__card:focus-visible {
outline: 2px solid #5b8cf8;
outline-offset: 3px;
}
.es__label {
margin: 0;
font-size: 14px;
font-weight: 700;
color: #17141a;
padding: 0 12px;
text-align: center;
}
.es__btn {
position: absolute;
bottom: 12px;
width: 34px;
height: 34px;
border-radius: 999px;
border: 0;
background: #ffffff;
box-shadow: 0 6px 12px rgba(23, 20, 26, 0.32);
font-size: 15px;
line-height: 1;
cursor: pointer;
display: grid;
place-items: center;
z-index: 2;
}
.es__btn--nope {
left: 12px;
color: #c2361a;
}
.es__btn--like {
right: 12px;
color: #0a4fe8;
}
.es__btn:focus-visible {
outline: 2px solid #5b8cf8;
outline-offset: 2px;
}
.es__status {
margin: 0;
font-size: 11px;
color: #fff7e6;
font-weight: 600;
}
@media (max-width: 340px) {
.es {
gap: 8px;
}
.es__scene {
width: 150px;
height: 108px;
}
.es__peek {
width: 78px;
height: 92px;
}
.es__card {
width: 78px;
height: 92px;
}
.es__label {
font-size: 10px;
padding: 0 4px;
}
.es__btn {
width: 22px;
height: 22px;
font-size: 11px;
bottom: 4px;
}
.es__btn--nope {
left: 4px;
}
.es__btn--like {
right: 4px;
}
}
@media (prefers-reduced-motion: reduce) {
.es__card {
transition: none;
}
}(function () {
"use strict";
// 변형 3: 03 폴더에 SWIPE_STACK_DEPTH_SCALE 를 실재시킨다 — 뒤 카드 한 장을 이 비율만큼 줄여 살짝 비친다.
var SWIPE_STACK_DEPTH_SCALE = 0.04;
// 값 하나: 해제 속도가 이 값에 못 미치면 스프링(강성·감쇠)을 적분해 오버슛하며 되돌아온다.
var SPRING_FLING_VELOCITY_MIN = 0.5;
var SPRING_STIFFNESS = 120;
var SPRING_DAMPING = 14;
var EXIT_PX = 320;
var CYCLE_S = 2;
var root = document.getElementById("es");
var card = document.getElementById("esCard");
var peek = document.getElementById("esPeek");
var label = document.getElementById("esLabel");
var status = document.getElementById("esStatus");
var btnLike = document.getElementById("esLike");
var btnNope = document.getElementById("esNope");
var reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
peek.style.transform = "translateY(" + (SWIPE_STACK_DEPTH_SCALE * 100).toFixed(1) + "%) scale(" + (1 - SWIPE_STACK_DEPTH_SCALE).toFixed(3) + ")";
function seedRand(seed) {
var s = seed >>> 0;
return function () { s = (s * 1664525 + 1013904223) >>> 0; return s / 4294967296; };
}
function clamp(v, lo, hi) { return Math.max(lo, Math.min(hi, v)); }
var CARDS = ["주말 카페", "홈트 기록", "독서 목록", "여행 메모", "아침 루틴", "저녁 산책"];
var rand = seedRand(37);
var idx = Math.floor(rand() * CARDS.length);
var dragging = false;
var startX = 0, lastX = 0, lastT = 0, vxRaw = 0;
var pos = 0, vel = 0, phase = "idle", exitDir = 1;
function setCard() { label.textContent = CARDS[idx % CARDS.length]; }
setCard();
function render() {
var rot = clamp(pos * 0.06, -18, 18);
card.style.transform = "translateX(" + pos.toFixed(1) + "px) rotate(" + rot.toFixed(2) + "deg)";
}
function nextCard() {
idx += 1; setCard();
pos = 0; vel = 0; phase = "idle";
render();
status.textContent = "대기 중";
}
function judge(velocityPxMs, dir) {
root.classList.remove("is-demo");
var flung = Math.abs(velocityPxMs) >= SPRING_FLING_VELOCITY_MIN;
if (reduce) {
if (flung) { status.textContent = dir > 0 ? "좋아요 처리됨" : "싫어요 처리됨"; nextCard(); }
else { pos = 0; vel = 0; render(); status.textContent = "스프링으로 되돌아옴"; phase = "idle"; }
return;
}
if (flung) {
phase = "exit"; exitDir = dir;
status.textContent = dir > 0 ? "좋아요 처리됨" : "싫어요 처리됨";
} else {
phase = "spring";
vel = velocityPxMs * 1000; // px/ms → px/s, 관성을 스프링에 넘긴다
status.textContent = "스프링으로 되돌아옴";
}
}
function startDrag(clientX) {
root.classList.remove("is-demo");
dragging = true; phase = "idle";
startX = clientX; lastX = clientX; lastT = performance.now(); vxRaw = 0;
}
function moveDrag(clientX) {
if (!dragging) return;
var now = performance.now();
var dt = Math.max(now - lastT, 1);
vxRaw = (clientX - lastX) / dt;
lastX = clientX; lastT = now;
pos = clientX - startX;
render();
}
function endDrag() {
if (!dragging) return;
dragging = false;
judge(vxRaw, pos >= 0 ? 1 : -1);
}
card.addEventListener("pointerdown", function (e) { card.setPointerCapture(e.pointerId); startDrag(e.clientX); });
card.addEventListener("pointermove", function (e) { moveDrag(e.clientX); });
card.addEventListener("pointerup", endDrag);
card.addEventListener("pointercancel", endDrag);
function keyVerdict(dir, weak) {
root.classList.remove("is-demo");
pos = dir * (weak ? 34 : 70); render();
judge(dir * (weak ? 0.1 : SPRING_FLING_VELOCITY_MIN + 0.4), dir);
}
card.addEventListener("keydown", function (e) {
if (e.key === "ArrowRight") { e.preventDefault(); keyVerdict(1, false); }
else if (e.key === "ArrowLeft") { e.preventDefault(); keyVerdict(-1, false); }
});
btnLike.addEventListener("click", function () { keyVerdict(1, false); });
btnNope.addEventListener("click", function () { keyVerdict(-1, false); });
// 스프링 방정식(강성 SPRING_STIFFNESS·감쇠 SPRING_DAMPING)을 매 프레임 적분한다 — 목표(0)를 넘겼다가 되돌아온다.
function integrate(dt) {
var accel = SPRING_STIFFNESS * (0 - pos) - SPRING_DAMPING * vel;
vel += accel * dt;
pos += vel * dt;
if (Math.abs(pos) < 0.4 && Math.abs(vel) < 4) { pos = 0; vel = 0; phase = "idle"; }
}
function step(dt) {
var dtS = Math.min(dt / 1000, 0.032);
if (phase === "exit") {
pos += exitDir * Math.max(Math.abs(vel) / 1000, SPRING_FLING_VELOCITY_MIN * 1.3) * dt;
render();
if (Math.abs(pos) > EXIT_PX) nextCard();
} else if (phase === "spring") {
integrate(dtS);
render();
}
}
// .is-demo 자동 시연: 실제 pointer 없이 pos·judge() 를 같은 경로로 호출한다.
var start = null, lastNow = 0, prevT = 0, synthPhase = "wait";
function synth(t) {
if (t > 0.4 && t < 0.65 && synthPhase === "wait") synthPhase = "pull";
if (synthPhase === "pull") {
var p = clamp((t - 0.4) / 0.25, 0, 1);
pos = p * 60; render();
if (t >= 0.65) { synthPhase = "afterPull"; judge(0.08, 1); }
}
if (t > 1.3 && t < 1.55 && synthPhase === "afterPull") synthPhase = "throw";
if (synthPhase === "throw") {
var q = clamp((t - 1.3) / 0.25, 0, 1);
pos = -q * 140; render();
if (t >= 1.55) { synthPhase = "done"; judge(-(SPRING_FLING_VELOCITY_MIN + 0.4), -1); }
}
}
function loop(now) {
if (start === null) { start = now; lastNow = now; lastT = now; }
var dt = Math.min(now - lastNow, 48);
lastNow = now;
var t = ((now - start) / 1000) % CYCLE_S;
if (t < prevT) synthPhase = "wait";
prevT = t;
if (!reduce && root.classList.contains("is-demo")) synth(t);
if (!reduce) step(dt);
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
})();// ElasticSnapbackSwipeCard — vanilla 판(run/422/demo/03-swipe-deck-precision-elastic-snapback/index.html) 의 React 포트.
// 변형 3: SWIPE_STACK_DEPTH_SCALE 를 뒤 카드 한 장에 실재시킨다. 값 하나: 해제 속도가
// SPRING_FLING_VELOCITY_MIN 에 못 미치면 스프링(강성·감쇠)을 적분해 오버슛하며 되돌아온다.
import { useEffect, useRef, useState } from "react";
import type { PointerEvent as ReactPointerEvent } from "react";
import styles from "./ElasticSnapbackSwipeCard.module.scss";
type Box<T> = { current: T };
const SWIPE_STACK_DEPTH_SCALE = 0.04;
const SPRING_FLING_VELOCITY_MIN = 0.5;
const SPRING_STIFFNESS = 120;
const SPRING_DAMPING = 14;
const EXIT_PX = 320;
const CYCLE_S = 2;
const CARDS = ["주말 카페", "홈트 기록", "독서 목록", "여행 메모", "아침 루틴", "저녁 산책"];
function seedRand(seed: number) {
let s = seed >>> 0;
return function (): number {
s = (s * 1664525 + 1013904223) >>> 0;
return s / 4294967296;
};
}
function clamp(v: number, lo: number, hi: number): number {
return Math.max(lo, Math.min(hi, v));
}
export default function ElasticSnapbackSwipeCard() {
const cardRef = useRef<HTMLDivElement | null>(null);
const peekRef = useRef<HTMLDivElement | null>(null);
const posRef = useRef<number>(0) as Box<number>;
const velRef = useRef<number>(0) as Box<number>;
const phaseRef = useRef<string>("idle") as Box<string>;
const exitDirRef = useRef<number>(1) as Box<number>;
const draggingRef = useRef<boolean>(false) as Box<boolean>;
const startXRef = useRef<number>(0) as Box<number>;
const lastXRef = useRef<number>(0) as Box<number>;
const lastTRef = useRef<number>(0) as Box<number>;
const idxRef = useRef<number>(Math.floor(seedRand(37)() * CARDS.length)) as Box<number>;
const frameRef = useRef<number>(0) as Box<number>;
const [label, setLabel] = useState(CARDS[idxRef.current % CARDS.length]);
const [status, setStatus] = useState("대기 중");
const [demo, setDemo] = useState(true);
const [reduce, setReduce] = useState(false);
useEffect(() => {
const peek = peekRef.current;
if (!peek) return;
peek.style.transform = "translateY(" + (SWIPE_STACK_DEPTH_SCALE * 100).toFixed(1) + "%) scale(" + (1 - SWIPE_STACK_DEPTH_SCALE).toFixed(3) + ")";
}, []);
function render(): void {
const card = cardRef.current;
if (!card) return;
const rot = clamp(posRef.current * 0.06, -18, 18);
card.style.transform = "translateX(" + posRef.current.toFixed(1) + "px) rotate(" + rot.toFixed(2) + "deg)";
}
function nextCard(): void {
idxRef.current += 1;
setLabel(CARDS[idxRef.current % CARDS.length]);
posRef.current = 0; velRef.current = 0; phaseRef.current = "idle";
render();
setStatus("대기 중");
}
function judge(velocityPxMs: number, dir: number): void {
setDemo(false);
const flung = Math.abs(velocityPxMs) >= SPRING_FLING_VELOCITY_MIN;
if (reduce) {
if (flung) { setStatus(dir > 0 ? "좋아요 처리됨" : "싫어요 처리됨"); nextCard(); }
else { posRef.current = 0; velRef.current = 0; render(); setStatus("스프링으로 되돌아옴"); phaseRef.current = "idle"; }
return;
}
if (flung) {
phaseRef.current = "exit"; exitDirRef.current = dir;
setStatus(dir > 0 ? "좋아요 처리됨" : "싫어요 처리됨");
} else {
phaseRef.current = "spring";
velRef.current = velocityPxMs * 1000;
setStatus("스프링으로 되돌아옴");
}
}
function startDrag(clientX: number): void {
setDemo(false);
draggingRef.current = true; phaseRef.current = "idle";
startXRef.current = clientX; lastXRef.current = clientX; lastTRef.current = performance.now();
}
function moveDrag(clientX: number): void {
if (!draggingRef.current) return;
const now = performance.now();
const dt = Math.max(now - lastTRef.current, 1);
velRef.current = ((clientX - lastXRef.current) / dt) * 1000;
lastXRef.current = clientX; lastTRef.current = now;
posRef.current = clientX - startXRef.current;
render();
}
function endDrag(): void {
if (!draggingRef.current) return;
draggingRef.current = false;
judge(velRef.current / 1000, posRef.current >= 0 ? 1 : -1);
}
function onPointerDown(e: ReactPointerEvent<HTMLDivElement>): void {
e.currentTarget.setPointerCapture(e.pointerId);
startDrag(e.clientX);
}
function onPointerMove(e: ReactPointerEvent<HTMLDivElement>): void { moveDrag(e.clientX); }
function onPointerUp(): void { endDrag(); }
function keyVerdict(dir: number, weak: boolean): void {
setDemo(false);
posRef.current = dir * (weak ? 34 : 70); render();
judge(dir * (weak ? 0.1 : SPRING_FLING_VELOCITY_MIN + 0.4), dir);
}
function onKeyDown(e: any): void {
if (e.key === "ArrowRight") { e.preventDefault(); keyVerdict(1, false); }
else if (e.key === "ArrowLeft") { e.preventDefault(); keyVerdict(-1, false); }
}
function integrate(dt: number): void {
const accel = SPRING_STIFFNESS * (0 - posRef.current) - SPRING_DAMPING * velRef.current;
velRef.current += accel * dt;
posRef.current += velRef.current * dt;
if (Math.abs(posRef.current) < 0.4 && Math.abs(velRef.current) < 4) { posRef.current = 0; velRef.current = 0; phaseRef.current = "idle"; }
}
function step(dt: number): void {
const dtS = Math.min(dt / 1000, 0.032);
if (phaseRef.current === "exit") {
posRef.current += exitDirRef.current * Math.max(Math.abs(velRef.current) / 1000, SPRING_FLING_VELOCITY_MIN * 1.3) * dt;
render();
if (Math.abs(posRef.current) > EXIT_PX) nextCard();
} else if (phaseRef.current === "spring") {
integrate(dtS);
render();
}
}
function synth(t: number, synthPhaseRef: Box<string>): void {
if (t > 0.4 && t < 0.65 && synthPhaseRef.current === "wait") synthPhaseRef.current = "pull";
if (synthPhaseRef.current === "pull") {
const p = clamp((t - 0.4) / 0.25, 0, 1);
posRef.current = p * 60; render();
if (t >= 0.65) { synthPhaseRef.current = "afterPull"; judge(0.08, 1); }
}
if (t > 1.3 && t < 1.55 && synthPhaseRef.current === "afterPull") synthPhaseRef.current = "throw";
if (synthPhaseRef.current === "throw") {
const q = clamp((t - 1.3) / 0.25, 0, 1);
posRef.current = -q * 140; render();
if (t >= 1.55) { synthPhaseRef.current = "done"; judge(-(SPRING_FLING_VELOCITY_MIN + 0.4), -1); }
}
}
useEffect(() => {
setReduce(window.matchMedia("(prefers-reduced-motion: reduce)").matches);
}, []);
useEffect(() => {
let start = 0, lastNow = 0, prevT = 0;
const synthPhaseRef: Box<string> = { current: "wait" };
function loop(now: number): void {
if (start === 0) { start = now; lastNow = now; }
const dt = Math.min(now - lastNow, 48);
lastNow = now;
const t = ((now - start) / 1000) % CYCLE_S;
if (t < prevT) synthPhaseRef.current = "wait";
prevT = t;
if (!reduce && demo) synth(t, synthPhaseRef);
if (!reduce) step(dt);
frameRef.current = requestAnimationFrame(loop);
}
frameRef.current = requestAnimationFrame(loop);
return () => cancelAnimationFrame(frameRef.current);
}, [reduce, demo]);
return (
<main className={styles.stage}>
<div className={styles.es}>
<p className={styles.caption}>스프링 오버슛으로 되돌아오는 카드</p>
<div className={styles.scene}>
<div className={styles.peek} ref={peekRef} aria-hidden="true" />
<div
className={styles.card}
ref={cardRef}
tabIndex={0}
role="group"
aria-roledescription="스와이프 카드"
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={onPointerUp}
onKeyDown={onKeyDown}
>
<p className={styles.label}>{label}</p>
</div>
<button className={styles.btnNope} type="button" aria-label="싫어요" onClick={() => keyVerdict(-1, false)}>✕</button>
<button className={styles.btnLike} type="button" aria-label="좋아요" onClick={() => keyVerdict(1, false)}>♥</button>
</div>
<p className={styles.status} aria-live="polite">{status}</p>
</div>
</main>
);
}03 스프링 오버슛으로 되돌아오는 카드 — 측정 누적면적 15.172% · 움직인 프레임 8/23GODRICH 원작 · zip 에 SCSS·React 포함 · 카드 스와이프 ui 9가지 — 드래그를 물리 계산으로 다듬기
이 데모가 속한 글
카드 스와이프 ui 9가지 — 드래그를 물리 계산으로 다듬기카드 스와이프 ui 아홉 개를 모아 놓고 봤다. 엄지 끝 속도가 02번 기준을 넘지 못한 순간, 카드는 손을 놓아도 날아가지 않고 03번처럼 스프링으로 튕겨 제자리에 앉는다. 마지막 장까지 넘긴 자리엔 08번 빈 카 이 글의 데모 전부 보기


