Three.js는 자바스크립트 3D 라이브러리로, 브라우저에서 3D 그래픽을 구현할 수 있도록 도와줍니다. 내부적으로는 WebGL을 사용하지만, 복잡한 WebGL 코드를 추상화하여 훨씬 쉽게 사용할 수 있게 해줍니다.
WebGL(Web Graphics Library)는 자바스크립트를 이용해, 별도의 플러그인 없이 웹 브라우저에서 고성능의 2D 및 3D 그래픽을 렌더링할 수 있게 해주는 API입니다.
import * as THREE from "https://unpkg.com/three@0.150.0/build/three.module.js";
class App {
constructor() {
const divContainer = document.querySelector("#webgl-container");
this._divContainer = divContainer;
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(window.devicePixelRatio);
divContainer.appendChild(renderer.domElement);
this._renderer = renderer;
const scene = new THREE.Scene();
this._scene = scene;
WebGLRenderer : Three.js에서 화면에 그리기 위한 렌더러antialias : true : 계단 현상 제거 Scene : 3D 공간이며, 여기에 객체(모델), 조명 등을 추가 _setupCamera() {
const width = this._divContainer.clientWidth;
const height = this._divContainer.clientHeight;
const camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 100);
camera.position.z = 2;
this._camera = camera;
}
PerspectiveCamera : 사람 눈처럼 원근감 있는 시야를 제공.75 : 시야각(FOV)width/height : 화면 비율0.1~100 : 카메라가 볼 수 있는 거리 범위 _setupLight() {
const light = new THREE.DirectionalLight(0xffffff, 1);
light.position.set(-1, 2, 4);
this._scene.add(light);
}
_setupModel() {
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshPhongMaterial({ color: 0x044aa8 });
const cube = new THREE.Mesh(geometry, material);
this._scene.add(cube);
this._cube = cube;
}
MeshPhongMaterial : 광원 반응이 있는 재질Mesh : geometry + material을 합쳐서 3D 객체 생성 resize() {
const width = this._divContainer.clientWidth;
const height = this._divContainer.clientHeight;
this._camera.aspect = width / height;
this._camera.updateProjectionMatrix();
this._renderer.setSize(width, height);
}
render(time) {
this._renderer.render(this._scene, this._camera);
this.update(time);
requestAnimationFrame(this.render.bind(this));
}
render()를 매 프레임마다 호출update(time) {
time *= 0.001;
this._cube.rotation.x = time;
this._cube.rotation.y = time;
}
window.onload = () => {
new App();
};