我正在尝试将 3D 模块导入 three.js我正在阅读 here和 here .但这一切都是黑色的。我试过移动相机的z
定位到5
,但仍然是黑色的。我刚刚开始使用 Three.js。我在在线 Three.js 查看器中加载了模型,它加载得很好。这是我的代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Import 3D Model into Three JS</title>
<link rel="stylesheet" href="../common.css">
</head>
<body>
<div id="container">
</div>
</body>
<script src="../three.js-master/build/three.js"></script>
<script type="module">
// import { THREE } from '../three.js-master/build/three.js';
import { GLTFLoader } from '../three.js-master/examples/jsm/loaders/GLTFLoader.js';
const container = document.querySelector('div#container');
const path_to_model = './Mini-Game Variety Pack/Models/gltf/tree_forest.gltf.glb';
const loader = new GLTFLoader();
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
loader.load(path_to_model, function (gltf)
{
console.log('Adding glTF model to scene...');
scene.add(gltf.scene);
console.log('Model added.');
console.log('Moving camera 5z...');
camera.position.z = 5;
console.log('Camera moved.');
}, undefined, function (error)
{
console.error(error);
});
container.appendChild(renderer.domElement);
function animate()
{
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
</script>
</html>
我的文件夹是这样的:
(未显示所有文件,仅显示必要的文件)
我从 here 下载了所有模型,但使用
tree_forest
一。当我加载页面时,我看到的是:
我在 Mac 上,我在 VSCode 上使用五个服务器。
最佳答案
<script src="../three.js-master/build/three.js"></script>
<script type="module">
// import { THREE } from '../three.js-master/build/three.js';
import { GLTFLoader } from '../three.js-master/examples/jsm/loaders/GLTFLoader.js';
将全局脚本与 ES6 模块混合不是一个好主意,并且很快会导致未定义的行为。我建议您像这样组织导入,直到应用程序正常工作:import * as THREE from 'https://cdn.skypack.dev/three@0.129.0/build/three.module.js';
import { OrbitControls } from 'https://cdn.skypack.dev/three@0.129.0/examples/jsm/loaders/GLTFLoader.js';
您还应该在场景中添加一些灯光,否则您只会看到黑屏。试试看:const hemiLight = new THREE.HemisphereLight( 0xffffff, 0x444444 );
hemiLight.position.set( 0, 10, 0 );
scene.add( hemiLight );
const dirLight = new THREE.DirectionalLight( 0xffffff );
dirLight.position.set( 0, 0, 10 );
scene.add( dirLight );
关于javascript - 无法导入three.js glTF模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68082760/