ThreeJS Div 跟随鼠标

问题描述 投票:0回答:1

我是编程世界的新手。我正在尝试在 Three JS 中创建一个跟随鼠标的圆圈。这是我的代码。该圆圈跟随鼠标,但从视觉上看,它距离实际光标位置大约是屏幕宽度和高度的一半。我该如何解决它?

const CircleFollowMouse = () => {
  const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 });
  const circleSize = 40; // Define the size of the circle

  useEffect(() => {
    const handleMouseMove = (event) => {
      // Update mouse position state with the current mouse position
      setMousePosition({ x: event.pageX, y: event.pageY });
    };

    // Add mouse move event listener
    document.addEventListener('mousemove', handleMouseMove);

    // Remove event listener on cleanup
    return () => {
      document.removeEventListener('mousemove', handleMouseMove);
    };
  }, []);

  return (
    <Html>
      <div
        className="circle"
        style={{
          left: `${mousePosition.x - circleSize / 2}px`, // Center the circle on the mouse by adjusting for half its size
          top: `${mousePosition.y - circleSize / 2}px`, // Center the circle on the mouse by adjusting for half its size
          width: `${circleSize}px`, // Set the width of the circle
          height: `${circleSize}px`, // Set the height of the circle
          borderRadius: '50%', // Make the div a circle
          backgroundColor: 'white', // Set the circle color
          position: 'fixed', // Ensure the circle follows the mouse correctly
          zIndex: 9999, // Make sure the circle is above other content
        }}
      ></div>
    </Html>
  );
};
reactjs three.js react-three-fiber react-three-drei
1个回答
0
投票

默认情况下,来自

Html
@react-three/drei
位于屏幕中央。

您有两个选择:

  1. 更改
    Html
    布局以将其放回左上角:
<Html
  style={{
    transform: `translate3d(-50vw, -50vh, 0)`
  }}
></Html>
  1. 更新圆的位置:
{
    left: `${mousePosition.x - circleSize / 2 - halfScreenWidth}px`,
     top: `${mousePosition.y - circleSize / 2 - halfScreenHeight}px`
}
© www.soinside.com 2019 - 2024. All rights reserved.