将 Html 固定到固定位置 r3f

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

我正在尝试将 drei Html 元素固定到左上角。在旋转或移动相机时,我很难让它保持在同一位置。这是我目前的尝试:

  const { mouse2D, mouse3D, normal, plane } = useMemo(() => {
    return {
      mouse2D: new THREE.Vector2(),
      mouse3D: new THREE.Vector3(),
      normal: new THREE.Vector3(),
      plane: new THREE.Plane(),
    };
  }, []);

  const { width, height } = useWindowDimensions();

  useFrame(({camera, raycaster, size}) => {
    mouse2D.set(((0.02 * width) / size.width) * 2 - 1, ((-0.02 * height) / size.height) * 2 + 1);
    raycaster.setFromCamera(mouse2D, camera);
    camera.getWorldDirection(normal).negate();
    plane.setFromNormalAndCoplanarPoint(normal, mouse3D);
    raycaster.ray.intersectPlane(plane, mouse3D);
  });

  return <Html position={[mouse3D.x, mouse3D.y, mouse3D.z]}>stuff</Html>;

Html 位置在窗口调整大小时正确更新,但在相机旋转或相机移动时不会更新。有人知道如何解决这个问题吗?

react-three-fiber drei
2个回答
0
投票

如果有人感兴趣,这是我当前的解决方案:

const { viewport } = useThree();

const groupRef = useRef<THREE.Group>(null!);
  useEffect(() => {
    const groupRefCopy = groupRef.current;
    camera.add(groupRefCopy);
    return () => {
      camera.remove(groupRefCopy);
    };
  }, [camera, groupRef.current]);

  return (
    <group ref={groupRef} position={[-viewport.width / 3.5, viewport.height / 3.8, -5]} rotation={[0, 0, 0]}>
      <Html style={{ opacity: show ? 1 : 0, width: menuWidth, userSelect: "none", pointerEvents: show? "auto" : "none" }}>
         {...}
      </Html>
    </group>
  );

3.5 和 3.8 非常适合我的场景。如果有人知道如何从3JS动态获取这些常量,请评论!


0
投票

我遇到了这个问题,并且我已将 CSS 属性应用到 HTML 组件内的 div(我正在使用 MUI)。这似乎对我有用,适合任何感兴趣的人

<Box component='div' sx={{ position: 'absolute', right: '45vw', top: '-48vh' }}> 

© www.soinside.com 2019 - 2024. All rights reserved.