Appearance
人物编辑
一、准备模型
1.1 士兵模型
1.2 女孩模型
1.3 存放结构
- 放置于
public目录下面 - 目录示意
public/
├── favicon.svg
├── icons.svg
└── glb/ 3D 模型目录
├── Michelle.glb
└── Soldier.glb1.4 glb模型
1.4.1 glb模型简介
GLB(GL Transmission Format Binary) 是glTF 2.0 的二进制版本,可以理解为:“3D 界的 JPEG / MP4”
- 一种开放的
3D文件标准- 由
Khronos Group(OpenGL/WebGL背后组织)制定- 专门为 传输和加载效率 设计
- 在
Web、游戏、AR/VR中非常常见
1.4.2 存放位置
GLB并不是“只能”放public,放在public,是因为GLTFLoader/useGLTF是通过HTTP URL 去请求模型文件的,而public目录正好就是“构建后原样暴露给浏览器访问”的地方。
核心原因:浏览器加载的是
URL,不是源码路径
GLTFLoader.load('/models/a.glb')本质是发一个HTTP请求
sh
GET /models/a.glb- 浏览器里没有
src/这个概念,构建后src早就变成dist/assets/xxx.js了。 - 因此
- 放
public/models/a.glb→ 开发/生产都能通过/models/a.glb访问 ✅ - 写
./src/assets/a.glb→ 运行时根本不存在这个HTTP路径,通常404,或者拿到index.html,然后报Unexpected token '<'❌
二、人物管理
2.1 定义人物组件
tsx
const MODELS = {
michelle: '/glb/Michelle.glb',
soldier: '/glb/Soldier.glb',
} as const2.2 实现initCharacterScene方法加载3D场景
src/components/Main/init-character-3d.ts
ts
import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
/** 场景实例对外暴露的能力(目前只有切换模型) */
export type CharacterSceneApi = {
/** 加载并挂载 glb 模型;内部会自动移除上一个模型并重新取景 */
loadModel: (url: string) => Promise<void>;
};
/**
* 读取容器的实际尺寸。
* 宽高取 max(…, 1),避免容器尚未布局时得到 0 导致除零 / 相机 aspect 为 NaN。
*/
function getSize(dom: HTMLElement) {
const rect = dom.getBoundingClientRect();
const w = Math.max(rect.width, 1);
const h = Math.max(rect.height, 1);
return { width: w, height: h };
}
/**
* 在指定容器内初始化一个角色预览场景(相机 / 光照 / 控制器都是独立的)。
* 返回 loadModel 供外部切换模型;不自动加载任何模型。
*/
export function initCharacterScene(dom: HTMLElement): CharacterSceneApi {
const scene = new THREE.Scene();
// 主光:方向光兼做环境光,右上方打光,给模型立体感
const directionalLight = new THREE.DirectionalLight(0xffffff, 2.0);
directionalLight.position.set(4.5, 12, 6);
scene.add(directionalLight);
// 环境光:整体提亮,避免背光面过暗
const ambientLight = new THREE.AmbientLight(0xffffff, 0.88);
scene.add(ambientLight);
// 初始相机:fov 42 偏长焦,减少透视畸变;位姿后续会被 fitCameraToObject 覆盖
const { width: initW, height: initH } = getSize(dom);
const camera = new THREE.PerspectiveCamera(42, initW / initH, 0.08, 2000);
camera.position.set(2.1, 1.45, 2.4);
// 渲染器:antialias 抗牙齿;alpha:false 走不透明背景(配合 setClearColor)
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
renderer.setSize(initW, initH);
// 限制 pixelRatio 上限为 2,兼顾高清屏清晰度与性能
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setClearColor(0xf0f2f5, 1);
// canvas 直接挂到容器里(组件卸载时不会自动清理,需外部 dispose)
dom.appendChild(renderer.domElement);
// 轨道控制器:允许鼠标拖拽旋转 / 滚轮缩放;target 对准模型腰部高度
const controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(0, 0.85, 0);
const loader = new GLTFLoader();
// 当前已挂载的模型根节点,换模型时用于移除旧模型
let currentRoot: THREE.Object3D | null = null;
/** 逐帧循环:更新控制器阻尼 / 相机状态后渲染一帧 */
function loop() {
requestAnimationFrame(loop);
controls.update();
renderer.render(scene, camera);
}
loop();
// 容器尺寸变化时同步相机 aspect 与渲染尺寸(改用窗口 resize 更精确)
const resizeObserver = new ResizeObserver(() => {
const { width, height } = getSize(dom);
// 容器被隐藏(尺寸归 0/1)时跳过,避免 aspect 退化
if (width < 2 || height < 2) return;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
});
resizeObserver.observe(dom);
/**
* 按模型包围盒自动取景:
* 用垂直视角 fov 反推“完整装下模型”所需距离 dist,再酌量放大为 offset,
* 最后把相机放在模型右上偏前方,使模型完整入镜。
*/
function fitCameraToObject(object: THREE.Object3D) {
const box = new THREE.Box3().setFromObject(object);
const center = box.getCenter(new THREE.Vector3());
const size = box.getSize(new THREE.Vector3());
// 取最大边长作为取景基准;下限 0.05 防止空 / 极细模型导致距离为 0
const maxDim = Math.max(size.x, size.y, size.z, 0.05);
// dist 满足:模型高度恰好填满垂直视野
const dist = maxDim / (2 * Math.tan((camera.fov * Math.PI) / 360));
// 留白系数,避免模型贴边
const offset = dist * 1.28;
camera.position.set(
center.x + offset * 0.72,
center.y + offset * 0.32,
center.z + offset,
);
// 视线中心对齐模型中心,保证旋转围绕模型自身
controls.target.copy(center);
controls.update();
}
/** 挂载模型根节点:先移除旧模型,再添加新模型并重新取景 */
function mountRoot(root: THREE.Object3D) {
if (currentRoot) {
scene.remove(currentRoot);
currentRoot = null;
}
currentRoot = root;
scene.add(currentRoot);
fitCameraToObject(currentRoot);
}
/** 从 url 加载 glb 并挂载(加载失败会向上抛出 Promise 错误) */
async function loadModel(url: string) {
const gltf = await loader.loadAsync(url);
mountRoot(gltf.scene);
}
// 目前只暴露 loadModel;scene/renderer/ResizeObserver 均未对外释放
return { loadModel };
}2.3 实现人物管理组件
src/components/Main/CharacterView.tsx
tsx
import { useEffect, useRef, useState } from 'react'
import { initCharacterScene } from './init-character-3d'
/**
* 角色模型清单:key 作为状态标记,value 是 public/ 下的模型地址。
* public 资源不参与打包,写根路径字符串即可(不要用 import)。
*/
const MODELS = {
michelle: '/glb/Michelle.glb',
soldier: '/glb/Soldier.glb',
} as const
/** 角色标识联合类型:'michelle' | 'soldier'(由 MODELS 的 key 推导) */
type CharacterModelKey = keyof typeof MODELS
/**
* 人物模型预览组件。
* 左右两个面板各自持有一个独立的 Three.js 场景,点击卡片切换「当前选中」角色。
*/
function CharacterView() {
// 当前选中的角色,仅用于卡片高亮与无障碍状态,不影响 3D 场景本身
const [active, setActive] = useState<CharacterModelKey>('michelle')
// 左右两个预览视口的挂载点:Three.js 的 canvas 会被插入到这两个 div 中
const leftRef = useRef<HTMLDivElement>(null)
const rightRef = useRef<HTMLDivElement>(null)
// 仅在挂载时执行一次:初始化双场景并加载模型
useEffect(() => {
const leftEl = leftRef.current
const rightEl = rightRef.current
// DOM 尚未挂载完成时直接跳过
if (!leftEl || !rightEl) return
// 左右各建一个场景(相机 / 光照 / OrbitControls 互相独立,可分别旋转缩放)
const leftApi = initCharacterScene(leftEl)
const rightApi = initCharacterScene(rightEl)
// 分别加载两个 glb,initCharacterScene 内部会自动按模型尺寸取景
leftApi.loadModel(MODELS.michelle)
rightApi.loadModel(MODELS.soldier)
return () => {
// 目前未做清理:场景与渲染器资源不会随组件卸载释放
// TODO: 若后续支持切换视图,需在此 dispose 场景 / 渲染器 / 几何体
}
}, [])
return (
<div className="character-view">
{/* 标题区:仅说明文案,无交互 */}
<header className="character-view-header">
<h2 className="character-view-title">人物模型</h2>
<p className="character-view-desc">左右各预览一个模型,点击卡片切换当前选中的角色。</p>
</header>
{/* 左右分栏:每张卡片既是 3D 预览容器,也是切换选中的按钮 */}
<div className="character-split">
{/* 左:Michelle */}
<button
type="button"
// 选中时追加 --active 修饰类,用于高亮描边
className={`character-panel${active === 'michelle' ? ' character-panel--active' : ''}`}
onClick={() => setActive('michelle')}
// 无障碍:向读屏软件暴露「已按下 / 选中」状态
aria-pressed={active === 'michelle'}
>
<div className="character-panel-head">
<span className="character-panel-name">Michelle</span>
{/* 角标只在选中时渲染 */}
{active === 'michelle' && <span className="character-panel-badge">当前选中</span>}
</div>
{/* Three.js 画布挂载点(由 useEffect 注入) */}
<div ref={leftRef} className="character-panel-viewport" />
</button>
{/* 右:Soldier */}
<button
type="button"
// 选中时追加 --active 修饰类,用于高亮描边
className={`character-panel${active === 'soldier' ? ' character-panel--active' : ''}`}
onClick={() => setActive('soldier')}
// 无障碍:向读屏软件暴露「已按下 / 选中」状态
aria-pressed={active === 'soldier'}
>
<div className="character-panel-head">
<span className="character-panel-name">Soldier</span>
{/* 角标只在选中时渲染 */}
{active === 'soldier' && <span className="character-panel-badge">当前选中</span>}
</div>
{/* Three.js 画布挂载点(由 useEffect 注入) */}
<div ref={rightRef} className="character-panel-viewport" />
</button>
</div>
</div>
)
}
export default CharacterView2.4 双场景抽离
src/components/Main/GalleryView.tsx
tsx
import React from "react";
import { init3D } from "./init-3d";
import { init2D } from "./init-2d";
import { Segmented } from "antd";
function GalleryView() {
React.useEffect(() => {
const dom = document.getElementById('threejs-3d-container')
init3D(dom!);
return () => {
if (dom) {
dom.innerHTML = ''
}
}
}, [])
React.useEffect(() => {
const dom = document.getElementById('threejs-2d-container')
init2D(dom!);
return () => {
if (dom) {
dom.innerHTML = ''
}
}
}, [])
const [curMode, setCurMode] = React.useState<'2d' | '3d'>('2d')
return (
<div className="main-content">
<div id="threejs-3d-container" style={{ display: curMode === '3d' ? 'block' : 'none' }}></div>
<div id="threejs-2d-container" style={{ display: curMode === '2d' ? 'block' : 'none' }}></div>
<div className="mode-change-btns">
<Segmented
options={[
{ label: '2D', value: '2d' },
{ label: '3D', value: '3d' }
]}
value={curMode}
onChange={(value) => setCurMode(value as '2d' | '3d')}
/>
</div>
</div>
);
}
export default GalleryView;2.5 sider改造支持选中定位
2.5.1 src/components/Menu/sidebar.tsx
tsx
import { Menu } from 'antd'
import type { MainView } from '../Main';
const menuItems = [
{ key: 'gallery', label: '画廊编辑' },
{ key: 'character', label: '人物编辑' },
]
function AppSider(props: { activeKey: MainView; onSelect: (key: MainView) => void }) {
return (
<Menu
mode="inline"
selectedKeys={[props.activeKey]}
items={menuItems}
style={{ height: '100%', borderRight: 0 }}
onSelect={(e) => props.onSelect(e.key as MainView)}
/>
)
}
export default AppSider2.5.2 src/components/Menu/index.tsx
tsx
import React from "react";
import AppSider from "./sidebar";
import type { MainView } from "../Main";
function Menu({ activeKey, onSelect }: { activeKey: MainView; onSelect: (key: MainView) => void }) {
const [left, setLeft] = React.useState(0);
return (
<div className="Menu" style={{ left }}>
<AppSider activeKey={activeKey} onSelect={onSelect} />
<div className="drawer-bar" onClick={() => setLeft(left === 0 ? -200 : 0)}></div>
</div>
);
}
export default Menu;2.6 入口改造
src/App.tsx
tsx
import { Layout } from 'antd'
import './App.scss'
import AppHeader from './components/Header'
import AppSider from './components/Menu'
import Main, { type MainView } from './components/Main'
import React from 'react'
const { Header, Sider, Content } = Layout
function App() {
const [menuKey, setMenuKey] = React.useState<MainView>('gallery')
return (
<Layout className="gallery-editor-layout">
<Header className="app-header">
<AppHeader />
</Header>
<Layout>
<Sider width={200} className="app-sider">
<AppSider activeKey={menuKey} onSelect={(key: MainView) => setMenuKey(key)} />
</Sider>
<Content className="app-content">
<Main view={menuKey} />
</Content>
</Layout>
</Layout>
)
}
export default App2.7 样式调整
src/App.scss
scss
body {
margin: 0;
}
.gallery-editor-layout {
min-height: 100vh;
.app-header {
display: flex;
align-items: center;
padding: 0 24px;
background: #fff;
border-bottom: 1px solid #000;
.header-content {
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
}
.header-title {
margin: 0;
font-size: 18px;
font-weight: 500;
}
}
.app-sider {
background: #fff;
border-right: 1px solid #000;
.ant-menu {
margin-top: 16px;
}
}
.app-content {
position: relative;
min-height: calc(100vh - 64px);
background: #fff;
}
.main-content {
position: relative;
height: 100%;
min-height: calc(100vh - 64px);
display: flex;
flex-direction: column;
#threejs-3d-container,
#threejs-2d-container {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
width: 100%;
height: 100%;
}
.mode-change-btns {
position: absolute;
z-index: 10;
bottom: 20px;
left: 20px;
}
.character-view {
flex: 1;
display: flex;
flex-direction: column;
min-height: 0;
padding: 20px 24px 24px;
box-sizing: border-box;
background: linear-gradient(180deg, #fafbfc 0%, #f0f2f5 100%);
}
.character-view-header {
flex-shrink: 0;
margin-bottom: 16px;
}
.character-view-title {
margin: 0 0 6px;
font-size: 16px;
font-weight: 600;
color: rgba(0, 0, 0, 0.88);
letter-spacing: 0.02em;
}
.character-view-desc {
margin: 0;
font-size: 13px;
color: rgba(0, 0, 0, 0.45);
line-height: 1.5;
}
.character-split {
flex: 1;
display: flex;
gap: 20px;
min-height: 0;
align-items: stretch;
}
.character-panel {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
padding: 0;
margin: 0;
border: 1px solid rgba(0, 0, 0, 0.08);
border-radius: 12px;
background: #fff;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
cursor: pointer;
text-align: left;
font: inherit;
color: inherit;
overflow: hidden;
outline: none;
transition:
border-color 0.2s ease,
box-shadow 0.2s ease,
transform 0.15s ease;
&:focus-visible {
box-shadow:
0 0 0 2px #fff,
0 0 0 4px rgba(22, 119, 255, 0.45);
}
&:hover {
border-color: rgba(22, 119, 255, 0.35);
box-shadow: 0 4px 14px rgba(22, 119, 255, 0.08);
}
.character-panel-head {
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 12px 16px;
background: linear-gradient(180deg, #fafafa 0%, #fff 100%);
border-bottom: 1px solid rgba(0, 0, 0, 0.06);
}
.character-panel-name {
font-size: 15px;
font-weight: 600;
color: rgba(0, 0, 0, 0.85);
}
.character-panel-badge {
font-size: 12px;
font-weight: 500;
color: #1677ff;
padding: 2px 10px;
border-radius: 999px;
background: rgba(22, 119, 255, 0.1);
border: 1px solid rgba(22, 119, 255, 0.2);
}
.character-panel-viewport {
flex: 1;
min-height: 280px;
position: relative;
background: #f0f2f5;
canvas {
display: block;
width: 100% !important;
height: 100% !important;
}
}
.character-panel--active {
border-color: #1677ff;
box-shadow:
0 0 0 1px rgba(22, 119, 255, 0.2),
0 6px 20px rgba(22, 119, 255, 0.12);
&:hover {
border-color: #1677ff;
}
.character-panel-head {
background: linear-gradient(180deg, #e6f4ff 0%, #fff 100%);
border-bottom-color: rgba(22, 119, 255, 0.15);
}
}
}
}
}