three.jsreact-three-fiberreact-three-drei

React three fiber using different materials on faces of cylinder


I am trying to create a cylinder with different colors on faces. I was able to do this using three.js. But while I am trying to implement this on r3f, I am not able to do this.

<Canvas frameloop="demand" camera={{ position: [75, 1, 0.1], zoom: 20 }}>
    <mesh>
      <cylinderGeometry />
      <meshBasicMaterial color={0xff0000} />
      <meshBasicMaterial color={0x00ff00} />
    </mesh>
    <OrbitControls />
  </Canvas>

I was able to do this on three.js by passing the materials as an array to the mesh. I don't know how to do this in r3f.

Codesandbox: here


Solution

  • Try this

    import "./styles.css";
    import { Canvas } from "@react-three/fiber";
    import { OrbitControls } from "@react-three/drei";
    
    const colors = [0x00ff00, 0xff0000, 0x0000ff];
    
    export default function App() {
      return (
        <div className="App">
          {/* eslint-disable */}
          <Canvas frameloop="demand" camera={{ position: [75, 1, 0.1], zoom: 15 }}>
            <mesh>
              <cylinderGeometry />
              {colors.map((color, index) => (
                <meshBasicMaterial
                  key={index}
                  attach={`material-${index}`}
                  color={color}
                />
              ))}
            </mesh>
            <OrbitControls />
          </Canvas>
          {/* eslint-enable */}
        </div>
      );
    }
    

    https://codesandbox.io/p/devbox/cylinder-forked-yl47v5?file=%2Fsrc%2FApp.js%3A7%2C32

    https://github.com/pmndrs/react-three-fiber/blob/484c6787bd4862d50a6fd38e436413f06f394fdb/docs/tutorials/v8-migration-guide.mdx#unified-attach-api