three.js | 텍스처와 조명이 적용된 3D 큐브 구현하기

가잉·2025년 4월 5일

JavaScript

목록 보기
4/4

지난 글에서는 기본적인 three.js 큐브를 만들어봤다면 이번에는 큐브에 텍스처(질감)를 입히고 조명을 더해 훨씬 더 실제에 가까운 입체적인 표현을 구현해봤습니다.

배경 색상은 제가 좋아하는 연핑크 색상으로 변경했어요!


🧩 전체 코드

import * as THREE from 'three'
import { WEBGL } from './webgl'

// 텍스처 로더 추가
const textureLoader = new THREE.TextureLoader()
const texture = textureLoader.load('./static/styles/textures/marble.png')

if (WEBGL.isWebGLAvailable()) {
  // 장면
  const scene = new THREE.Scene()
  scene.background = new THREE.Color('#fce4ec')

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

  // 렌더러
  const renderer = new THREE.WebGLRenderer()
  renderer.setPixelRatio(window.devicePixelRatio)
  renderer.setSize(window.innerWidth, window.innerHeight)

  document.body.appendChild(renderer.domElement)

  // 매쉬
  const geometry = new THREE.BoxGeometry(0.5, 0.5, 0.5)
  const material = new THREE.MeshStandardMaterial({
    map: texture, // 텍스처를 재질에 적용
  })
  const cube = new THREE.Mesh(geometry, material)
  scene.add(cube)

  // 빛 추가
  // 환경광 (전체를 은은하게 비추는 기본 조명)
  const ambientLight = new THREE.AmbientLight(0xffffff, 0.4)
  scene.add(ambientLight)

  // 방향광 (태양처럼 한 방향에서 오는 조명)
  const directionalLight = new THREE.DirectionalLight(0xffffff, 1)
  directionalLight.position.set(3, 3, 2)
  scene.add(directionalLight)

  function render(time) {
    time *= 0.001

    cube.rotation.x = time
    cube.rotation.y = time

    renderer.render(scene, camera)

    requestAnimationFrame(render)
  }
  requestAnimationFrame(render)
} else {
  var warning = WEBGL.getWebGLErrorMessage()
  document.body.appendChild(warning)
}

1. 텍스처 적용하기

const textureLoader = new THREE.TextureLoader()
const texture = textureLoader.load('./static/styles/textures/marble.png')
  • TextureLoader를 사용해 이미지를 불러옵니다.
  • 이 텍스처를 MeshStandardMaterialmap 속성에 적용해주면 도형 표면에 질감을 입힐 수 있습니다.

2. 고해상도 디스플레이 대응

renderer.setPixelRatio(window.devicePixelRatio)
  • Mac이나 고해상도 디스플레이에서 화면이 흐릿하게 보이는 걸 방지합니다.
  • 이 코드를 추가하면 더 선명하고 또렷한 그래픽으로 출력됩니다.

3. 조명 넣기

const ambientLight = new THREE.AmbientLight(0xffffff, 0.4)
scene.add(ambientLight)

const directionalLight = new THREE.DirectionalLight(0xffffff, 1)
directionalLight.position.set(3, 3, 2)
scene.add(directionalLight)
  • AmbientLight 는 전체를 은은하게 비춰주는 기본 조명입니다.
  • DirectionalLight 는 햇빛처럼 한 방향에서 강하게 비춰주는 조명입니다.
  • 두 조명을 함께 사용하면 오브젝트가 너무 어둡게 보이거나 한쪽만 밝아지는 문제를 피할 수 있어 더 자연스럽고 입체감 있는 장면을 만들 수 있습니다.

4. 텍스처 응용 예시

profile
공부합니다.

0개의 댓글