본문 바로가기

Three.js/Study

Three.js 개발환경 세팅 및 큐브 생성

해당 글은 유튜브 GIS DEVELPOPER 채널의 영상을 보고 개인적인 스터디 차원에서 메모하는 글입니다.

 

1. VScode 설치

 

2. Node.js 설치

 

3. 스터디를 위한 폴더 생성 후 VScode로 열기

 

4. VScode 에서 새 터미널 열기

 

5. 터미널에서 개발 환경에 필요한 npm 설치

npm create vite@latest . //설치시 사용할 프레임 워크는 Vanilla, 언어는 TypeScript 로 선택


//기본 라이브러리 설치
npm install              //라이브러리 설치를 위한 npm 설치


//Three.js를 이용하기 위한 라이브러리 설치
npm install @types/three  //Three.js에 대한 타입 정의가 되어있는 라이브러리, 타입스크립트를 사용하기 위해 필요
npm install three.        //Three.js 라이브러리

//프로젝트 실행을 위한 서버 구동
npm run dev

 

 

6. 구동 후 터미널의 로컬 호스트 링크 를 클릭

 

 

 

 

7. 자동으로 생성된 main.ts 에서 import './style.css' 만 남기고 모두 삭제

 

8. style.css 에서 전체 코드 삭제 후 다음 코드 입력

 

style.css

#app {
  position: absolute;
  inset: 0;
  background-color: black;
}

 

 

9. main.ts 작성

 

main.ts

import './style.css'
import * as THREE from 'three'

// App 클래스 정의
class App{

  // 렌더러 생성
  private renderer: THREE.WebGLRenderer
  
  // id 가 app 인 div를 참조하는 DOM 객체 생성
  private domApp: Element

  // scene 객체 생성
  private scene: THREE.Scene

  // 카메라, 광원, 모델을 참조하기 위한 필드 생성
  private camera?: THREE.PerspectiveCamera // ? 는 PerspectiveCamera 객체나 Undefine 객체를 가질 수 있게 함

  // cube 를 추가
  private cube?: THREE.Mesh


  constructor(){
    console.log('Hello three.js')
    this.renderer = new THREE.WebGLRenderer({ antialias: true}) //antialias 계단 현상 방지
    this.renderer.setPixelRatio(Math.min(2, window.devicePixelRatio)) //현재 모니터의 픽셀 비율을 가져옴, 팍셀 비율을 2로 설정

    this.domApp = document.querySelector('#app')! //!는 쿼리셀렉터의 발언값이 Null이 아닐때만 적용
    this.domApp.appendChild(this.renderer.domElement) // canvas 타입의 돔 객체

    this.scene = new THREE.Scene() //scene 객체

    // 카메라, 광원, 모델 객체
    this.setupCamera()
    this.setupLight()
    this.setupModels()

    // 객체의 이벤트
    this.setupEvents()
  }

  private setupCamera(){
    // 카메라의 렌더링 비율을 얻기 위해 domApp 객체의 가로 세로 값을 가져옴
    const width = this.domApp.clientWidth
    const height = this.domApp.clientHeight

    // 카메라 객체 생성
    this.camera = new THREE.PerspectiveCamera(75, width/height, 0.1, 100)

    // 카메라 위치
    this.camera.position.z = 2 // 카메라의 위치 x,y,z 는 0, 0, 2 로 세팅

  }

  private setupLight(){
    // 광원 세팅
    const color = 0xffffff //색상
    const intensity = 2 //강도
    const light = new THREE.DirectionalLight(color, intensity)
    light.position.set(-1, 2, 4) //위치

    this.scene.add(light) // scene 에 광원 추가
  }

  private setupModels(){
    // 모델은 Geometry 와 Material 로 구성
    const geometry = new THREE.BoxGeometry(1,1,1) // 정육면체 모양의 박스
    const material = new THREE.MeshPhongMaterial({color: 0xf1c40f}) // 재질과 컬러 

    // 모델 생성
    this.cube = new THREE.Mesh(geometry, material) // 모델은 Three.js에서 Mesh 클래스로 나타냄

    // cube를 scene 에 자식으로 추가
    this.scene.add(this.cube)

  }

  private setupEvents(){
    window.onresize = this.resize.bind(this) // 브라우저의 크기가 변경될 때 사이즈 변경
    this.resize() // 첫 실행 시 리사이즈 실행

    // render 실행
    this.renderer.setAnimationLoop(this.render.bind(this))

  }

  private resize(){
    const width = this.domApp.clientWidth
    const height = this.domApp.clientHeight

    const camera = this.camera
    if(camera){
      camera.aspect = width / height
      camera.updateProjectionMatrix()
    }

    this.renderer.setSize(width,height)
  }

  // 모델 객체의 애니메니션 정의
  private update(time: number){ // time 인자 값은 애니메이션 기능을 추가할 때 중요한 요소
    time *= 0.001 // time 인자는 원래 밀리세컨드 단위라서 세컨드 단위로 변경

    const cube = this.cube
    if(cube){
      cube.rotation.x = time
      cube.rotation.y = time
    }
  }  

  // 렌더링을 위한 메서드
  private render(time: number){

    this.update(time) // 모델의 애니메이션 호출
    this.renderer.render(this.scene, this.camera!) // 렌더러 객체에 랜더 메서드를 호출해서 랜더링
  }

}



// App 클래스 생성
new App()

 

 

 

최종 결과

 

 

반응형

'Three.js > Study' 카테고리의 다른 글

geometry #03  (0) 2024.08.05
geometry #02  (0) 2024.08.05
geometry #01  (0) 2024.08.02