설치 및 기본 사용법

0

Three.js는 WebGL을 이용해 브라우저에서 3D 컴퓨터 그래픽을 생성하고 애니메이션하기 위한 JavaScript 라이브러리다. 1

설치

Three.js는 NPM이나 CDN으로 설치할 수 있다.

방법 1: NPM으로 설치

  1. Node.js를 설치한다.
  2. Three.js와 Vite를 설치한다.
    npm install --save three
    npm install --save-dev vite
    
  3. 터미널에서 다음을 실행한다.
    npx vite
    
  4. 결과를 확인하려면 localhost URL(예: http://localhost:5173/)을 연다.

방법 2: CDN으로 설치

  1. index.html의 <head></head> 태그 안에 import map을 삽입한다. {version}은 0.153.1과 같은 실제 Three.js 버전으로 바꾸어야 한다.
    <!-- index.html -->
    <script type="importmap">
     {
         "imports": {
             "three": "https://unpkg.com/three@{version}/build/three.module.js",
             "three/addons/": "https://unpkg.com/three@{version}/examples/jsm/"
         }
     }
    </script>
    
  2. 서버를 실행하기 위해 Node.js와 Vite를 설치한다.
    npm install --save-dev vite
    npx serve .
    

    또는 VS Code를 사용한다면 Live Server로 서버를 실행할 수 있다.

사용법

Three.js를 사용하려면 main.js에서 THREE를 import해야 한다. 이는 설치 방법에 따라 다르다. 방법 1로 Three.js를 설치했다면 다음과 같이 import한다.

// main.js
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
...

방법 2로 Three.js를 설치했다면 다음과 같이 사용한다.

// main.js
import * as THREE from 'three'
import { OrbitControls } from 'three/addon/controls/OrbitControls.js';
...

위 스크립트가 다른 html에 추가될 때, typemodule인지 확인한다. 이후 포스트에서는 CDN으로 Three.js를 import하고 VS Code의 Live Server를 사용하여 예제를 작성한다.