滚动

Starter pack

HTML 中,页面滚动由浏览器根据页面内容进行处理。在 Three.jsReact Three Fiber 中,Canvas 大多数时候是 固定 的,占据 整个屏幕

这意味着,默认情况下,页面滚动3D 场景 没有影响

为了解决这个问题,我们需要 监听滚动事件相应地更新我们的 3D 场景

这正是 Drei 中的 ScrollControls 完美实现的功能。

ScrollControls

<ScrollControls/> 在画布前创建一个 HTML 滚动容器。其大小基于 pages 属性。

一页等于屏幕的高度(100vh)。

让我们在 <Canvas/> 中用 <ScrollControls/> 包裹我们的 3D 场景

import { ScrollControls } from "@react-three/drei";

// ...

function App() {
  return (
    <>
      <Canvas camera={{ position: [0, 4, 12], fov: 30 }}>
        <ScrollControls pages={5}>
          <Experience />
        </ScrollControls>
      </Canvas>
    </>
  );
}

export default App;

现在,我们在 3D 场景 前面有一个 可滚动的容器,但滚动时还没有发生任何变化。

让我们来探索两种根据 滚动位置 更新场景 的方法。

Scroll 组件

第一种让元素随滚动条移动的方法是使用 <Scroll/> 组件。

这是一个包装组件,会根据滚动位置更新其子组件的位置

让我们在 Experience.jsx 中将其添加到包裹 foodItems 映射的部分:

import { Scroll } from "@react-three/drei";
// ...

export const Experience = () => {
  return (
    <>
      {/* ... */}
      <Scroll>
        {foodItems.map((foodItem, idx) => (
          <FoodItem key={idx} {...foodItem} />
        ))}
      </Scroll>
    </>
  );
};

// ...

现在,食物项的位置会根据滚动位置更新,但是我们希望每一页显示一个项目。 (从第二个开始,因为第一个将是介绍)

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.