マウス位置の取得

useMousePosition() はデスクトップアプリから配信される正規化されたマウス座標を返します。xy はウィンドウに対して -11 で正規化され、y は数学的座標系(上が +1)です。

基本的な使い方

CSS で使う前にピクセル座標へ変換します。

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 (
    <div
      style={{
        position: "absolute",
        left: px,
        top: py,
        width: 20,
        height: 20,
        borderRadius: "50%",
        backgroundColor: "white",
        transform: "translate(-50%, -50%)"
      }}
    />
  );
}

アニメーション付き

スプリング物理で追従をなめらかにできます。

import { useSpring, animated } from "@react-spring/web";
import { useMousePosition } from "@fluxlay/react";
 
function Cursor() {
  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: 200, friction: 20 } });
 
  return (
    <animated.div
      style={{
        position: "absolute",
        left: spring.x,
        top: spring.y,
        width: 20,
        height: 20,
        borderRadius: "50%",
        backgroundColor: "white",
        transform: "translate(-50%, -50%)"
      }}
    />
  );
}

注意事項

  • 最初のマウスイベントを受信するまで { x: 0, y: 0 } を返します。
  • 座標はウィンドウ相対です。マルチウィンドウ構成では window_label ごとに別ストリームが流れます。
  • Fluxlay デスクトップアプリ内でのみ動作します。

詳細は useMousePosition リファレンスを参照してください。