如何在react-three-fiber中使用坐标数组创建自定义BufferGeometry
react-three-fiber自定义几何体不渲染的解决方法
核心问题排查
你提供的代码存在以下几个导致无渲染的问题:
- 缺少
bufferAttribute必填的count字段,该字段用于声明顶点总数量,取值为顶点数组长度除以每个顶点的分量数(3D坐标固定为3) - 未配置法线属性,
meshNormalMaterial依赖顶点法线计算显示颜色,没有法线会导致渲染异常 - 顶点数组未做缓存,每次组件重渲染都会重复创建数组,引发不必要的几何体重建
- 未显式声明
attach绑定属性,部分旧版本react-three-fiber可能无法正确挂载几何体和材质到mesh上
完整实现代码
import { useMemo } from 'react' function CustomPlane() { // 用useMemo缓存顶点数据,避免重复创建触发重渲染 const vertices = useMemo(() => new Float32Array([ -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0, -1.0, -1.0, 1.0 ]), []) return ( <mesh> <bufferGeometry attach="geometry" {/* 几何体更新时自动计算顶点法线,不需要手动传法线的话可以用这个方法 */} onUpdate={(geo) => geo.computeVertexNormals()} > <bufferAttribute attachObject={["attributes", "position"]} array={vertices} itemSize={3} {/* 补全必填的count属性 */} count={vertices.length / 3} /> </bufferGeometry> <meshNormalMaterial attach="material" /> </mesh> ) }
手动传入自定义法线数组的写法
如果你已经提前计算好了法线数据,不需要自动计算,可以直接添加法线对应的bufferAttribute即可:
function CustomGeometryWithNormal() { const vertices = useMemo(() => new Float32Array([ // 你的顶点坐标数组 ]), []) // 自定义法线数组,每个顶点对应一组x/y/z法线分量 const normals = useMemo(() => new Float32Array([ 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1 ]), []) return ( <mesh> <bufferGeometry attach="geometry"> <bufferAttribute attachObject={["attributes", "position"]} array={vertices} itemSize={3} count={vertices.length / 3} /> {/* 手动添加法线属性 */} <bufferAttribute attachObject={["attributes", "normal"]} array={normals} itemSize={3} count={normals.length / 3} /> </bufferGeometry> <meshNormalMaterial attach="material" /> </mesh> ) }
补充排查点
如果修改后还是无法看到渲染内容,可以检查以下配置:
- 相机位置是否在几何体外侧:你当前的几何体所有顶点都在z=1的平面上,默认相机位置为z=0,会处于几何体内部触发背面裁剪,将相机z轴位置调整到大于1的数值即可
- 如果需要显示几何体正反两面,可以给材质添加
side={THREE.DoubleSide}属性
内容的提问来源于stack exchange,提问作者agt-ru
相关产品推荐
相关产品推荐

