开发者问题收集

React-three-fiber 点不渲染

2022-04-17
2748

我开始学习 React-three-fiber,并尝试在画布上渲染一些点。我在网上找到了一些代码,但似乎无法在画布上渲染这些点。 控制台中没有错误。 我附上我正在运行的代码:

App.js

import { OrbitControls } from "@react-three/drei";
import { Canvas } from '@react-three/fiber';
import './App.css';
import Points from './components/Points';
import Lights from './components/Lights';

function App() {
  return (
    <div className="App">
      <Canvas orthographic camera={{ zoom: 60 }} raycaster={{ params: { Points: { threshold: 0.2 } } }}> 
          <color attach="background" args={["#161c24"]}/>
          {/* <Lights/> */}
          <Points/>
          {/* <OrbitControls/> */}
      </Canvas>

    </div>
  );
}
export default App;

Point.js

import { useRef } from 'react';

const Points = () => {

    const attrib = useRef();
    const positions = new Float32Array(
        [1,1,1, 
         0,0,0]);
    const colors = new Float32Array(
        [1,0.5,0.5,
         1,0.5,0.5]);

    return (
        <points>
            <bufferGeometry attach="geometry">
                <bufferAttribute attachObject={["attributes", "position"]} count={positions.length / 3} array={positions} itemSize={3} />
                <bufferAttribute ref={attrib} attachObject={["attributes", "color"]} count={colors.length / 3} array={colors} itemSize={3} />
            </bufferGeometry>
            <pointsMaterial attach="material" vertexColors size={100} sizeAttenuation={false} />
        </points>
    );
}

export default Points;

我已经注释了 Lights 和 OrbitControls,因为它们与某些东西冲突,但什么都没有改变。我还尝试更改光线投射并使用其他类型的灯光代替我的自定义灯光,但没有任何效果。

1个回答

这是因为 R3F 在每个更新/发布中都会破坏某些功能,这很烦人,因为没有相关文档。我和你一样遇到过这个问题,所以这些代码片段应该可以回答你的问题:

function MyPoints() {
  const positions = new Float32Array(
      [-10,0,0, 
        10,0,0]);
  const colors = new Float32Array(
      [1,0.5,0.5,
        1,0.5,0.5]);

  return (
    <points>
        <bufferGeometry attach="geometry">
          <bufferAttribute
              attach="attributes-position"
              count={positions.length / 3}
              array={positions}
              itemSize={3}
              usage={THREE.DynamicDrawUsage}
            />
            <bufferAttribute
              attach="attributes-color"
              count={colors.length / 3}
              array={colors}
              itemSize={3}
              usage={THREE.DynamicDrawUsage}
            />
        </bufferGeometry>
        <pointsMaterial attach="material" vertexColors size={10} sizeAttenuation={false} />
    </points>
  );

}

function App() {
  return (
    <div className='App'>
      <Canvas
        camera={{
          fov: 75,
          aspect: 2,
          near: 0.1,
          far: 1000,
          position: [0,0,20],
          rotation: [0,0,0]
        }}
      >               
        <MyPoints/>        
        <Controls/>
      </Canvas>
    </div>
  );
}
Darkensses
2022-04-18