본문 바로가기
프론트엔드/Three.js

Three.js로 간단한 3D 장면 만들기

by CODESIGN 2025. 1. 28.

이번 글에서는 Three.js를 사용해 간단한 3D 장면(Scene)을 만들어보겠습니다. 코드와 함께 주요 개념들을 정리해보았습니다.

Three.js 프로젝트 기본 설정


Three.js는 웹에서 3D 그래픽을 렌더링 할 수 있도록 도와주는 라이브러리입니다. 먼저 Three.js를 설치하거나 CDN으로 로드한 후 사용합니다.

 

 

최종 결과물


 

 

코드 설명


1. 씬(Scene) 생성

const scene = new THREE.Scene();
scene.background = new THREE.Color('F0F0F0'); // 장면의 배경색 설정

 

Scene은 3D 객체를 추가하는 컨테이너 역할을 합니다. 여기에서는 배경색을 #F0F0F0으로 설정했습니다.


2. 카메라(Camera) 추가

const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;


Three.js에는 여러 종류의 카메라가 있지만, PerspectiveCamera를 사용했습니다.  
- `fov`: 시야(Field of View) 각도 (75도 설정).  
- `aspect`: 화면 비율 (창의 너비/높이).  
- `near`, `far`: 카메라가 인식할 수 있는 거리 범위.


3. 큐브(Cube) 객체 생

const geometry = new THREE.BoxGeometry(); // 박스 형태의 기본 지오메트리
const material = new THREE.MeshLambertMaterial({ 
  color: '#468585', 
  emissive: '#468585' 
});
const cube = new THREE.Mesh(geometry, material);
scene.add(cube); // 큐브를 씬에 추가


- `BoxGeometry`: 박스 형태의 기본 도형(지오메트리).
- `MeshLambertMaterial`: 재질(Material) 중 하나로, 조명 효과를 받을 수 있음.
- `emissive`: 물체가 스스로 빛을 내는 발광 색상을 설정.

 


4. 조명(Lighting) 추가

const light = new THREE.DirectionalLight(0x9CDBA6, 10); // 조명 생성
light.position.set(1, 1, 1); // 조명의 위치 설정
scene.add(light);


3D 그래픽에서 조명이 없으면 아무것도 보이지 않습니다.  
여기서는 DirectionalLigh(직사광 조명)를 추가하여 물체를 밝히도록 설정했습니다.


5. 렌더러(Renderer) 설정

const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight); // 창 크기에 맞게 설정
document.body.appendChild(renderer.domElement); // HTML에 캔버스 추가


렌더러는 장면과 카메라를 사용해 화면에 3D 콘텐츠를 표시하는 역할을 합니다.


6. 애니메이션(Animate) 추가

function animate() {
  requestAnimationFrame(animate); // 매 프레임마다 호출
  cube.rotation.x += 0.01; // x축으로 회전
  cube.rotation.y += 0.01; // y축으로 회전
  renderer.render(scene, camera); // 씬과 카메라를 렌더링
}

animate();


`animate()` 함수는 `requestAnimationFrame()`을 이용해 반복적으로 호출됩니다. 여기에서는 큐브를 회전시키는 애니메이션을 추가했습니다.



전체 코드


import * as THREE from 'three';

// 1. 씬 생성
const scene = new THREE.Scene();
scene.background = new THREE.Color('F0F0F0');

// 2. 카메라 추가
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;

// 3. 큐브 생성
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshLambertMaterial({ color: '#468585', emissive: '#468585' });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);

// 4. 조명 추가
const light = new THREE.DirectionalLight(0x9CDBA6, 10);
light.position.set(1, 1, 1);
scene.add(light);

// 5. 렌더러 설정
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

// 6. 애니메이션
function animate() {
  requestAnimationFrame(animate);
  cube.rotation.x += 0.01;
  cube.rotation.y += 0.01;
  renderer.render(scene, camera);
}

animate();

 

 

실행 방법


1. 위 코드를 index.js 파일에 저장합니다.
2. 'index.html 파일에 `<script type="module" src="index.js"></script>`를 추가합니다.
3. 브라우저에서 실행하면 회전하는 큐브를 확인할 수 있습니다!

 

마무리


이 코드로 간단한 3D 장면을 만들어 보았습니다. 이제 기본을 익혔으니, 더 복잡한 지오메트리와 재질을 추가하거나, 카메라와 조명을 조정하면서 다양한 3D 장면을 제작해 보세요. 🚀

 

댓글