Three.js 按照 es6 标准进行模块化,官方推荐 npm,node.js 加载,对于玩熟了 python ,搞前后分离的人,确实茫然,按three.js 文档加载总是报错。
上代码,js脚本在 js 文件中,script标签要 type= module,因为脚本中用了 import
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>My first three.js app</title> <style> body { margin: 0; } </style> </head> <body> <!-- <script async src="https://unpkg.com/es-module-shims@1.3.6/dist/es-module-shims.js"></script>--> <!-- //这个还必须得有,先命名为three,要不后边es6标准的其他模块加载有困难。--> <script type="importmap"> { "imports": { "three": "./three/build/three.module.js" } } </script> <script type="module" src="./loadModel.js"> </script> </body> </html>
loadModel.js 如下, 因为GLTFLoader,import 了 ‘’three‘’, 所以 hltml 中要 先 importMap
import * as THREE from 'three'; // 导入three 包, 先由 importmap,将一个有 export 的 three.js 模块 命名为 three const scene = new THREE.Scene(); import { GLTFLoader } from './three/build/GLTFLoader.js'; const loader = new GLTFLoader(); const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 ); const renderer = new THREE.WebGLRenderer(); renderer.setSize( window.innerWidth, window.innerHeight ); document.body.appendChild( renderer.domElement ); loader.load( './windturbine.gltf', function ( gltf ) { scene.add( gltf.scene ); }, undefined, function ( error ) { console.error( error ); } ); //const geometry = new THREE.BoxGeometry( 1, 1, 1 ); //const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } ); //const cube = new THREE.Mesh( geometry, material ); //scene.add( cube ); camera.position.z = 5; function animate() { requestAnimationFrame( animate ); // cube.rotation.x += 0.01; // cube.rotation.y += 0.01; renderer.render( scene, camera ); }; animate();