Text

Starter pack

在本章节中,我们将学习如何在 React Three Fiber 项目中添加2D3D 文字

我们将学习如何使用自定义字体,避免常见陷阱,以及一些创造漂亮效果的实用技巧

本课程涉及的是通过HTML Canvas像其他 3D 对象一样直接将文字添加到场景中。这样做时,文字将被完美地集成到 3D 世界中,受到光线、阴影和摄像机的影响。

但是,所写的文字是不可选择的不可访问的,并且不会被搜索引擎索引。在创建项目时选择正确的文本显示方式时,需牢记这一点。

在必要时考虑使用HTML 文本

2D Text

添加文本到 React Three Fiber 场景的最简单方法是显示2D 文本。要做到这一点,我们将使用 drei 库中的 Text 组件。

我们将在木质标牌上添加**"Hyrule Castle"**文字:

import { Text } from "drei";
// ...

export const Experience = () => {
  const woodenSign = useGLTF("models/Wooden Sign.glb");

  return (
    <>
      <group position-x={-1.5} rotation-y={THREE.MathUtils.degToRad(15)}>
        <primitive object={woodenSign.scene} />
        <Text>
          Hyrule Castle
          <meshStandardMaterial color={"#803d1c"} />
        </Text>
      </group>
      {/* ... */}
    </>
  );
};

在包含木质标牌的组中,我们通过添加一个 Text 组件,并把我们想要显示的文本作为一个子元素。此外,我们还添加了带棕色的 meshStandardMaterial,使其看起来像木头。

我常用的一种寻找颜色的技巧是使用 Chrome inspector 选择器。先在 <body> 标签添加 color: red;,然后用选择器找到我需要的颜色。

Chrome color picker

然后,我可以悬停在我想要的颜色上并复制十六进制值

当然也有工具可以做到这些,但我喜欢使用开发者工具的简单性。

目前文字太大位置不正确

Text too big

要解决这个问题,我们可以使用 fontSizeposition 属性:

 <Text fontSize={0.3} position={[0, 1.2, 0.01]}>

Text with correct size and position

这样就好多了。虽然大小是正确的,但超出了标牌。理想情况下,文字应该是居中并且换行的 (当文字到达标牌的边缘时换行)

我们可以使用 maxWidthtextAlign 属性来解决这个问题:

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.