Vanilla JavaScript 기본 사용법

Vanilla JavaScript 환경에서 VRISM Viewer SDK를 4단계로 익혀보세요. React 없이도 완전한 3D 뷰어를 구현할 수 있습니다.

1단계: 뷰어 띄우기

CDN으로 간단하게 시작하기

HTML에 직접 스크립트를 추가하여 뷰어를 초기화해보겠습니다.

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>VRISM Viewer</title>
  <script src="https://unpkg.com/@vrism/viewer-sdk@0.1.0/dist/vanilla/umd.js"></script>
</head>
<body>
  <div id="viewer-container" style="width: 100%; height: 500px;"></div>
  
  <script>
    // VrismSDK는 전역 변수로 사용 가능
    const viewer = VrismSDK.VrismViewer.init('viewer-container', {
      token: 'your-token-here',
      contentId: 'your-content-id',
      onLoadFinish: () => console.log('로드 완료'),
      onStepChange: (options) => console.log('스텝 변경:', options.step)
    });
  </script>
</body>
</html>

이것만으로도 완전한 3D 뷰어가 동작합니다!

✅ 팁: Vanilla SDK에서는 이벤트 핸들러(onLoadFinish, onStepChange 등)를 VrismViewer.init 호출 시 옵션으로 함께 전달해야 합니다.

ES6 모듈로 사용하기

모던 프런트엔드 빌드 환경(예: Vite, Webpack, Rollup 등)에서는 ES6 모듈로 사용할 수 있습니다:

import { VrismViewer } from '@vrism/viewer-sdk/vanilla';

// 뷰어 인스턴스 생성
const viewer = VrismViewer.init('viewer-container', {
  token: 'your-token-here',
  contentId: 'your-content-id',
  onLoadFinish: () => console.log('로드 완료'),
  onStepChange: (options) => console.log('스텝 변경:', options.step)
});

컨테이너 스타일링

뷰어의 크기와 위치를 조정할 수 있습니다:

<div id="viewer-container" style="
  width: 800px;
  height: 600px;
  border: 1px solid #ddd;
  border-radius: 8px;
  margin: 20px auto;
"></div>

2단계: 옵션 설정하기

UI 요소 제어

필요한 UI 요소만 선택적으로 표시할 수 있습니다:

const viewer = VrismSDK.VrismViewer.init('viewer-container', {
  token: 'your-token-here',
  contentId: 'your-content-id',
  config: {
    ui: {
      // 배경색 변경
      viewerBackgroundColor: '#f8f9fa',
      
      // UI 요소 끄고 켜기
      gestureGuide: true,           // 제스처 가이드 표시
      fullscreenButton: true,       // 전체화면 버튼 표시
      userGuide: false,             // 사용자 가이드 숨김
      
      // 로더 커스터마이징
      loader: {
        type: 'circle',             // 'circle' 또는 'bar'
        size: 'medium',             // 'small', 'medium', 'large'
        loaderFillColor: '#007bff', // 로더 색상
        loaderPlaceholderColor: '#e9ecef'
      }
    }
  }
});

카메라 초기 설정

뷰어의 초기 카메라 위치와 동작을 설정할 수 있습니다:

const viewer = VrismSDK.VrismViewer.init('viewer-container', {
  token: 'your-token-here',
  contentId: 'your-content-id',
  config: {
    camera: {
      // 자동 회전 (음수: 반시계방향, 양수: 시계방향, 0: 정지)
      autoRotation: -2,
      
      // 사용자 조작 제어
      controls: {
        enableZoom: true,    // 줌 허용
        enablePan: true,     // 팬(이동) 허용  
        enableRotate: true   // 회전 허용
      },
      
      // 데스크톱 초기 위치
      desktop: {
        angle: { x: 0.2, y: 0.1 },  // 초기 각도
        zoom: 1.5,                   // 초기 줌
        limits: {
          angleUp: 1.5,              // 위쪽 각도 제한
          angleDown: -1.5,           // 아래쪽 각도 제한
          zoomMin: 0.5,              // 최소 줌
          zoomMax: 3.0               // 최대 줌
        }
      }
    }
  }
});

