TIL / 2022.10.26

박동준·2023년 10월 26일
0

TIL

목록 보기
1/2
post-thumbnail

React-three-fiber

react renderer for threejs

줄여서 R3F three.js를 React에서 더욱 사용하기 쉽도록 개발 된 라이브러리이다. 우선 three.js가 어떤 것인지 알아보도록 하자.

three.js란?

three.js는 웹 브라우저에서 3차원 컴퓨터 그래픽스 애니메이션 응용을 만들고 표현하기 위해 사용되는 자바스크립트 라이브러리이자 API이다.
아래에 보이는 격자들의 모든 썸네일이 three.js 로 만들어진 웹 브라우저이다.

3D웹 개발을 위해서 사용하는 three.js에 대해서는 알고 있었으나 Vanilla JavaScript 기반으로 React에서 사용하기에는 어려운점들이 있었다. 그러다 이번에 R3F의 존재에 대해서 알게 되었다.

어떤것이 다른가

  • 코드의 가독성과 개발이 더욱 쉬워졌다.
    three.js의 기본 docs의 정육면체 코드를 보면 아래와 같다.

    import * as THREE from 'three';
    
    const scene = new THREE.Scene();
    const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
    
    const renderer = new THREE.WebGLRenderer();
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.body.appendChild( renderer.domElement );
    
    const geometry = new THREE.BoxGeometry( 1, 1, 1 );
    const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
    const cube = new THREE.Mesh( geometry, material );
    scene.add( cube );
    
    camera.position.z = 5;
    
    function animate() {
        requestAnimationFrame( animate );
    
        cube.rotation.x += 0.01;
        cube.rotation.y += 0.01;
    
        renderer.render( scene, camera );
    }
    
    animate();

    딱 봐도 뭐가 뭔지 이해하는데 시간이 걸리고 각 method들을 찾는데 시간이 소요된다. 나도 처음에는 이걸 이해하는데 시간이 걸렸다.

    이제 같은 정육면제를 R3F를 이용 해 보자.

    import { useRef, useState } from 'react'
    import { Canvas, useFrame } from '@react-three/fiber'
    import { OrbitControls } from '@react-three/drei'
    
    function Box(props) {
      // This reference gives us direct access to the THREE.Mesh object
      const ref = useRef()
      // Hold state for hovered and clicked events
      // Subscribe this component to the render-loop, rotate the mesh every frame
      useFrame((state, delta) => (ref.current.rotation.x += delta))
      // Return the view, these are regular Threejs elements expressed in JSX
      return (
        <mesh
          {...props}
          ref={ref}>
          <boxGeometry args={[1, 1, 1]} />
        </mesh>
      )
    }
    
    export default function App() {
      return (
        <Canvas>
          <Box position={[1.2, 0, 0]} />
          <OrbitControls />
        </Canvas>
      )
    }
    

    박스를 렌더링시키는 커스텀 태그와 컴포넌트로 이루어져 기존 React 를 이용한 개발을 했던 개발자에게는 더욱 친숙하게 사용할 수 있게 되었다.

결론

오늘은 간단하게 three.js와 R3F를 비교하여 새로이 알게 된 R3F의 장점을 알게 되었다. 앞으로는 R3F를 이용하여 3D 웹 환경을 더욱 쉽게 구축할 수 있을 것 같다.

profile
과거를 딛고 나아가는 개발자 박동준입니다

0개의 댓글