Hi! I'm HIGASHIYUKI® Art Director | Photo & Videographer | Web Engineer

配色

音楽

Lo-Fi #001by ST®AND.(音源のサイト。新しいタブで開きます)

ジャンル

カーソル

カーソルにぶら下がり、商品写真の上で裏返るタグ

デモ

操作:カーソルを動かす・カーソルを重ねる。「さわってみる」を押すと自動再生が止まり、マウスで動かせます。

仕様

用途
カーソル
動作
DOM
種類
レシピ
動作確認
three 0.186.0・gsap 3.15.0
公開日

しくみと調整

カーソルの小さな点から、1枚のタグを紐で吊るしました。カーソルをさっと動かすとタグが大きく振れ、手を止めたあとも余韻を残してしばらく揺れ続けます。そのまま商品写真にカーソルを合わせると、タグがくるりと裏返って、通常の商品なら「VIEW」、セール品なら赤い「SALE」の文字が現れます。

紐は6つの区間に分けており、前のコマからの移動量をもとに次の位置を求め、そこに重力を加える「Verlet積分」という物理計算で動かしています。隣り合う点が離れすぎたら元の長さに戻す計算を数回繰り返す一方で、点どうしが近づく分には制限をかけていません。そのため、カーソルを急に止めてもタグが勢いのまま前へ進み、紐がふわっとたるむような自然な動きが生まれます。紐の描画には、滑らかな曲線(Catmull-Rom曲線)を3次ベジェ曲線に変換したSVGの path を使っています。

タグの傾きは、紐を通す穴と重心の位置関係で決まります。紐に引かれた穴が先に動き、重心が少し遅れてついてくるので、穴を支点にして振り子のように振れて見えます。裏返る動きには余弦(cos)を使い、0.5秒かけて横幅をいったん0まで縮めてから再び広げています。幅が0になって真横を向いた瞬間に文字と色を差し替えれば、切り替わる瞬間が見えません。さらに、商品写真からカーソルが離れても0.15秒間は表示を戻さないようにして、隣の写真へ移る途中で文字がちらつくのを防いでいます。

重力の強さを決める GRAVITY を上げると揺れの往復が速くなり、軽くて小ぶりなタグに見えます。減衰率の DAMPING を下げると揺れが早く収まり、上げると余韻が長く残ります。端末で「動きを減らす」設定が有効になっているときは、紐をまっすぐ垂らしたまま文字だけを切り替えるようにしました。キーボードで商品写真を選んだときも、その写真の上に同じタグが表示されます。

コード

HTML
<section class="shop" aria-labelledby="shop-title">
  <p class="shop__label">NEW ARRIVALS</p>
  <h2 class="shop__title" id="shop-title">新しく入荷したうつわ</h2>
  <ul class="shop__grid">
    <li>
      <!-- data-tag はタグに表示する文言、data-tag-tone はタグの色(無ければ view) -->
      <a class="shop__card" href="/items/hakuji-bowl/" data-tag="VIEW">
        <img src="/img/hakuji-bowl.jpg" alt="" width="508" height="580">
        <span class="shop__name">白磁の飯碗</span>
        <span class="shop__price">¥3,300</span>
      </a>
    </li>
    <li>
      <a class="shop__card" href="/items/kaiyu-dish/" data-tag="VIEW">
        <img src="/img/kaiyu-dish.jpg" alt="" width="508" height="580">
        <span class="shop__name">灰釉の小鉢</span>
        <span class="shop__price">¥2,640</span>
      </a>
    </li>
    <li>
      <a class="shop__card" href="/items/kohiki-mug/" data-tag="SALE" data-tag-tone="sale">
        <img src="/img/kohiki-mug.jpg" alt="" width="508" height="580">
        <span class="shop__badge">SALE</span>
        <span class="shop__name">粉引のマグカップ</span>
        <span class="shop__price is-sale">¥2,970 <s>¥3,960</s></span>
      </a>
    </li>
    <li>
      <a class="shop__card" href="/items/ai-plate/" data-tag="VIEW">
        <img src="/img/ai-plate.jpg" alt="" width="508" height="580">
        <span class="shop__name">藍の豆皿</span>
        <span class="shop__price">¥1,650</span>
      </a>
    </li>
  </ul>
