到目前为止,我们已经创建了许多 3D 场景,但我们只是在一个时间点显示一个场景,并且覆盖了整个页面。
在本节课中,我们将学习如何在单个 HTML 页面中集成多个 3D 场景,就像您可以将图像、视频或任何其他 HTML 元素添加到网站上一样。
起始项目
在本节课中,我们将为一个虚构的 3D Web 开发机构创建一个登录页面。
起始包包含一个简单且可直接使用的响应式页面,包含以下几个部分:主页、服务、团队、作品集和联系方式。
这是一个标准的 HTML 页面,包含可供搜索引擎和无障碍访问索引的内容,我们将通过 3D 内容进行增强和说明。
不含 3D 内容的登录页面
视图
为了在页面中创建和渲染多个 3D 场景,我们将使用 Drei 库中的 View 组件。
通过使用它,我们可以只使用一个 Canvas
组件,并在其中渲染多个独立的场景(视图)。这非常有用,因为它允许我们只使用一个 WebGL 上下文,从而避免性能问题。
这些视图绑定到一个目标 HTML 元素,可以独立定位和调整大小,同时对触摸、鼠标、滚动和调整大小事件做出正确反应。
Canvas
为了让我们的页面准备好3D内容,让我们在main
元素的顶部创建我们常用的Canvas
组件。
HomePage.jsx
:
// ... import { Canvas } from "react-three-fiber"; export const HomePage = () => { // ... return ( <main> <Canvas className="canvas" camera={{ position: [0, 0, 1.5], fov: 30 }} ></Canvas> {/* ... */} </main> ); };
canvas
类用于样式化canvas并让其占据整个页面。在index.css
文件中已经定义好了。
Tracking
起始项目包含我们将用于展示页面不同部分的3D场景组件。
让我们为主页部分添加一个:
import { Hero3D } from "./Hero3D"; export const HomePage = () => { // ... return ( <main> <Canvas className="canvas" camera={{ position: [0, 0, 1.5], fov: 30 }}> <Hero3D /> </Canvas> {/* ... */} </main> ); };
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
One-time payment. Lifetime updates included.