インタラクティブな壁紙

このチュートリアルでは、useMousePosition フックを使ってマウスカーソルに反応する壁紙を作ります。

前提条件

先にはじめようチュートリアルを完了してください。

マウストラッキングの追加

src/main.tsx の内容を置き換えます。

src/main.tsx
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { useMousePosition } from "@fluxlay/react";
 
function Wallpaper() {
  const { x, y } = useMousePosition();
  const px = ((x + 1) / 2) * window.innerWidth;
  const py = (1 - (y + 1) / 2) * window.innerHeight;
 
  return (
    <main
      style={{
        height: "100vh",
        width: "100vw",
        backgroundColor: "#0f0f23",
        overflow: "hidden",
        position: "relative"
      }}
    >
      <div
        style={{
          position: "absolute",
          left: px,
          top: py,
          width: 40,
          height: 40,
          borderRadius: "50%",
          backgroundColor: "#6366f1",
          transform: "translate(-50%, -50%)",
          transition: "left 0.1s ease-out, top 0.1s ease-out",
          boxShadow: "0 0 30px 10px rgba(99, 102, 241, 0.4)"
        }}
      />
    </main>
  );
}
 
createRoot(document.getElementById("root")!).render(
  <StrictMode>
    <Wallpaper />
  </StrictMode>
);

開発サーバーを起動してマウスを動かすと、光る円がカーソルを追いかけます。

pnpm fluxlay dev

座標系について

useMousePosition()壁紙ウィンドウに対して正規化された座標を返します。xy は両方とも -11 の範囲で、Y 軸は数学的(+1 が上端、-1 が下端)です。CSS は上が負なので逆向きになります。ピクセルとして扱う前に ((x + 1) / 2) * window.innerWidth(1 - (y + 1) / 2) * window.innerHeight で変換してください。

アニメーションライブラリの活用

より滑らかなアニメーションには、@react-spring/web のようなライブラリを使えます。

pnpm add @react-spring/web
src/main.tsx
import { useSpring, animated } from "@react-spring/web";
import { useMousePosition } from "@fluxlay/react";
 
function Wallpaper() {
  const { x, y } = useMousePosition();
  const px = ((x + 1) / 2) * window.innerWidth;
  const py = (1 - (y + 1) / 2) * window.innerHeight;
  const spring = useSpring({ to: { x: px, y: py }, config: { tension: 120, friction: 14 } });
 
  return (
    <main style={{ height: "100vh", width: "100vw", backgroundColor: "#0f0f23" }}>
      <animated.div
        style={{
          position: "absolute",
          left: spring.x,
          top: spring.y,
          width: 40,
          height: 40,
          borderRadius: "50%",
          backgroundColor: "#6366f1",
          transform: "translate(-50%, -50%)"
        }}
      />
    </main>
  );
}

次のステップ

タスクごとの詳しいガイド:

別のチュートリアル:

API リファレンス: