You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Three.js纹理加载失败:制作地球3D模型时贴图无法正常显示如何解决

问题原因&解决方法

  • 路径书写错误:你的纹理加载路径写为.img/global.jpeg,属于语法错误。如果是当前目录下img文件夹内的资源,正确路径应为./img/global.jpeg;如果是站点根目录下的img文件夹,路径应为/img/global.jpeg。
  • 缺少加载错误校验:当前代码没有添加纹理加载的错误回调,无法定位是路径404、跨域还是图片损坏导致的加载失败。
  • 本地预览跨域限制:如果你直接通过file://协议打开本地HTML文件,浏览器的安全策略会禁止加载本地图片资源,出现跨域报错。需要启动本地静态服务预览,比如使用VS Code的Live Server插件、执行python -m http.server或npx serve命令启动服务后访问。
  • 冗余重复代码:代码中重复执行了两次renderer.setSize和document.body.appendChild(renderer.domElement),属于无效冗余代码,可以删除重复部分。
  • 异步加载渲染时机问题:TextureLoader加载纹理是异步操作,第一帧渲染时纹理可能还未加载完成,不会显示。可以添加加载回调触发重渲染,或者开启材质的自动更新。

修正后参考代码

import * as THREE from 'https://cdn.skypack.dev/three@0.134.0'

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);
document.body.appendChild(renderer.domElement);

const textureLoader = new THREE.TextureLoader();
// 替换为正确的图片路径
textureLoader.load('./img/global.jpeg', (texture) => {
  const sphere = new THREE.Mesh(
    new THREE.SphereGeometry(5, 50, 50), 
    new THREE.MeshBasicMaterial({
      map: texture
    })
  );
  scene.add(sphere);
}, undefined, (err) => {
  // 加载出错时会打印错误信息,方便定位问题
  console.error('纹理加载失败:', err);
});

camera.position.z = 15;

function animate() {
  requestAnimationFrame(animate);
  renderer.render(scene, camera);
}
animate();

内容的提问来源于stack exchange,提问作者Del

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 17:24:05