iT邦幫忙

2024 iThome 鐵人賽

DAY 6
0

Day16 要來玩的是讓文字產生背景的陰影,並會隨著滑鼠的移動更改方向

資料

  const [offset, setOffset] = useState<Offset>({ x: 0, y: 0 });
  const containerRef = useRef<HTMLDivElement | null>(null);

滑鼠移動

  const handleMouseMove = (e: MouseEvent<HTMLDivElement>) => {
    if (!containerRef.current) {
      return;
    }

    const { offsetWidth: width, offsetHeight: height } = containerRef.current;
    const { clientX, clientY } = e;
    const { left, top } = containerRef.current.getBoundingClientRect();

    const x = clientX - left;
    const y = clientY - top;

    const xWalk = Math.round((x / width) * 100 - 50) * 2;
    const yWalk = Math.round((y / height) * 100 - 50) * 2;

    setOffset({ x: xWalk, y: yWalk });
  };

畫面結構

  return (
    <div
      ref={containerRef}
      className="flex items-center justify-center h-screen bg-gradient-to-r from-purple-500 to-pink-500"
      onMouseMove={handleMouseMove}
    >
      <h1
        className="text-6xl font-bold text-white select-none"
        style={{
          textShadow: `
          ${offset.x}px ${offset.y}px 0 rgba(255,0,255,0.7),
          ${offset.x * -1}px ${offset.y}px 0 rgba(0,255,255,0.7),
          ${offset.y}px ${offset.x * -1}px 0 rgba(0,255,0,0.7),
          ${offset.y * -1}px ${offset.x}px 0 rgba(0,0,255,0.7)
        `,
        }}
      >
        Mouse Move Shadow
      </h1>
    </div>
  );

DEMO

https://codesandbox.io/p/devbox/67pnpk


上一篇
[Day15]_LocalStorage
下一篇
[Day17]_Sort-Without-Articles
系列文
React30——用 React 探索 JavaScript30 的魅力17
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言