[React] Three.js 적용하기
Three.js 의 기본구조를 안다는 상태에서 작성했습니다. React에 Three.js를 적용해봅시다. 먼저 리액트 프로젝트를 만들고, three.js 를 사용하기 위해 3가지 패키지를 설치합니다. 저는 vite로 프로젝트를 만들었습니다.
npm init vite
- three.js
- react-three-fiber : three.js 를 리액트 문법에 맞게 사용할 수 있도록
- react-three/drei : react-three-fiber 하는 일을 좀 더 쉽게 도와줌.
npm install three @react-three/fiber @react-three/drei
기본 구조
Three.js는 기본적으로 html canvas 태그 안에서 렌더링됩니다. 따라서 react-three-fiber에 canvas 를 불러옵니다. canvas 컴포넌트안에 mesh 컴포넌트등과 같은 Three 관련 컴포넌트를 넣어주면 따로 선언 하지 않고도 알아서 인식합니다. (와옹!)
import { Canvas } from "@react-three/fiber";
function App() {
return (
<Canvas>
<mesh position={[2,2,2]}>
<boxGeometry attach="geometry" args={[3,3,3]}/>
<meshLambertMaterial attach="material" color="orange" />
</mesh>
</Canvas>
)
}
export default App;
활용
리액트에서 THREE 가 어떻게 동작하는 지 알았습니다. 직접 3D 모델링하여 렌더할 수 있겠지만 이미 만들어진 3D 모델을 가져와 적용해 볼 수 있어야겠죠. 무료 3D 모델링을 지원하는 사이트와 교육용 레파지토리가 있지만 그 중에서 sketchfab를 이용했습니다. 원하는 3D 모델을 골라 glTF파일로 다운로드합니다.
Log in to your Sketchfab account
sketchfab.com
레파지토리
교육용으로 3D 모델링을 지원한다.
https://github.com/drcmda/floating-shoe/tree/master/resources/gltf
*glTF? 3차원 장면과 모델을 표현하는 파일 포맷으로 JSON 형식으로 구성되어 있습니다.
압축을 풀면 다음과 같은 파일들을 볼 수 있습니다. 터미널을 켜 glTF파일이 있는 경로에 들어가 npx gltfjsx 파일명.gltf 명령어를 실행합니다. 해당 명령어는 glTF파일를 적용할 수 있는 js 파일을 자동 생성합니다. 리액트 프로젝트 public 폴더안에 license.txt와 생성된 자바스크립트파일 scene.jsx를 제외한 파일들을 넣습니다.
npx gltfjsx 파일명.gltf
npx gltfjsx scene.gltf 명령어로 만들어진 Scene.jsx 를 열어 살펴봅시다. @react-three/drei 에 useGLTF 를 가져와 public 폴더에 있는 gltf파일을 가져와 해당 3d 객체를 Model 컴포넌트로 만들어졌습니다.다음과같이 다른 파일로 분리할 수 있지만 구조를 쉽게 파악하기 위해 App.jsx에 Model 컴포넌트를 복사해 적용했습니다.
// Scene.jsx
/*
Auto-generated by: https://github.com/pmndrs/gltfjsx
Command: npx gltfjsx@6.2.13 scene.gltf
Author: kane_sk06 (https://sketchfab.com/kanesk06)
License: CC-BY-4.0 (http://creativecommons.org/licenses/by/4.0/)
Source: https://sketchfab.com/3d-models/sneakers-game-ready-textured-mockup-d9a4eda1845249a69d3c79814be9efc0
Title: Sneakers - Game Ready - Textured (Mockup)
*/
import React, { useRef } from 'react'
import { useGLTF } from '@react-three/drei'
export function Model(props) {
const { nodes, materials } = useGLTF('/scene.gltf')
return (
<group {...props} dispose={null}>
<mesh geometry={nodes.Object_4.geometry} material={materials.TEXTURE} />
<mesh geometry={nodes.Object_5.geometry} material={materials.TEXTURE} />
<mesh geometry={nodes.Object_6.geometry} material={materials.TEXTURE} />
</group>
)
}
useGLTF.preload('/scene.gltf')
App.jsx 입니다. Canvas 의 props 로 Canvas의 사이즈를 지정해줄 수 있고 카메라를 설치할 수 있습니다. 그리고 Canvas 컴포넌트 자식으로 조명과 넣고자 하는 Model 컴포넌트를 넣으면 끝입니다! ambientLight 컴포넌트는 조명이며 scene 내의 모든 object들에 전 방향에서 조명을 비춰줘줍니다. 인자로 조명색과 intensity 빛 강도를 지정해줄 수 있습니다. 그리고 @react-three/drei 패키지에 OrbitControls 를 Canvas 자식요소 하단에 배치하면 마우스로 3D 객체를 줌인아웃하거나 회전하는 등 인터랙션을 할 수 있습니다.
//App.jsx
import './App.css'
import React, { Suspense,useRef,useState } from 'react'
import {OrbitControls, useGLTF } from '@react-three/drei'
import {Canvas} from "@react-three/fiber"
export function Model(props) {
const { nodes, materials } = useGLTF('/scene.gltf')
return (
<group {...props} dispose={null}>
<mesh geometry={nodes.Object_4.geometry} material={materials.TEXTURE} />
<mesh geometry={nodes.Object_5.geometry} material={materials.TEXTURE} />
<mesh geometry={nodes.Object_6.geometry} material={materials.TEXTURE} />
{/* material-color={"red"} */}
</group>
)
}
function App() {
return (
<>
<Canvas
style={{ width: "70vw", height: "80vh", border: "1px solid black" }}
camera={{
aspect: 1,
fov: 100,
near: 0.1,
far: 1000,
position: [10, 10, 10],
}}
>
<ambientLight intensity={1.2}/>
{/* scene 내의 모든 object들에 전 방향에서 조명을 비춰준다. 강도 */}
<Model/>
<OrbitControls
enablePan={true}
enableRotate={true}
enableZoom={true}
/>
</Canvas>
</>
)
}
export default App
출처
https://www.youtube.com/watch?v=2jwqotdQmdQ&t=1476s
https://sketchfab.com/3d-models/photon-knight-c4b6483f7e3d4c9dbac92a837a97e76d
Photon Knight - Download Free 3D model by nigelgoh - Sketchfab
a low poly cyberpunk character design
sketchfab.com
https://docs.fileformat.com/ko/3d/gltf/
GLTF - GL 전송 파일 형식
GLTF 파일을 만들고 열 수 있는 GLTF 파일 및 API에 대해 알아보세요.
docs.fileformat.com
https://github.com/KhronosGroup/glTF-Tutorials/tree/master/gltfTutorial
https://github.com/KhronosGroup/glTF-Sample-Models/tree/master/2.0
https://velog.io/@iepppop/react-three.js-%EC%A0%81%EC%9A%A9%EB%B2%95
react three.js 적용법
은근 자료가 많은 게 아니여서 많이 헤맸다. 일단 무료 3D이미지를 다운 받는다.https://sketchfab.com/3d-models/smg-90-3b5371ff0db24407ab592997e5038ad3클릭한다gltp를 다운 받는다. 압축을 풀면 이렇게
velog.io