three.js basic template

233 阅读1分钟

three.js basic template

build on three.js r158

codepan

codepan

codepan-juejin

html

<script async src="https://unpkg.com/es-module-shims@1.8.0/dist/es-module-shims.js"></script>
<script type="importmap">
  {
    "imports": {
      "three": "https://unpkg.com/three@0.158.0/build/three.module.js",
      "three/addons/": "https://unpkg.com/three@0.158.0/examples/jsm/"
    }
  }
</script>

css

body {
  margin: 0;
}

javascript

import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import { GUI } from "three/addons/libs/lil-gui.module.min.js";
import Status from "three/addons/libs/stats.module.js";

const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setAnimationLoop(animate);
document.body.appendChild(renderer.domElement);
const status = new Status();
document.body.appendChild(status.dom);

const aspect = window.innerWidth / window.innerHeight;
const camera = new THREE.PerspectiveCamera(50, aspect, 0.1, 2000);
camera.position.z = 5;

const controls = new OrbitControls(camera, renderer.domElement);

const scene = new THREE.Scene();
scene.add(new THREE.AxesHelper());
scene.add(new THREE.AmbientLight());
scene.add(new THREE.HemisphereLight(0xffffff, 0x000000));
const light = new THREE.DirectionalLight();
light.position.set(-5, 5, 5);
scene.add(light);

const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshLambertMaterial();
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);

const gui = new GUI();
gui.add(mesh.position, "x", -1, 1, 0.1);
gui.add(mesh.position, "y", -1, 1, 0.1);
gui.add(mesh.position, "z", -1, 1, 0.1);

function animate() {
  mesh.rotation.x += 0.01;
  mesh.rotation.y += 0.02;
  controls.update();
  status.update();
  renderer.render(scene, camera);
}

window.addEventListener("resize", () => {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(window.innerWidth, window.innerHeight);
});