React-Three-Fiber渲染Indexed Buffer Geometry报错与颜色不显示问题
问题修复方案
问题根因说明
- GL_INVALID_ENUM警告:WebGL的缓冲区属性仅支持**类型化数组(TypedArray)**作为输入,你当前代码传入的都是普通JS数组,不符合WebGL参数要求,因此抛出枚举不支持错误
- 顶点颜色不显示:除了上述类型数组问题外,你错误将相机的z轴位置写在了Canvas标签根属性上没有生效,相机默认位置和网格重合导致看不到渲染内容,同时材质的
vertexColors属性需要显式传布尔值true才会生效
修复步骤
- 所有缓冲区属性数组转换为对应类型化数组:索引用
Uint32Array,顶点位置、颜色、法线用Float32Array - 把相机z轴位置移到camera配置项的position属性中
- 材质的
vertexColors显式赋值为true - 适当调高半球光强度,避免渲染效果过暗
修复后完整代码
import React, { useMemo } from "react"; import { Canvas } from "@react-three/fiber"; import { DoubleSide } from "three"; const App = () => { const size = 20; const segments = 10; const [colors, normals, positions] = useMemo(() => { const colorsArr = []; const normalsArr = []; const positionsArr = []; const halfSize = size / 2; const segmentSize = size / segments; for (let i = 0; i <= segments; i++) { const y = i * segmentSize - halfSize; for (let j = 0; j <= segments; j++) { const x = j * segmentSize - halfSize; positionsArr.push(x, -y, 0); normalsArr.push(0, 0, 1); const r = x / size + 0.5; const g = y / size + 0.5; colorsArr.push(r, g, 1); } } // 转换为类型化数组 return [ new Float32Array(colorsArr), new Float32Array(normalsArr), new Float32Array(positionsArr) ]; }, []); const indices = useMemo(() => { const indicesArr = []; for (let i = 0; i < segments; i++) { for (let j = 0; j < segments; j++) { const a = i * (segments + 1) + (j + 1); const b = i * (segments + 1) + j; const c = (i + 1) * (segments + 1) + j; const d = (i + 1) * (segments + 1) + (j + 1); indicesArr.push(a, b, d); indicesArr.push(b, c, d); } } // 索引转换为Uint32Array return new Uint32Array(indicesArr); }, []); return ( <Canvas camera={{ fov: 27, near: 1, far: 3500, position: [0, 0, 64] // 相机位置移到此处生效 }} > <color attach="background" args={["#050505"]} /> <mesh> <bufferGeometry attach="geometry"> <bufferAttribute array={indices} attach="index" count={indices.length} itemSize={1} /> <bufferAttribute attachObject={["attributes", "position"]} count={positions.length / 3} array={positions} itemSize={3} /> <bufferAttribute attachObject={["attributes", "color"]} count={colors.length / 3} array={colors} itemSize={3} /> <bufferAttribute attachObject={["attributes", "normal"]} count={normals.length / 3} array={normals} itemSize={3} /> </bufferGeometry> <meshPhongMaterial attach="material" side={DoubleSide} vertexColors={true} /> </mesh> <hemisphereLight intensity={1.5} /> </Canvas> ); }; export default App;
内容的提问来源于stack exchange,提问作者bryyytl
相关产品推荐
相关产品推荐

