Three.js glTF Load Sample

Sample to load glTF model of Draco compression with Three.js

by warrentrent

HTML

<script async src="https://unpkg.com/es-module-shims@1.3.6/dist/es-module-shims.js"></script>
    
<script type="importmap">
	{
		"imports": {
			"three": "https://unpkg.com/three@0.157.0/build/three.module.js"
		}
	}
</script>

<canvas id="c"></canvas>

CSS

html, body {
  margin: 0;
  padding: 0;
  border: 0;
  overflow: hidden;
}

JavaScript

import * as THREE from 'three';
import {
  OrbitControls
} from "https://unpkg.com/three@0.157.0/examples/jsm/controls/OrbitControls.js";
import {
  DecalGeometry
} from "https://unpkg.com/three@0.157.0/examples/jsm/geometries/DecalGeometry.js";

import {
  GLTFLoader
} from "https://unpkg.com/three@0.157.0/examples/jsm/loaders/GLTFLoader.js";

window.addEventListener('load', init);

function init() {

  const width = window.innerWidth;
  const height = window.innerHeight;

  const canvasElement = document.querySelector('#c');
  const renderer = new THREE.WebGLRenderer({
    canvas: canvasElement,
  });

  renderer.setSize(width, height);

  const scene = new THREE.Scene();

  const camera = new THREE.PerspectiveCamera(5, width / height, 0.1, 10000);
  camera.position.set(0, 1, 2);

  const controls = new OrbitControls(camera, canvasElement);
  controls.update();

  const directionalLight = new THREE.DirectionalLight(0xffffff);
  directionalLight.position.set(1, 1, 1);
  scene.add(directionalLight);

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

  const loader = new GLTFLoader();
  loader.setCrossOrigin('anonymous');

  loader.load('https://vu-development.s3.amazonaws.com/sample/teapot.gltf', (gltf) => {
    const model = gltf.scene;
    scene.add(model);


    //****************************************************************
    // Apply a decal at the location of the plane or Dummy object using it's 
    // position and rotation
    //*****************************************************************
    let decal = "https://vu-development.s3.amazonaws.com/sample/uv_checker.png";
    const texture = new THREE.TextureLoader().load(decal);

    texture.flipY = false;
    texture.colorSpace = THREE.SRGBColorSpace;

    let decalMaterial = new THREE.MeshBasicMaterial({
      map: texture,
      transparent: true,
      depthTest: true,
      depthWrite: false,
      polygonOffset: true,
      polygonOffsetFactor: -4
    });

 ...