04遠近投影で積み重なるカードスタック
後ろに積まれたカードは遠近投影で一枚ずつ小さくなり、上へずれて階段状に重なる。
使いどころ商品レコメンドのカードスタック
STACK_PERSPECTIVE_SCALEFOCALRELEASE_VELOCITY_MIN

<main class="stage">
<div class="sd is-demo" id="sd">
<p class="sd__caption">遠近投影で積み重なるカードスタック</p>
<div class="sd__scene" id="sdScene">
<div class="sd__peek" id="sdPeek3" aria-hidden="true"></div>
<div class="sd__peek" id="sdPeek2" aria-hidden="true"></div>
<div class="sd__peek" id="sdPeek1" aria-hidden="true"></div>
<div class="sd__card" id="sdCard" tabindex="0" role="group" aria-roledescription="スワイプカード">
<p class="sd__label" id="sdLabel">宅トレ記録</p>
</div>
<button class="sd__btn sd__btn--nope" id="sdNope" type="button" aria-label="いいえ">✕</button>
<button class="sd__btn sd__btn--like" id="sdLike" type="button" aria-label="いいね">♥</button>
</div>
<p class="sd__status" id="sdStatus" aria-live="polite">待機中</p>
</div>
</main>@use "../../../../site/static/demo-tokens" as *;
// 값 하나: 뒤 카드일수록 STACK_PERSPECTIVE_SCALE·초점거리로 원근 투영 계산해 작아지고 위로 겹친다.
$duration: $dur-base;
$easing: $ease-out;
$color: $subject-blue-deep;
@include stage($stage-orange);
.sd { display: grid; gap: $sp-2; justify-items: center; width: 100%; }
.sd__caption { margin: 0; font-size: 12px; font-weight: 600; color: $subject-ink; }
.sd__scene {
position: relative;
width: 220px;
height: 190px;
display: grid;
place-items: center;
}
.sd__peek {
position: absolute;
width: 160px;
height: 180px;
border-radius: $r-card;
background: linear-gradient(160deg, $subject-lilac, $subject-sky);
will-change: transform, opacity;
}
.sd__card {
position: relative;
z-index: 4;
width: 160px;
height: 180px;
border-radius: $r-card;
background: linear-gradient(160deg, $subject-mint, $subject-blue-light);
box-shadow: $shadow-raised;
display: grid;
place-items: center;
touch-action: none;
cursor: grab;
will-change: transform;
}
.sd__card:active { cursor: grabbing; }
.sd__card:focus-visible { outline: 2px solid $subject-blue-light; outline-offset: 3px; }
.sd__label { margin: 0; font-size: 14px; font-weight: 700; color: $subject-ink; padding: 0 $sp-3; text-align: center; }
.sd__btn {
position: absolute;
bottom: $sp-3;
z-index: 5;
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;
}
.sd__btn--nope { left: $sp-3; color: $error; }
.sd__btn--like { right: $sp-3; color: $subject-blue-deep; }
.sd__btn:focus-visible { outline: 2px solid $subject-blue-light; outline-offset: 2px; }
.sd__status { margin: 0; font-size: 11px; color: $subject-ink; font-weight: 600; }
@media (max-width: 340px) {
.sd { gap: $sp-2; }
.sd__scene { width: 150px; height: 108px; }
.sd__peek { width: 78px; height: 92px; }
.sd__card { width: 78px; height: 92px; }
.sd__label { font-size: 10px; padding: 0 $sp-1; }
.sd__btn { width: 22px; height: 22px; font-size: 11px; bottom: $sp-1; }
.sd__btn--nope { left: $sp-1; }
.sd__btn--like { right: $sp-1; }
}
@media (prefers-reduced-motion: reduce) {
.sd__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: #ff4d1f;
font-family: -apple-system, "Segoe UI", "Noto Sans KR", sans-serif;
padding: clamp(8px, 4vw, 24px);
}
.sd {
display: grid;
gap: 8px;
justify-items: center;
width: 100%;
}
.sd__caption {
margin: 0;
font-size: 12px;
font-weight: 600;
color: #17141a;
}
.sd__scene {
position: relative;
width: 220px;
height: 190px;
display: grid;
place-items: center;
}
.sd__peek {
position: absolute;
width: 160px;
height: 180px;
border-radius: 16px;
background: linear-gradient(160deg, #b9a0ff, #6ec8ff);
will-change: transform, opacity;
}
.sd__card {
position: relative;
z-index: 4;
width: 160px;
height: 180px;
border-radius: 16px;
background: linear-gradient(160deg, #4cd4a6, #5b8cf8);
box-shadow: 0 14px 24px rgba(23, 20, 26, 0.32);
display: grid;
place-items: center;
touch-action: none;
cursor: grab;
will-change: transform;
}
.sd__card:active {
cursor: grabbing;
}
.sd__card:focus-visible {
outline: 2px solid #5b8cf8;
outline-offset: 3px;
}
.sd__label {
margin: 0;
font-size: 14px;
font-weight: 700;
color: #17141a;
padding: 0 12px;
text-align: center;
}
.sd__btn {
position: absolute;
bottom: 12px;
z-index: 5;
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;
}
.sd__btn--nope {
left: 12px;
color: #c2361a;
}
.sd__btn--like {
right: 12px;
color: #0a4fe8;
}
.sd__btn:focus-visible {
outline: 2px solid #5b8cf8;
outline-offset: 2px;
}
.sd__status {
margin: 0;
font-size: 11px;
color: #17141a;
font-weight: 600;
}
@media (max-width: 340px) {
.sd {
gap: 8px;
}
.sd__scene {
width: 150px;
height: 108px;
}
.sd__peek {
width: 78px;
height: 92px;
}
.sd__card {
width: 78px;
height: 92px;
}
.sd__label {
font-size: 10px;
padding: 0 4px;
}
.sd__btn {
width: 22px;
height: 22px;
font-size: 11px;
bottom: 4px;
}
.sd__btn--nope {
left: 4px;
}
.sd__btn--like {
right: 4px;
}
}
@media (prefers-reduced-motion: reduce) {
.sd__card {
transition: none;
}
}(function () {
"use strict";
// 값 하나: 인덱스가 하나 늘 때마다 원근 투영(초점거리 FOCAL) 으로 scale·translateY 가 줄어든다.
var STACK_PERSPECTIVE_SCALE = 0.14;
var FOCAL = 260;
var STACK_SIZE = 3;
var RELEASE_VELOCITY_MIN = 0.4;
var EXIT_PX = 320;
var CYCLE_S = 2;
var root = document.getElementById("sd");
var card = document.getElementById("sdCard");
var label = document.getElementById("sdLabel");
var status = document.getElementById("sdStatus");
var btnLike = document.getElementById("sdLike");
var btnNope = document.getElementById("sdNope");
var peeks = [
document.getElementById("sdPeek1"),
document.getElementById("sdPeek2"),
document.getElementById("sdPeek3")
];
var reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
// 원근 투영: depth_i = i * STACK_PERSPECTIVE_SCALE * FOCAL, scale_i = FOCAL / (FOCAL + depth_i)
function layoutStack() {
for (var i = 1; i <= STACK_SIZE; i++) {
var depth = i * STACK_PERSPECTIVE_SCALE * FOCAL;
var scale = FOCAL / (FOCAL + depth);
var ty = -(1 - scale) * 60;
var el = peeks[i - 1];
el.style.transform = "translateY(" + ty.toFixed(2) + "%) scale(" + scale.toFixed(3) + ")";
el.style.opacity = (1 - i * 0.24).toFixed(2);
el.style.zIndex = String(STACK_SIZE - i);
}
}
layoutStack();
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(51);
var idx = Math.floor(rand() * CARDS.length);
var dragging = false;
var startX = 0, lastX = 0, lastT = 0, vx = 0;
var x = 0, phase = "idle", exitDir = 1;
function setCard() { label.textContent = CARDS[idx % CARDS.length]; }
setCard();
function render() {
var rot = clamp(x * 0.09, -20, 20);
card.style.transform = "translateX(" + x.toFixed(1) + "px) rotate(" + rot.toFixed(2) + "deg)";
}
function nextCard() {
idx += 1; setCard();
x = 0; vx = 0; phase = "idle";
render();
status.textContent = "待機中";
}
function judge(velocity, dir) {
root.classList.remove("is-demo");
var flung = Math.abs(velocity) >= RELEASE_VELOCITY_MIN;
if (reduce) {
if (flung) { status.textContent = dir > 0 ? "「いいね」処理済み" : "「いいえ」処理済み"; nextCard(); }
else { x = 0; render(); status.textContent = "元の位置に戻った"; phase = "idle"; }
return;
}
if (flung) { phase = "exit"; exitDir = dir; status.textContent = dir > 0 ? "「いいね」処理済み" : "「いいえ」処理済み"; }
else { phase = "settle"; status.textContent = "元の位置に戻った"; }
}
function startDrag(clientX) {
root.classList.remove("is-demo");
dragging = true; phase = "idle";
startX = clientX; lastX = clientX; lastT = performance.now(); vx = 0;
}
function moveDrag(clientX) {
if (!dragging) return;
var now = performance.now();
var dt = Math.max(now - lastT, 1);
vx = (clientX - lastX) / dt;
lastX = clientX; lastT = now;
x = clientX - startX;
render();
}
function endDrag() {
if (!dragging) return;
dragging = false;
judge(vx, x >= 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) {
root.classList.remove("is-demo");
x = dir * 60; render();
judge(dir * (RELEASE_VELOCITY_MIN + 0.3), dir);
}
card.addEventListener("keydown", function (e) {
if (e.key === "ArrowRight") { e.preventDefault(); keyVerdict(1); }
else if (e.key === "ArrowLeft") { e.preventDefault(); keyVerdict(-1); }
});
btnLike.addEventListener("click", function () { keyVerdict(1); });
btnNope.addEventListener("click", function () { keyVerdict(-1); });
function step(dt) {
if (phase === "exit") {
x += exitDir * Math.max(Math.abs(vx), RELEASE_VELOCITY_MIN * 1.3) * dt;
render();
if (Math.abs(x) > EXIT_PX) nextCard();
} else if (phase === "settle") {
x += (0 - x) * 0.22;
render();
if (Math.abs(x) < 0.4) { x = 0; phase = "idle"; render(); }
}
}
// .is-demo 자동 시연: 실제 pointer 없이 x·judge() 를 같은 경로로 호출한다.
var start = null, lastNow = 0, prevT = 0, synthPhase = "wait";
function synth(t) {
if (t > 0.45 && t < 0.75 && synthPhase === "wait") synthPhase = "drag";
if (synthPhase === "drag") {
var p = clamp((t - 0.45) / 0.3, 0, 1);
x = p * 130; render();
if (t >= 0.75) { synthPhase = "afterDrag"; judge(RELEASE_VELOCITY_MIN + 0.35, 1); }
}
if (t > 1.3 && t < 1.55 && synthPhase === "afterDrag") synthPhase = "drag2";
if (synthPhase === "drag2") {
var q = clamp((t - 1.3) / 0.25, 0, 1);
x = -q * 130; render();
if (t >= 1.55) { synthPhase = "done"; judge(-(RELEASE_VELOCITY_MIN + 0.35), -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);
})();// StackDepthPerspectiveSwipeCard — vanilla 판(run/422/demo/04-swipe-deck-precision-stack-depth-perspective/index.html) 의 React 포트.
// 값 하나: 뒤 카드 STACK_SIZE 장을 원근 투영(FOCAL)으로 축소·이동시켜 쌓고,
// 앞 카드가 빠지면 화가 알고리즘 순서(뒤→앞)로 한 칸씩 당겨 다시 그린다.
import { useEffect, useRef, useState } from "react";
import type { PointerEvent as ReactPointerEvent } from "react";
import styles from "./StackDepthPerspectiveSwipeCard.module.scss";
type Box<T> = { current: T };
const STACK_PERSPECTIVE_SCALE = 0.14;
const FOCAL = 260;
const STACK_SIZE = 3;
const RELEASE_VELOCITY_MIN = 0.4;
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 StackDepthPerspectiveSwipeCard() {
const frontRef = useRef<HTMLDivElement | null>(null);
const peekRefs = useRef<Array<HTMLDivElement | null>>([null, null, null]) as Box<Array<HTMLDivElement | 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(41)() * CARDS.length)) as Box<number>;
const frameRef = useRef<number>(0) as Box<number>;
const [front, setFront] = useState(CARDS[idxRef.current % CARDS.length]);
const [peeks, setPeeks] = useState<string[]>(
Array.from({ length: STACK_SIZE }, (_, i) => CARDS[(idxRef.current + i + 1) % CARDS.length])
);
const [status, setStatus] = useState("대기 중");
const [demo, setDemo] = useState(true);
const [reduce, setReduce] = useState(false);
function layoutStack(): void {
for (let i = 0; i < STACK_SIZE; i += 1) {
const el = peekRefs.current[i];
if (!el) continue;
const depth = i + 1;
const scale = FOCAL / (FOCAL + depth * STACK_PERSPECTIVE_SCALE * FOCAL);
const y = depth * STACK_PERSPECTIVE_SCALE * 22;
el.style.transform = "translateY(" + y.toFixed(1) + "px) scale(" + scale.toFixed(3) + ")";
el.style.zIndex = String(STACK_SIZE - i);
}
}
useEffect(() => { layoutStack(); }, []);
function render(): void {
const card = frontRef.current;
if (!card) return;
const rot = clamp(posRef.current * 0.05, -16, 16);
card.style.transform = "translateX(" + posRef.current.toFixed(1) + "px) rotate(" + rot.toFixed(2) + "deg)";
}
function nextCard(): void {
idxRef.current += 1;
setFront(CARDS[idxRef.current % CARDS.length]);
setPeeks(Array.from({ length: STACK_SIZE }, (_, i) => CARDS[(idxRef.current + i + 1) % CARDS.length]));
posRef.current = 0; velRef.current = 0; phaseRef.current = "idle";
render();
setStatus("대기 중");
}
function judge(velocity: number, dir: number): void {
setDemo(false);
const flung = Math.abs(velocity) >= RELEASE_VELOCITY_MIN;
if (reduce) {
if (flung) { setStatus(dir > 0 ? "좋아요 처리됨" : "싫어요 처리됨"); nextCard(); }
else { posRef.current = 0; render(); setStatus("제자리로 돌아옴"); phaseRef.current = "idle"; }
return;
}
if (flung) {
phaseRef.current = "exit"; exitDirRef.current = dir;
setStatus(dir > 0 ? "좋아요 처리됨" : "싫어요 처리됨");
} else {
phaseRef.current = "settle";
setStatus("제자리로 돌아옴");
}
}
function startDrag(clientX: number): void {
setDemo(false);
draggingRef.current = true; phaseRef.current = "idle";
startXRef.current = clientX; lastXRef.current = clientX; lastTRef.current = performance.now(); velRef.current = 0;
}
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;
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, 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): void {
setDemo(false);
posRef.current = dir * 40; render();
judge(dir * (RELEASE_VELOCITY_MIN + 0.2), dir);
}
function onKeyDown(e: any): void {
if (e.key === "ArrowRight") { e.preventDefault(); keyVerdict(1); }
else if (e.key === "ArrowLeft") { e.preventDefault(); keyVerdict(-1); }
}
function step(dt: number): void {
if (phaseRef.current === "exit") {
const speed = Math.max(Math.abs(velRef.current), RELEASE_VELOCITY_MIN * 1.4);
posRef.current += exitDirRef.current * speed * dt;
render();
if (Math.abs(posRef.current) > EXIT_PX) nextCard();
} else if (phaseRef.current === "settle") {
posRef.current += (0 - posRef.current) * 0.22;
render();
if (Math.abs(posRef.current) < 0.5) { posRef.current = 0; phaseRef.current = "idle"; render(); }
}
}
function synth(t: number, synthPhaseRef: Box<string>): void {
if (t > 0.4 && t < 0.7 && synthPhaseRef.current === "wait") synthPhaseRef.current = "drop";
if (synthPhaseRef.current === "drop") {
const p = clamp((t - 0.4) / 0.3, 0, 1);
posRef.current = p * 90; render();
if (t >= 0.7) { synthPhaseRef.current = "afterDrop"; judge(RELEASE_VELOCITY_MIN + 0.3, 1); }
}
if (t > 1.3 && t < 1.6 && synthPhaseRef.current === "afterDrop") synthPhaseRef.current = "drop2";
if (synthPhaseRef.current === "drop2") {
const q = clamp((t - 1.3) / 0.3, 0, 1);
posRef.current = -q * 90; render();
if (t >= 1.6) { synthPhaseRef.current = "done"; judge(-(RELEASE_VELOCITY_MIN + 0.3), -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.sd}>
<p className={styles.caption}>원근 투영으로 쌓이는 카드 더미</p>
<div className={styles.scene}>
{peeks.map((txt, i) => (
<div
className={styles.peek}
key={i}
ref={(el: HTMLDivElement | null) => { peekRefs.current[i] = el; }}
aria-hidden="true"
>
<p className={styles.label}>{txt}</p>
</div>
))}
<div
className={styles.card}
ref={frontRef}
tabIndex={0}
role="group"
aria-roledescription="스와이프 카드"
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={onPointerUp}
onKeyDown={onKeyDown}
>
<p className={styles.label}>{front}</p>
</div>
<button className={styles.btnNope} type="button" aria-label="싫어요" onClick={() => keyVerdict(-1)}>✕</button>
<button className={styles.btnLike} type="button" aria-label="좋아요" onClick={() => keyVerdict(1)}>♥</button>
</div>
<p className={styles.status} aria-live="polite">{status}</p>
</div>
</main>
);
}04 遠近投影で積み重なるカードスタック — 計測 累積面積 48.063% · 動いたフレーム 6/23GODRICH オリジナル · SCSS と React は zip に同梱 · カード スワイプ ui 9パターン — 物理計算で仕上げる
このデモが属する記事
カード スワイプ ui 9パターン — 物理計算で仕上げるこのカード スワイプ ui には9パターンあります。指を離す速度が02番の基準に届かない瞬間、カードは飛ばずに03番のようにばねで元の位置へ戻る。最後の一枚をめくった先には08番の空のデッキだけが残る。 この記事のデモをすべて見る


