web graphics

Three.js 프로젝트 가장 쉽게 시작하기: (1) 초기 세팅

ainniz 2024. 6. 16. 18:49
  • build tool로 vite 사용
  • 크롬  브라우저 기준
  • 간단한 프로젝트 제작 시

0. 초기 설정

  • vite를 사용하기 위해 node.js가 설치되어 있어야 한다. node -v로 확인할 수 있다.
  • npm init -y를 실행하면 NPM은 Node.js 프로젝트를 실행하는 데 필요한 최소한의 정보를 포함하는 package.json을 생성한다. ( npm init -y 명령어는 Node.js 프로젝트를 빠르게 초기화하는 명령어 )

프로젝트 시작 초기 명령어

1. vite와 three 패키지를 설치한다.

의존성 추가

 

2. package.json의 scripts 부분을 수정한다.

scripts 섹션에 vite 관련 명령어 추가

3. vite.config.js 파일을 추가한다.

import restart from 'vite-plugin-restart'

export default {
    root: 'src/', // Sources files (typically where index.html is)
    publicDir: '../static/', // Path from "root" to static assets (files that are served as they are)
    server:
    {
        host: true, // Open to local network and display URL
        open: !('SANDBOX_URL' in process.env || 'CODESANDBOX_HOST' in process.env) // Open if it's not a CodeSandbox
    },
    build:
    {
        outDir: '../dist', // Output in the dist/ folder
        emptyOutDir: true, // Empty the folder first
        sourcemap: true // Add sourcemap
    },
    plugins:
    [
        restart({ restart: [ '../static/**', ] }) // Restart server on static file change
    ],
}

4. src 폴더 내 html, css, js 파일을 만든다.

초기 디렉터리

5. 각 파일을 수정한다.

html

! shortcut으로 빠르게 html 템플릿 입력
title 요소 수정 및 link, canvas, script 요소 추가

  • script type="module"로 설정해주는 것을 잊지 않는다.

css

3d 그래픽을 브라우저 화면에 꽉 차게 랜더링하기 위한 css 파일 설정

  • 전체 `margin`과 `padding`을 없애 브라우저에서 기본 설정된 여백을 없애준다.
  • `overflow: hidden;`을 통해 스크롤을 없앤다.
  • `.webgl` canvas의 위치를 고정하고 테두리를 없앤다.

javascript

three.js 패키지 전체를 import 하고 canvas element 정의한 코드

6. npm run dev를 통해 실행하고 브라우저에서 확인한다.

npm run dev 터미널에 입력
해당 도메인에서 잘 작동하는 것을 확인

 

 

다음 단계: https://be-at-peace.tistory.com/13


참고 자료: three.js journey 3강