React Three Fiber 钩子

Starter pack

在本课中,我们将了解 React Three Fiber 提供的 useThreeuseFrame 钩子,以及如何及何时使用它们。

useThree

useThree 提供对 state 模型的访问,state 包含默认的渲染器、场景、摄像机、视口大小等信息。

虽然我将在适当的时候解释我们使用的每个 state 属性,但您可以在文档中找到完整的属性列表。

要使用它,我们需要从 @react-three/fiber 导入,然后在组件内调用它:

import { Canvas, useThree } from "@react-three/fiber";
// ...

const Cube = (props) => {
  const { camera } = useThree();
  // ...
};

// ...

虽然这种使用 useThree 的方式有效,但它会导致组件在属性值变化时重新渲染,即便这些值未被解构。

相反,我们可以使用 selector 模式来仅获取所需的值:

import { Canvas, useThree } from "@react-three/fiber";

const Cube = (props) => {
  const camera = useThree((state) => state.camera);
  // ...
};

这样,只有当 camera 值变化时,组件才会重新渲染。

请记住,threejs 内部的值不是反应式的。如果 camera.position 改变,组件不会重新渲染。(幸好如此)

现在我们可以访问摄像机并修改其 fov(视野)来进行放大或缩小:

// ...

const Cube = (props) => {
  const camera = useThree((state) => state.camera);

  const updateFov = (fov) => {
    camera.fov = fov;
    camera.updateProjectionMatrix();
  };

  useControls("FOV", {
    smallFov: button(() => updateFov(20)),
    normalFov: button(() => updateFov(42)),
    bigFov: button(() => updateFov(60)),
    hugeFov: button(() => updateFov(110)),
  });

  // ...
};

// ...

注意事项:

  • updateProjectionMatrix 方法用于告诉 threejs 摄像机已更改,需要更新。
  • 通过将字符串值作为 useControls 的第一个参数传递,我们可以按照文件夹对属性进行分组。

我们的摄像机视野已从控件中正确更新

useFrame

Threejs是一个基于渲染循环的库。这意味着我们在屏幕上看到的内容是场景在每一帧中渲染的结果。正如视频是一系列图像一样,3D场景是一系列帧

useFrame hook允许我们在每一个渲染帧中执行代码,比如运行效果、更新控件和动画。

当目标是60fps时,回调函数将每秒被调用60次。

Three.js logoReact logo

React Three Fiber: The Ultimate Guide to 3D Web Development

✨ You have reached the end of the preview ✨

Go to the next level with Three.js and React Three Fiber!

Get full access to this lesson and the complete course when you enroll:

  • 🔓 Full lesson videos with no limits
  • 💻 Access to the final source code
  • 🎓 Course progress tracking & completion
  • 💬 Invite to our private Discord community
Unlock the Full Course – Just $85

One-time payment. Lifetime updates included.