</section>

<!-- カーソル: 紐・タグ・点。タグの座標の原点は穴の中心 -->
<svg class="hang-tag" aria-hidden="true">
  <g class="hang-tag__tag">
    <path class="hang-tag__shape" fill-rule="evenodd" d="M-24 -16H24L42 2V96H-42V2Z M-6 0a6 6 0 1 0 12 0a6 6 0 1 0 -12 0Z" />
    <circle class="hang-tag__ring" r="9" />
    <rect class="hang-tag__stitch" x="-34" y="20" width="68" height="68" rx="3" />
    <text class="hang-tag__word" x="1.2" y="61" text-anchor="middle"></text>
  </g>
  <path class="hang-tag__string" />
  <circle class="hang-tag__dot" r="6" />
</svg>

CSS
.shop { max-width: 1088px; margin: 0 auto; padding: 64px 24px; color: #262626; }
.shop__label { margin: 0 0 14px; font-size: 12px; font-weight: 700; letter-spacing: 0.14em; }
.shop__title { margin: 0 0 48px; font-size: clamp(28px, 5vw, 44px); font-weight: 800; line-height: 1.1; letter-spacing: -0.02em; }
.shop__label, .shop__price, .shop__price s { color: #6b6b6b; font-variant-numeric: tabular-nums; }
.shop__price { font-size: 14px; }
.shop__price.is-sale { color: #a8432d; }
.shop__name { display: block; margin: 16px 0 4px; font-size: clamp(16px, 4vw, 20px); font-weight: 700; }

.shop__grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(min(200px, 36vw), 1fr));
  gap: 24px;
  margin: 0;
  padding: 0;
  list-style: none;
}

.shop__card { position: relative; display: block; color: inherit; text-decoration: none; }
.shop__card:focus-visible { outline: 2px solid currentColor; outline-offset: 4px; }

.shop__card img {
  display: block;
  width: 100%;
  height: auto;
  aspect-ratio: 254 / 290;
  object-fit: cover;
  border-radius: 4px;
  background: #e4e2dc;
}

.shop__badge {
  position: absolute;
  left: 16px;
  top: 16px;
  padding: 6px 10px 6px 12px;
  border-radius: 999px;
  background: #a8432d;
  color: #fff;
  font-size: 12px;
  font-weight: 700;
  line-height: 1;
  letter-spacing: 0.14em;
}

/* 紐の長さと、タグの穴から重心までの距離(px)。JS が読む */
.hang-tag {
  --string: 80;
  --drop: 44;
  position: fixed;
  inset: 0;
  z-index: 9999;
  width: 100%;
  height: 100%;
  pointer-events: none;
  opacity: 0;
  transition: opacity 0.3s;
}

/* ポインタが画面に入ったら表示し、本物のカーソルを隠す */
.has-hang-tag .hang-tag { opacity: 1; }
.has-hang-tag, .has-hang-tag a { cursor: none; }

/* タグの色。カードの data-tag-tone に合わせて、JS が data-tone を付け替える */
.hang-tag__tag {
  --fill: #bd894c;
  --word: #262626;
  --line: rgba(38, 38, 38, 0.32);
}

.hang-tag__tag[data-tone="view"] {
  --fill: #262626;
  --word: #fff;
  --line: rgba(255, 255, 255, 0.34);
}

.hang-tag__tag[data-tone="sale"] {
  --fill: #a8432d;
  --word: #fff;
  --line: rgba(255, 255, 255, 0.42);
}

.hang-tag__shape { fill: var(--fill); }
.hang-tag__ring { fill: none; stroke: var(--line); stroke-width: 2.5; }
.hang-tag__stitch { fill: none; stroke: var(--line); stroke-width: 1.5; stroke-dasharray: 4 4; }
.hang-tag__word { fill: var(--word); font-size: 20px; font-weight: 800; letter-spacing: 0.12em; }
.hang-tag__string { fill: none; stroke: #262626; stroke-width: 2; stroke-linecap: round; }
.hang-tag__dot { fill: #262626; stroke: #fff; stroke-width: 2; }

@media (prefers-reduced-motion: reduce) {
  .hang-tag { transition: none; }
}

JavaScript
import { gsap } from "gsap";

const svg = document.querySelector(".hang-tag");
// タッチ端末にはポインタが無いので、タグは表示せず本物のカーソルのままにする
const canHover = window.matchMedia("(hover: hover) and (pointer: fine)").matches;
const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;

if (svg && canHover) {
  // 1 ステップの秒数・紐を分ける数・重力(px/秒²)・1 ステップで残す速さ・タグが返る秒数
  const STEP = 1 / 120, SEGMENTS = 6, GRAVITY = 5200, DAMPING = 0.982, FLIP = 0.5;
  const [tag, word, string, dot] = ["__tag", "__word", "__string", "__dot"].map((s) => svg.querySelector(`.hang-tag${s}`));
  const css = getComputedStyle(svg);
  const rest = [...Array(SEGMENTS).fill(parseFloat(css.getPropertyValue("--string")) / SEGMENTS), parseFloat(css.getPropertyValue("--drop"))];
  // 紐とタグを動かす点ごとの重さの逆数。端(ポインタ)は 0 で動かず、紐は軽く、タグの穴は少し重く、重心はいちばん重い
  const inv = [0, 1, 1, 1, 1, 1, 0.5, 0.2];
  const count = inv.length, pos = new Float64Array(count * 2), prev = new Float64Array(count * 2);
  const blank = { text: "", tone: "" }, aim = { x: 0, y: 0 }, from = { x: 0, y: 0 };
  let shown = blank, want = blank, flip = 1, acc = 0, ready = false, wait;

  // 紐をまっすぐ下げた静止の形で、ポインタの位置に置く
  const hang = (x, y) => {
    for (let i = 0, depth = 0; i < count; depth += rest[i++]) [pos[2 * i], pos[2 * i + 1], prev[2 * i], prev[2 * i + 1]] = [x, y + depth, x, y + depth];
    Object.assign(from, { x, y });
  };

  // 1 ステップ進める: 前の位置との差を速さにして重力を足し、隣どうしの長さを直す(Verlet 積分)
  const step = (ax, ay) => {
    [pos[0], pos[1], prev[0], prev[1]] = [ax, ay, ax, ay];
    for (let i = 2; i < count * 2; i++) [pos[i], prev[i]] = [pos[i] + (pos[i] - prev[i]) * DAMPING + (i % 2 ? GRAVITY * STEP * STEP : 0), pos[i]];
    for (let k = 0; k < 16 * (count - 1); k++) {
      const i = k % (count - 1), a = 2 * i, b = a + 2, dx = pos[b] - pos[a], dy = pos[b + 1] - pos[a + 1], d = Math.hypot(dx, dy) || 1e-6;
      // 紐は伸びたときだけ引き戻す(急に止めるとたるむ)。タグの穴と重心のあいだは硬い棒
      if (i < SEGMENTS && d <= rest[i]) continue;
      const s = (d - rest[i]) / d / (inv[i] + inv[i + 1]);
      [pos[a], pos[a + 1], pos[b], pos[b + 1]] = [pos[a] + dx * s * inv[i], pos[a + 1] + dy * s * inv[i], pos[b] - dx * s * inv[i + 1], pos[b + 1] - dy * s * inv[i + 1]];
    }
  };

  // 紐は各点を通る曲線(Catmull-Rom を 3 次ベジェに直したもの)。タグは穴の位置に置き、穴から重心への向きで傾ける
  const ease = gsap.parseEase("power2.inOut");
  const p = (i) => [pos[2 * i], pos[2 * i + 1]];
  const draw = () => {
    let d = `M${p(0)}`;
    for (let i = 0; i < SEGMENTS; i++) {
      const [a, b, c, e] = [p(Math.max(i - 1, 0)), p(i), p(i + 1), p(Math.min(i + 2, SEGMENTS))];
      d += `C${b[0] + (c[0] - a[0]) / 6},${b[1] + (c[1] - a[1]) / 6} ${c[0] - (e[0] - b[0]) / 6},${c[1] - (e[1] - b[1]) / 6} ${c}`;
    }
    const [[hx, hy], [cx, cy]] = [p(SEGMENTS), p(SEGMENTS + 1)];
    // 返る動きは横幅を cos で 0 まで縮めて戻す。0 になった瞬間に文言と色を替える
    const scale = Math.max(0.001, Math.abs(Math.cos(Math.PI * ease(flip))));
    string.setAttribute("d", d);
    tag.setAttribute("transform", `translate(${hx} ${hy}) rotate(${(Math.atan2(hx - cx, cy - hy) * 180) / Math.PI}) scale(${scale} 1)`);
    dot.setAttribute("transform", `translate(${pos[0]} ${pos[1]})`);
    if (word.textContent !== shown.text) word.textContent = shown.text;
    tag.dataset.tone = shown.tone;
  };
  gsap.ticker.add((time, deltaMs) => {
    if (!ready) return;
    const dt = Math.min(deltaMs, 100) / 1000;
    // 1 フレームのあいだのポインタの動きを、ステップごとに少しずつ進める。動きを減らす設定では揺らさない
    const steps = Math.floor((acc += dt) / STEP);
    if (reduceMotion) hang(aim.x, aim.y);
    else for (let s = 1; s <= steps; s++) step(from.x + ((aim.x - from.x) * s) / steps, from.y + ((aim.y - from.y) * s) / steps);
    acc -= steps * STEP;
    if (steps > 0) Object.assign(from, aim);
    // 返る途中に行き先が替わったら、閉じる途中ならそのまま、開く途中なら同じ幅から閉じ直す
    if (shown.text !== want.text || flip < 1) {
      if (flip >= 1) flip = 0;
      else if (flip >= 0.5 && shown.text !== want.text) flip = 1 - flip;
      flip = reduceMotion ? 1 : Math.min(1, flip + dt / FLIP);
      if (flip >= 0.5) shown = want;
    }
    draw();
  });

  // 画面に入ったら紐をまっすぐ下げた形で表示し、画面から出たら隠す
  const show = (x, y) => {
    Object.assign(aim, { x, y });
    if (!ready) hang(x, y);
    document.documentElement.classList.toggle("has-hang-tag", (ready = true));
  };
  window.addEventListener("pointermove", (e) => show(e.clientX, e.clientY));
  document.documentElement.addEventListener("pointerleave", () => document.documentElement.classList.toggle("has-hang-tag", (ready = false)));

  document.querySelectorAll("[data-tag]").forEach((card) => {
    const target = { text: card.dataset.tag, tone: card.dataset.tagTone || "view" };
    const enter = () => (wait?.kill(), (want = target));
    // 隣のカードへ渡るとき、隙間で文字の無いタグへ返りかけないよう少し待つ
    const leave = () => (wait?.kill(), (wait = gsap.delayedCall(0.15, () => (want = blank))));
    [["pointerenter", enter], ["pointerleave", leave], ["blur", leave]].forEach(([type, fn]) => card.addEventListener(type, fn));
    // キーボードでフォーカスを移したときは、カードの上にタグを下げて同じ見た目にする
    card.addEventListener("focus", () => {
      if (!card.matches(":focus-visible")) return;
      const r = card.getBoundingClientRect();
      show(r.left + r.width / 2, r.top + r.height * 0.25);
      enter();
    });
  });
}

カーソルをすべて見る