스텝 기능 설정

제품의 여러 각도나 기능을 단계별로 보여줄 수 있습니다:

const viewer = VrismSDK.VrismViewer.init('viewer-container', {
  token: 'your-token-here',
  contentId: 'your-content-id',
  config: {
    ui: {
      step: {
        enabled: true,          // 스텝 기능 활성화
        stepControls: true,     // 이전/다음 버튼 표시
        stepDots: true,         // 스텝 도트 네비게이션 표시
        stepAnnotation: true,   // 3D 마커 표시
        items: [
          {
            id: 1,
            anchor: {
              desktop: {
                position: { x: 0, y: 0, z: 5 },
                target: { x: 0, y: 0, z: 0 }
              },
              mobile: {
                position: { x: 0, y: 0, z: 5 },
                target: { x: 0, y: 0, z: 0 }
              }
            }
          },
          {
            id: 2,
            anchor: {
              desktop: {
                position: { x: 2, y: 1, z: 3 },
                target: { x: 0, y: 0, z: 0 }
              },
              mobile: {
                position: { x: 2, y: 1, z: 3 },
                target: { x: 0, y: 0, z: 0 }
              }
            },
            annotation: {
              marker: {
                position: { x: 1, y: 0.5, z: 0 }
              },
              content: {
                title: '디테일 보기',
                description: '특정 디테일을 강조합니다.'
              }
            }
          }
        ]
      }
    }
  }
});

💡 팁: 마커는 끄고 스텝 기능만 사용하려면 stepAnnotation: false로 설정하세요.

3단계: 이벤트 처리하기

로딩 상태 처리

뷰어의 로딩 상태를 감지하고 처리할 수 있습니다:

<div id="loading-status">로딩 중...</div>
<div id="viewer-container" style="width: 100%; height: 500px;"></div>

<script>
  let loadingProgress = 0;

  const viewer = VrismSDK.VrismViewer.init('viewer-container', {
    token: 'your-token-here',
    contentId: 'your-content-id',
    onLoadUpdate: (percentage) => {
      loadingProgress = percentage || 0;
      document.getElementById('loading-status').textContent = 
        `로딩 중... ${loadingProgress}%`;
    },
    onLoadScene: () => {
      console.log('뷰어 사용 준비 완료');
      document.getElementById('loading-status').style.display = 'none';
    }
  });
</script>

스텝 변경 감지

사용자가 스텝을 변경했을 때를 감지할 수 있습니다:

<div id="current-step">현재 스텝: 1</div>
<div id="viewer-container" style="width: 100%; height: 500px;"></div>

<script>
  let currentStep = 0;

  const viewer = VrismSDK.VrismViewer.init('viewer-container', {
    token: 'your-token-here',
    contentId: 'your-content-id',
    config: {
      ui: { step: { enabled: true } }
    },
    onStepChange: (options) => {
      console.log('스텝 변경:', options.step, options.direction);
      currentStep = options.step || 0;
      document.getElementById('current-step').textContent = 
        `현재 스텝: ${currentStep + 1}`;
    }
  });
</script>

에러 처리

뷰어에서 발생할 수 있는 에러를 처리할 수 있습니다:

<div id="error-message" style="display: none; color: red;"></div>
<div id="viewer-container" style="width: 100%; height: 500px;"></div>

<script>
  const viewer = VrismSDK.VrismViewer.init('viewer-container', {
    token: 'your-token-here',
    contentId: 'your-content-id',
    onError: (error) => {
      console.error('뷰어 에러:', error);
      const errorDiv = document.getElementById('error-message');
      errorDiv.textContent = `에러가 발생했습니다: ${error.message}`;
      errorDiv.style.display = 'block';
    }
  });
</script>

4단계: 뷰어 제어하기

뷰어 인스턴스 메서드 사용

뷰어를 프로그래밍 방식으로 제어할 수 있습니다:

<div>
  <button onclick="handleControls()">설정 확인</button>
  <button onclick="handleStepControl()">2번 스텝으로</button>
  <button onclick="handleUIControl()">UI 제어</button>
</div>
<div id="viewer-container" style="width: 100%; height: 500px;"></div>

