> For the complete documentation index, see [llms.txt](https://docs.convai.com/api-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-embody/add-a-3d-character-to-a-react-app.md).

# 将 3D 角色添加到 React 应用

在 React 应用中安装 Convai Embody，并根据角色 ID 渲染一个带有口型同步、视线和眨眼效果的 Convai 角色。

只需一个组件，即可在 React 应用中将 Convai 角色渲染为 3D 形象。首次在项目中添加 Convai Embody 时，请参考本页。完成后，角色会显示在页面上，用眼睛跟随摄像机，并让嘴部动作与语音同步。

### 前提条件

* React 18 或更高版本的应用（带打包工具），以及 Node.js 18 或更高版本。
* Convai 账户、从 <code class="expression">space.vars.dashboard\_url</code>获取的 API 密钥，以及角色 ID。
* 角色的头像必须已发布 Web 形象，或有适用于该角色的默认形象。两者皆无的角色无法渲染。请参阅 [故障排除](#troubleshooting).

### 安装软件包

`@convai/web-sdk` 和 `three` 是对等依赖项，因此请与 `@convai/embody`一同安装。React 方案还需要 `react` 和 `@react-three/fiber`.

{% tabs %}
{% tab title="npm" %}

```bash
npm install @convai/embody @convai/web-sdk three @react-three/fiber
```

{% endtab %}

{% tab title="pnpm" %}

```bash
pnpm add @convai/embody @convai/web-sdk three @react-three/fiber
```

{% endtab %}

{% tab title="yarn" %}

```bash
yarn add @convai/embody @convai/web-sdk three @react-three/fiber
```

{% endtab %}
{% endtabs %}

### 渲染角色

`ConvaiCharacter` 会自行创建画布、摄像机、灯光和轨道控制器。它会解析角色的形象、建立 Convai Web SDK 连接、播放角色的音频，并驱动面部动作。

{% code title="src/App.tsx" %}

```tsx
import ConvaiCharacter from '@convai/embody/react'

export default function App() {
  return (
    <ConvaiCharacter
      apiKey={import.meta.env.VITE_CONVAI_API_KEY}
      characterId="YOUR_CHARACTER_ID"
    />
  )
}
```

{% endcode %}

该组件会填满其父元素，且高度至少与视口相同。摄像机位于角色的眼睛高度，并绕其眼睛旋转：拖动即可环绕角色转动，滚动即可拉近。传入 `orbit={false}` 可固定摄像机；也可以传入一个 `orbit` 对象来修改限制，其默认值以 `ORBIT_DEFAULTS`.

导出。如果角色启用了长期记忆，连接还需要最终用户 ID，以便角色区分不同用户。请传入使用你应用的用户的稳定 ID： `session={{ endUserId: user.id }}`。若不传入，连接将因 "Missing end\_user\_id" 而失败。

{% hint style="danger" %}
API 密钥是工作区范围内的凭据。任何打开包含该密钥的页面的人都能读取它。对于公开页面，请在服务器上创建短期有效的身份验证令牌，并传入 `token` 而非 `apiKey`。请参阅 [身份验证令牌](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/auth-tokens.md).
{% endhint %}

### 将角色放入自己的场景

如果要将角色添加到你已使用 `@react-three/fiber`组合的场景中，请改用 `CharacterModel` 并将其放在你的 `<Canvas>` 中。它接受相同的凭据和角色属性，并且不会自行添加画布、摄像机或灯光。

{% code title="src/Scene.tsx" %}

```tsx
import { Canvas } from '@react-three/fiber'
import { CharacterModel } from '@convai/embody/react'

export function Scene({ token }: { token: string }) {
  return (
    <Canvas camera={{ position: [0, 1.58, 2.2], fov: 35 }}>
      <ambientLight intensity={0.6} />
      <directionalLight position={[2, 3, 2]} />
      <CharacterModel token={token} characterId="YOUR_CHARACTER_ID" />
    </Canvas>
  )
}
```

{% endcode %}

### 验证角色

加载页面并等待模型下载完成。然后与角色交谈，例如使用 [为角色添加聊天小组件](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-embody/add-a-chat-widget-to-a-character.md).

{% hint style="success" %}
角色会居中站立并播放待机动画；当你环绕查看时，它的眼睛会跟随镜头，回答时嘴部会随着语音同步动作。
{% endhint %}

若要在代码中观察加载状态，请传入 `onReady`，模型主体加载完成且连接可用后，它会接收角色句柄；并传入 `onError`，它会接收导致加载停止的错误。

### 故障排查

#### 角色始终没有出现

**现象：** `onError` 收到的错误消息以 Convai 提供的原因结尾：

```
embodiment resolve failed for YOUR_CHARACTER_ID: HTTP 404 — Character has no 3D embodiment configured.
```

**原因：** 该角色的头像没有已发布的 Web 形象，且没有适用于它的默认形象。

**解决方法：** 选择一个头像具有已发布 Web 形象的角色。如果你的角色都没有，请联系 Convai 支持团队。

**验证：** 重新加载页面。角色会正常渲染。

#### 内容加载前就出现凭据错误

**现象：** 创建角色时抛出以下错误：

```
@convai/embody: a credential is required — pass `token` (recommended for browsers) or `apiKey`. There is no anonymous access to Convai.
```

**原因：** 既没有设置 `token`, `authToken`，也没有设置 `apiKey` ，或者构建时对应的变量为空。

**解决方法：** 传入凭据。检查正在运行的构建是否定义了环境变量。

**验证：** 错误不再出现，且角色能够加载。

#### 在内容安全策略严格的页面上模型无法加载

**现象：** 主体始终无法渲染，浏览器控制台报告对以下地址的请求被拦截： `https://www.gstatic.com/draco/`.

**原因：** 角色模型经过 Draco 压缩，Convai Embody 默认从 `https://www.gstatic.com/draco/versioned/decoders/1.5.7/` 加载 Draco 解码器。

**修复：** 在策略中允许该来源，或自行托管解码器文件，并将其 URL 作为 `dracoDecoderPath`.

**验证：** 字符能够正常渲染，且控制台中没有显示被阻止的解码器请求。

### 后续步骤

{% content-ref url="/pages/2e94cc1e2d8d4d328ddd3855269d9e50f989aece" %}
[向角色添加聊天小部件](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-embody/add-a-chat-widget-to-a-character.md)
{% endcontent-ref %}

{% content-ref url="/pages/afcae56dd5bee11232aa7e5af42d7608c0a2f044" %}
[React API 参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-embody/react-api-reference.md)
{% endcontent-ref %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-embody/add-a-3d-character-to-a-react-app.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
