02離す速度で分かれるスワイプ判定
離す瞬間の速度が基準値に届かないと、カードは飛んでいかない。
使いどころマッチングアプリのカードめくり
FLING_VELOCITY_MINSWIPE_ROTATE_LERP_RATIOINERTIA_DECAY

<main class="stage">
<div class="vf is-demo" id="vf">
<p class="vf__caption">離す速度で分かれるスワイプ判定</p>
<div class="vf__scene" id="vfScene">
<div class="vf__card" id="vfCard" tabindex="0" role="group" aria-roledescription="スワイプカード">
<p class="vf__label" id="vfLabel">夕方の散歩</p>
<p class="vf__hint" id="vfHint">速度 0.00 px/ms</p>
</div>
<button class="vf__btn vf__btn--nope" id="vfNope" type="button" aria-label="いいえ">✕</button>
<button class="vf__btn vf__btn--like" id="vfLike" type="button" aria-label="いいね">♥</button>
</div>
<p class="vf__status" id="vfStatus" aria-live="polite">待機中</p>
</div>
</main>@use "../../../../site/static/demo-tokens" as *;
// 값 하나: 놓는 순간 속도(px/ms)가 FLING_VELOCITY_MIN 을 넘지 못하면 카드는 날아가지 않는다.
// 드래그 중에는 SWIPE_ROTATE_LERP_RATIO(px 당 도) 만큼 살짝 기운다.
$duration: $dur-base;
$easing: $ease-out;
$color: $subject-orange-deep;
@include stage($stage-yellow);
.vf { display: grid; gap: $sp-2; justify-items: center; width: 100%; }
.vf__caption { margin: 0; font-size: 12px; font-weight: 600; color: $subject-ink; }
.vf__scene {
position: relative;
width: 220px;
height: 190px;
border-radius: $r-card;
background: $subject-cream;
display: grid;
place-items: center;
overflow: hidden;
}
.vf__card {
position: relative;
width: 160px;
height: 180px;
border-radius: $r-card;
background: linear-gradient(160deg, $stage-orange, #e6d6cb);
box-shadow: $shadow-raised;
display: grid;
gap: $sp-2;
place-items: center;
touch-action: none;
cursor: grab;
will-change: transform;
}
.vf__card:active { cursor: grabbing; }
.vf__card:focus-visible { outline: 2px solid $subject-blue-light; outline-offset: 3px; }
.vf__label { margin: 0; font-size: 14px; font-weight: 700; color: $subject-ink; padding: 0 $sp-3; text-align: center; }
.vf__hint { margin: 0; font-size: 10px; color: $subject-ink; opacity: .8; }
.vf__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;
}
.vf__btn--nope { left: $sp-3; color: $error; }
.vf__btn--like { right: $sp-3; color: $subject-orange-deep; }
.vf__btn:focus-visible { outline: 2px solid $subject-blue-light; outline-offset: 2px; }
.vf__status { margin: 0; font-size: 11px; color: $subject-ink; font-weight: 600; }
@media (max-width: 340px) {
.vf { gap: $sp-2; }
.vf__scene { width: 150px; height: 108px; }
.vf__card { width: 78px; height: 92px; gap: $sp-1; }
.vf__label { font-size: 10px; padding: 0 $sp-1; }
.vf__hint { display: none; }
.vf__btn { width: 22px; height: 22px; font-size: 11px; bottom: $sp-1; }
.vf__btn--nope { left: $sp-1; }
.vf__btn--like { right: $sp-1; }
}
@media (prefers-reduced-motion: reduce) {
.vf__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: #ffd23f;
font-family: -apple-system, "Segoe UI", "Noto Sans KR", sans-serif;
padding: clamp(8px, 4vw, 24px);
}
.vf {
display: grid;
gap: 8px;
justify-items: center;
width: 100%;
}
.vf__caption {
margin: 0;
font-size: 12px;
font-weight: 600;
color: #17141a;
}
.vf__scene {
position: relative;
width: 220px;
height: 190px;
border-radius: 16px;
background: #fff7e6;
display: grid;
place-items: center;
overflow: hidden;
}
.vf__card {
position: relative;
width: 160px;
height: 180px;
border-radius: 16px;
background: linear-gradient(160deg, #ff4d1f, #e6d6cb);
box-shadow: 0 14px 24px rgba(23, 20, 26, 0.32);
display: grid;
gap: 8px;
place-items: center;
touch-action: none;
cursor: grab;
will-change: transform;
}
.vf__card:active {
cursor: grabbing;
}
.vf__card:focus-visible {
outline: 2px solid #5b8cf8;
outline-offset: 3px;
}
.vf__label {
margin: 0;
font-size: 14px;
font-weight: 700;
color: #17141a;
padding: 0 12px;
text-align: center;
}
.vf__hint {
margin: 0;
font-size: 10px;
color: #17141a;
opacity: 0.8;
}
.vf__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;
}
.vf__btn--nope {
left: 12px;
color: #c2361a;
}
.vf__btn--like {
right: 12px;
color: #c93000;
}
.vf__btn:focus-visible {
outline: 2px solid #5b8cf8;
outline-offset: 2px;
}
.vf__status {
margin: 0;
font-size: 11px;
color: #17141a;
font-weight: 600;
}
@media (max-width: 340px) {
.vf {
gap: 8px;
}
.vf__scene {
width: 150px;
height: 108px;
}
.vf__card {
width: 78px;
height: 92px;
gap: 4px;
}
.vf__label {
font-size: 10px;
padding: 0 4px;
}
.vf__hint {
display: none;
}
.vf__btn {
width: 22px;
height: 22px;
font-size: 11px;
bottom: 4px;
}
.vf__btn--nope {
left: 4px;
}
.vf__btn--like {
right: 4px;
}
}
@media (prefers-reduced-motion: reduce) {
.vf__card {
transition: none;
}
}(function () {
"use strict";
// 변형 3: 02 폴더에 SWIPE_ROTATE_LERP_RATIO 를 실재시킨다 — 드래그 중 카드가 이 비율로 살짝 기운다.
var SWIPE_ROTATE_LERP_RATIO = 0.05; // deg per px
var ROTATE_MAX_DEG = 14;
// 값 하나: 놓는 순간의 速度(px/ms)가 이 값을 넘지 못하면 카드는 날아가지 않는다.
var FLING_VELOCITY_MIN = 0.42;
var INERTIA_DECAY = 0.85;
var SETTLE_RATE = 0.2;
var EXIT_PX = 320;
var CYCLE_S = 2;
var root = document.getElementById("vf");
var card = document.getElementById("vfCard");
var label = document.getElementById("vfLabel");
var hint = document.getElementById("vfHint");
var status = document.getElementById("vfStatus");
var btnLike = document.getElementById("vfLike");
var btnNope = document.getElementById("vfNope");
var reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
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(23);
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 * SWIPE_ROTATE_LERP_RATIO, -ROTATE_MAX_DEG, ROTATE_MAX_DEG);
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");
hint.textContent = "速度 " + Math.abs(velocity).toFixed(2) + " px/ms";
var flung = Math.abs(velocity) >= FLING_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;
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 * 40; render();
judge(dir * (FLING_VELOCITY_MIN + 0.15), 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") {
var speed = Math.max(Math.abs(vx), FLING_VELOCITY_MIN * 1.4);
x += exitDir * speed * dt;
render();
if (Math.abs(x) > EXIT_PX) nextCard();
} else if (phase === "settle") {
x += vx * dt;
vx *= INERTIA_DECAY;
x += (0 - x) * SETTLE_RATE;
render();
if (Math.abs(x) < 0.5 && Math.abs(vx) < 0.01) { 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.7 && synthPhase === "wait") synthPhase = "weak";
if (synthPhase === "weak") {
var p = clamp((t - 0.45) / 0.25, 0, 1);
x = p * 30; render();
if (t >= 0.7) { synthPhase = "afterWeak"; judge(0.15, 1); }
}
if (t > 1.05 && t < 1.35 && synthPhase === "afterWeak") synthPhase = "strong";
if (synthPhase === "strong") {
var q = clamp((t - 1.05) / 0.3, 0, 1);
x = q * 130; render();
if (t >= 1.35) { synthPhase = "done"; judge(FLING_VELOCITY_MIN + 0.5, 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);
})();// VelocityFlingThresholdSwipeCard — vanilla 판(run/422/demo/02-swipe-deck-precision-velocity-fling-threshold/index.html) 의 React 포트.
// 값 하나: 놓는 순간 속도(px/ms) 가 FLING_VELOCITY_MIN 을 넘지 못하면 카드는 날아가지 않는다.
// 드래그 중에는 SWIPE_ROTATE_LERP_RATIO(px 당 도) 만큼 살짝 기운다.
import { useEffect, useRef, useState } from "react";
import type { PointerEvent as ReactPointerEvent } from "react";
import styles from "./VelocityFlingThresholdSwipeCard.module.scss";
type Box<T> = { current: T };
const SWIPE_ROTATE_LERP_RATIO = 0.05;
const ROTATE_MAX_DEG = 14;
const FLING_VELOCITY_MIN = 0.42;
const INERTIA_DECAY = 0.85;
const SETTLE_RATE = 0.2;
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 VelocityFlingThresholdSwipeCard() {
const cardRef = useRef<HTMLDivElement | null>(null);
const xRef = useRef<number>(0) as Box<number>;
const vxRef = 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(23)() * CARDS.length)) as Box<number>;
const frameRef = useRef<number>(0) as Box<number>;
const [label, setLabel] = useState(CARDS[idxRef.current % CARDS.length]);
const [hint, setHint] = useState("속도 0.00 px/ms");
const [status, setStatus] = useState("대기 중");
const [demo, setDemo] = useState(true);
const [reduce, setReduce] = useState(false);
function render(): void {
const card = cardRef.current;
if (!card) return;
const rot = clamp(xRef.current * SWIPE_ROTATE_LERP_RATIO, -ROTATE_MAX_DEG, ROTATE_MAX_DEG);
card.style.transform = "translateX(" + xRef.current.toFixed(1) + "px) rotate(" + rot.toFixed(2) + "deg)";
}
function nextCard(): void {
idxRef.current += 1;
setLabel(CARDS[idxRef.current % CARDS.length]);
xRef.current = 0; vxRef.current = 0; phaseRef.current = "idle";
render();
setStatus("대기 중");
}
function judge(velocity: number, dir: number): void {
setDemo(false);
setHint("속도 " + Math.abs(velocity).toFixed(2) + " px/ms");
const flung = Math.abs(velocity) >= FLING_VELOCITY_MIN;
if (reduce) {
if (flung) { setStatus(dir > 0 ? "좋아요 처리됨" : "싫어요 처리됨"); nextCard(); }
else { xRef.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;
startXRef.current = clientX; lastXRef.current = clientX; lastTRef.current = performance.now(); vxRef.current = 0;
}
function moveDrag(clientX: number): void {
if (!draggingRef.current) return;
const now = performance.now();
const dt = Math.max(now - lastTRef.current, 1);
vxRef.current = (clientX - lastXRef.current) / dt;
lastXRef.current = clientX; lastTRef.current = now;
xRef.current = clientX - startXRef.current;
render();
}
function endDrag(): void {
if (!draggingRef.current) return;
draggingRef.current = false;
judge(vxRef.current, xRef.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);
xRef.current = dir * 40; render();
judge(dir * (FLING_VELOCITY_MIN + 0.15), 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(vxRef.current), FLING_VELOCITY_MIN * 1.4);
xRef.current += exitDirRef.current * speed * dt;
render();
if (Math.abs(xRef.current) > EXIT_PX) nextCard();
} else if (phaseRef.current === "settle") {
xRef.current += vxRef.current * dt;
vxRef.current *= INERTIA_DECAY;
xRef.current += (0 - xRef.current) * SETTLE_RATE;
render();
if (Math.abs(xRef.current) < 0.5 && Math.abs(vxRef.current) < 0.01) { xRef.current = 0; phaseRef.current = "idle"; render(); }
}
}
function synth(t: number, synthPhaseRef: Box<string>): void {
if (t > 0.45 && t < 0.7 && synthPhaseRef.current === "wait") synthPhaseRef.current = "weak";
if (synthPhaseRef.current === "weak") {
const p = clamp((t - 0.45) / 0.25, 0, 1);
xRef.current = p * 30; render();
if (t >= 0.7) { synthPhaseRef.current = "afterWeak"; judge(0.15, 1); }
}
if (t > 1.05 && t < 1.35 && synthPhaseRef.current === "afterWeak") synthPhaseRef.current = "strong";
if (synthPhaseRef.current === "strong") {
const q = clamp((t - 1.05) / 0.3, 0, 1);
xRef.current = q * 130; render();
if (t >= 1.35) { synthPhaseRef.current = "done"; judge(FLING_VELOCITY_MIN + 0.5, 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.vf}>
<p className={styles.caption}>놓는 속도로 갈리는 스와이프 판정</p>
<div className={styles.scene}>
<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>
<p className={styles.hint}>{hint}</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>
);
}02 離す速度で分かれるスワイプ判定 — 計測 累積面積 8.493% · 動いたフレーム 6/23GODRICH オリジナル · SCSS と React は zip に同梱 · カード スワイプ ui 9パターン — 物理計算で仕上げる
このデモが属する記事
カード スワイプ ui 9パターン — 物理計算で仕上げるこのカード スワイプ ui には9パターンあります。指を離す速度が02番の基準に届かない瞬間、カードは飛ばずに03番のようにばねで元の位置へ戻る。最後の一枚をめくった先には08番の空のデッキだけが残る。 この記事のデモをすべて見る


