출처: https://blobmixer.14islands.com/
웹 게임 프로젝트를 진행하던 중 3D를 활용해보자는 의견을 받게 되었습니다. 저는 이번 기회에 Three.js와 R3F를 활용해 해보면 재미있는 프로젝트가 될 것 같아서 긍정적으로 받아들였습니다. 자료가 많지 않지만, 공식 문서를 참고하며 학습한 내용을 바탕으로 프로젝트에서 어떻게 활용했는지와 예제들을 통해 Three.js와 R3F에 대해 알아보겠습니다.
Three.js는 웹 페이지에서 3D 그래픽을 구현할 수 있도록 도와주는 JavaScript 라이브러리입니다. 기본적으로 WebGL(Web Graphics Library) 브라우저에서 실행되는 3D 그래픽 API 위에서 동작합니다. 직접 WebGL의 복잡한 부분을 다루지 않고도 3D 객체를 생성하고 렌더링하게 해줍니다.
Three.js로 만든 사이트 예:
https://patrickheng.com/
https://2050.earth/artworks/stolen-mind
출처: https://threejs.org/manual/#ko/fundamentals
npm install three
yarn add three
만약 folder안에 node_modules package.json 파일이 없다면
npm init -y
yarn init -y
이런 식으로 dependencies에 three가 들어가야합니다.준비가 다 되었다면 공식 문서에 나와있는 예제를 같이 해보죠. 제가 살짝 수정을 한 코드입니다.
foler안에는 index.html과 index.js 상태입니다.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<canvas id="c"></canvas>
<script type="module" src="./index.js"></script>
</body>
</html>
index.js
import * as THREE from './node_modules/three/build/three.module.js';
const canvas = document.querySelector('#c');
const renderer = new THREE.WebGLRenderer({ antialias: true, canvas });
renderer.setSize(window.innerWidth, window.innerHeight); // 크기 설정
const fov = 75;
const aspect = window.innerWidth / window.innerHeight; // 화면 비율
const near = 0.1;
const far = 5;
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.z = 2;
const scene = new THREE.Scene();
const boxWidth = 1;
const boxHeight = 1;
const boxDepth = 1;
const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
const material = new THREE.MeshBasicMaterial({ color: 0x44aa88 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
function render() {
renderer.render(scene, camera);
}
render();
이렇게 작성하고 실행하면 그냥 딱지같은게 생길겁니다. 사실 이건 1x1x1의 정육면체입니다. 조금 더 3D처럼 보이게 하기 위해서 애니메이션을 추가해보겠습니다. Mesh로 만든 객체에 rotate를 해주면 됩니다.
function animate() {
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
이번에는 여기까지 알아보고 다음 글부터는 기본 도형들에 대한 재미있는 예제를 들고 오겠습니다. 고생하셨어요.
출처:https://threejs.org/manual/#ko/fundamentals
공식 문서의 자료들과 examples들을 사용했습니다.