スワイプ(方向・速度判定)

検知閾値・速度計算・方向ロックのアルゴリズムを主要ライブラリで比較

💻 PC でご覧の方へ:3ライブラリともマウスドラッグに対応。スクロール競合・方向ロック感度などタッチ特有の挙動はスマートフォンで確認できます。
@use-gesture/react

読み込み中...

tsx
'use client';
import { useState } from 'react';
import { useSwipeable } from 'react-swipeable';

const COLORS = ['bg-violet-500', 'bg-rose-500', 'bg-emerald-500', 'bg-amber-500'];
const LABELS = ['パネル 1', 'パネル 2', 'パネル 3', 'パネル 4'];

export function UseGestureSwipeDemo() {
  const [index, setIndex] = useState(0);
  const [dir, setDir] = useState('');

  const bind = useSwipe(
    ({ swipedLeft, swipedRight, velocity }) => {
      if (velocity[0] < 0.3) return;
      if (swipedLeft) { setDir('←'); setIndex(i => Math.min(i + 1, COLORS.length - 1)); }
      if (swipedRight) { setDir('→'); setIndex(i => Math.max(i - 1, 0)); }
    }
  );

  return (
    <div className="overflow-hidden rounded-lg" style={{ touchAction: 'pan-y' }}>
      <div
        {...bind()}
        className={`h-48 flex items-center justify-center text-white font-bold text-xl rounded-lg transition-colors ${COLORS[index]}`}
      >
        {LABELS[index]} {dir && <span className="ml-2 text-base opacity-70">{dir}</span>}
      </div>
      <p className="text-center text-xs text-gray-400 mt-2">左右スワイプでパネルを切り替え</p>
    </div>
  );
}

アルゴリズム比較表

項目@use-gesture/reactreact-swipeableFramer Motion
検知閾値threshold オプション(px 指定)delta オプション(デフォルト 10px)専用オプションなし(即時認識)
速度の単位px/ms(ドラッグ中リアルタイム)px/ms(onSwiped 完了時のみ)px/s(onDrag / onDragEnd)
速度計算手法EMA(指数移動平均)で平滑化距離 ÷ 経過時間(シンプル)スプリング物理エンジン内で算出
方向ロックaxis: 'lock' で自動固定なし(後処理で direction 判定)dragDirectionLock prop
方向判定タイミングドラッグ開始後、支配軸が確定次第onSwiped 完了後(Left/Right/Up/Down)ドラッグ開始直後に即時固定

⚠️ iOS Safari での注意点

  • • ドラッグ要素に touch-action: none が必須(ページスクロールとの競合回避)
  • react-swipeablepreventScrollOnSwipe: true を必ず指定
  • • Framer Motion は内部で touch-action: none を付与するため追加設定不要
  • • 方向ロック後のスクロール挙動は iOS が独自に制御する部分があり、ライブラリだけでは完全制御できないケースがある

🤖 AIプロンプトテンプレート

Reactでスワイプ(方向・速度判定)を実装してください。以下の要件を満たしてください。

- @use-gesture/react、react-swipeable、またはFramer Motionのいずれかを使用すること
- 左・右・上・下の4方向のスワイプを検知できること
- スワイプの検知閾値(距離px)と速度閾値(px/ms)を設定できること
- 水平または垂直方向への方向ロック(directionLock)を実装し、軸が確定したら反対軸を無視すること
- スワイプ結果(方向・速度・距離)をリアルタイムに画面上に表示すること
- iOS SafariでページスクロールとのEventの競合を避ける設定(preventScrollOnSwipeなど)を適切に実装すること

⚠️ このプロンプトはあくまでたたき台です。AIの回答はモデルやバージョン、会話の文脈によって毎回異なります。意図通りに動かない場合は、条件を追記・修正してお使いください。