초기 canvas로 띄웠다가 마우스 회전 및 확대 축소를 넣기 위해 OrbitControls 로 변경
주석을 자세히 달았으니 소스를 남기고 이만~
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<title>glTF Viewer with OrbitControls</title>
<style>
body { margin: 0; }
canvas { display: block; }
</style>
<!-- import map: ES 모듈 import 경로에 별명을 붙여주는 설정 -->
<script type="importmap">
{
"imports": {
"three": "https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js",
"three/examples/jsm/": "https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/"
}
}
</script>
</head>
<body>
<script type="module">
// three.js 전체 모듈을 THREE라는 이름으로 가져옴
import * as THREE from 'three';
// glTF 로더와 궤도 컨트롤(마우스로 회전) 가져오기
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
// 3D 장면(scene) 생성
const scene = new THREE.Scene();
// 카메라 생성: 시야각 75도, 화면 비율, 클리핑 거리 설정
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
// 렌더러(WebGLRenderer) 생성 및 해상도 설정
// const renderer = new THREE.WebGLRenderer({ antialias: true }); // 테두리 부드럽게
// renderer.setSize(window.innerWidth, window.innerHeight); // 전체 창 크기에 맞게 설정
// document.body.appendChild(renderer.domElement); // 렌더러 캔버스를 문서에 추가
const renderer = new THREE.WebGLRenderer({ antialias: true });
scene.background = new THREE.Color(0xffffcc); // 배경을 흰색으로 설정
renderer.setSize(150, 200); // 👉 가로 150px, 세로 200px로 설정
renderer.domElement.style.position = 'absolute'; // 👉 좌측 상단 고정 위치
renderer.domElement.style.left = '1px';
renderer.domElement.style.top = '1px';
document.body.appendChild(renderer.domElement);
// ⬇️ 마우스로 카메라를 돌릴 수 있게 컨트롤 추가
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true; // 회전 시 관성 느낌 적용
controls.dampingFactor = 0.05; // 감쇠 계수(회전 속도 늦추기)
// 하늘/땅 방향에 따라 색이 다른 반구형 조명 추가
const light = new THREE.HemisphereLight(0xffffff, 0x444444);
light.position.set(0, 20, 0);
scene.add(light);
// glTF 파일 로더 생성
const loader = new GLTFLoader();
// 모델 파일 불러오기 (.gltf 파일)
loader.load('./model/scene.gltf', (gltf) => {
scene.add(gltf.scene); // 모델을 씬에 추가
animate(); // 렌더링 시작
}, undefined, (error) => {
console.error(error); // 에러 발생 시 콘솔에 표시
});
// 카메라 위치 설정 (x=0, y=1.5, z=5)
camera.position.set(0, 1.5, 5);
// 매 프레임마다 씬을 다시 그려주는 함수
function animate() {
requestAnimationFrame(animate); // 브라우저에 다음 프레임 요청
controls.update(); // OrbitControls 변화 적용
renderer.render(scene, camera); // 씬과 카메라를 이용해 화면 렌더링
}
</script>
</body>
</html>
source : https://github.com/wclee7/gltfhtml