Three.js导入GLTFLoader遇MIME类型(text/html)拦截错误求助
解决GLTFLoader导入错误及相关问题
核心错误原因
你遇到的MIME类型错误,本质是GLTFLoader内部尝试导入Three.js核心模块时,路径解析错误导致请求了不存在的文件(服务器返回404页面,MIME类型为text/html)。因为你本地导入Three.js的路径和GLTFLoader默认的npm包路径不匹配。
具体修复步骤
1. 用导入映射(Import Map)统一模块路径
在你的HTML文件里添加一段importmap,让GLTFLoader能正确找到Three.js核心模块:
<script type="importmap"> { "imports": { "three": "./node_modules/three/build/three.module.js", "three/addons/": "./node_modules/three/examples/jsm/" } } </script>
然后修改main.js里的导入语句,简化成:
import * as THREE from 'three'; import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
2. 修正模型加载路径
浏览器无法直接访问本地绝对路径(C:\Users\User\Desktop\...),把你的GLB模型放到项目目录里,比如新建一个models文件夹,然后修改加载路径:
loader.load('./models/realistic_human_heart.glb', (gltf) => { // ... 后续代码不变 });
3. 修复相机参数错误
你创建PerspectiveCamera时少了**宽高比(aspect)**参数,这会导致模型渲染变形,修正为:
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
4. 优化动画逻辑(可选)
原来的动画里通过scene.children.length > 1判断模型是否加载,不如直接用模型对象判断更可靠:
let heartModel = null; loader.load('./models/realistic_human_heart.glb', (gltf) => { heartModel = gltf.scene; scene.add(heartModel); heartModel.position.set(0, 0, 0); }); // 动画循环里改成 function animate() { requestAnimationFrame(animate); if (heartModel) { heartModel.rotation.y += 0.01; } renderer.render(scene, camera); }
内容的提问来源于stack exchange,提问作者Krrish Gupta
相关产品推荐
相关产品推荐