<script>
  const viewer = VrismSDK.VrismViewer.init('viewer-container', {
    token: 'your-token-here',
    contentId: 'your-content-id',
    config: {
      ui: { step: { enabled: true } }
    }
  });
  
  // 제어 함수들
  window.handleControls = async () => {
    // 현재 설정 확인
    const config = await viewer.getViewerConfig();
    console.log('현재 설정:', config);
  };
  
  window.handleStepControl = () => {
    // 특정 스텝으로 이동
    viewer.setStep(2);
  };
  
  window.handleUIControl = () => {
    // 제스처 가이드 끄기
    viewer.setGestureGuideShow(false);
    
    // 전체화면 열기
    viewer.setFullscreenOpen(true);
  };
</script>

3D 위치 선택 기능

사용자가 3D 모델에서 위치를 선택할 수 있게 할 수 있습니다:

<button onclick="handlePickPosition()">3D 위치 선택하기</button>
<div id="selected-position" style="display: none;">
  <h4>선택된 위치:</h4>
  <p id="position-x">X: 0.00</p>
  <p id="position-y">Y: 0.00</p>
  <p id="position-z">Z: 0.00</p>
</div>
<div id="viewer-container" style="width: 100%; height: 500px;"></div>

<script>
  const viewer = VrismSDK.VrismViewer.init('viewer-container', {
    token: 'your-token-here',
    contentId: 'your-content-id',
    config: {
      ui: {
        step: {
          enabled: true,  // getClickedPosition 사용을 위해 필수
          items: [        // 1개 이상 필수
            {
              id: 1,
              anchor: {
                desktop: {
                  position: { x: 0, y: 0, z: 5 },
                  target: { x: 0, y: 0, z: 0 }
                }
              }
            }
          ]
        }
      }
    }
  });

  window.handlePickPosition = async () => {
    console.log('3D 모델에서 원하는 위치를 클릭하세요');

    const position = await viewer.getClickedPosition();
    if (position) {
      console.log('선택된 위치:', position);
      
      // 선택된 위치 표시
      document.getElementById('position-x').textContent = 
        `X: ${position.anchor.position.x.toFixed(2)}`;
      document.getElementById('position-y').textContent = 
        `Y: ${position.anchor.position.y.toFixed(2)}`;
      document.getElementById('position-z').textContent = 
        `Z: ${position.anchor.position.z.toFixed(2)}`;
      document.getElementById('selected-position').style.display = 'block';
    }
  };
</script>

동적 설정 변경

뷰어를 리로드하여 설정을 동적으로 변경할 수 있습니다:

<div>
  <button onclick="changeBackground('#ffffff')">흰색 배경</button>
  <button onclick="changeBackground('#000000')">검은색 배경</button>
  <button onclick="changeBackground('#f8f9fa')">회색 배경</button>
</div>
<div id="viewer-container" style="width: 100%; height: 500px;"></div>

<script>
  const viewer = VrismSDK.VrismViewer.init('viewer-container', {
    token: 'your-token-here',
    contentId: 'your-content-id'
  });
  
  window.changeBackground = (color) => {
    // setConfig로 즉시 설정 변경
    viewer.setConfig({
      ui: { viewerBackgroundColor: color }
    });
  };
</script>

📋 사용 가능한 이벤트들

  • onLoadFinish - 로드 완료
  • onStepChange - 스텝 변경
  • onChange - 일반적인 변경
  • onLoadScene - 씬 로드 완료
  • onLoadUpdate - 로딩 진행률 업데이트
  • onFullscreenChange - 전체화면 변경

🛠️ 사용 가능한 메서드들

  • getViewerConfig() - 현재 설정 조회
  • setConfig(config) - 설정 일부를 즉시 업데이트
  • setStep(step) - 특정 스텝으로 이동
  • setGestureGuideShow(show) - 제스처 가이드 표시 제어
  • setFullscreenOpen(open) - 전체화면 제어
  • getClickedPosition() - 3D 위치 선택
  • reload(config) - 전체 리로드가 필요할 때 사용

🎯 다음 단계

Vanilla JavaScript 기본 사용법을 익혔다면: