如何在Three.js中加载图片?地球夜景纹理映射404错误求助
解决Three.js纹理图片404及映射失败问题
核心原因
404错误直接说明图片文件的路径配置不正确,浏览器无法找到对应的资源文件,自然无法将纹理映射到球体上。
分步排查与解决
1. 确认文件目录结构是否正确
先检查项目文件夹结构,确保图片确实放在了指定位置:
- 假设项目根目录下有
assets文件夹,里面存放nightmapearth.jpg - 项目结构示例:
项目根目录/ ├── assets/ │ └── nightmapearth.jpg ├── src/ │ ├── main.js (你的JS代码文件) │ └── style.css └── index.html
2. 调整图片引用路径
根据使用的打包工具,路径写法有区别:
- 用Vite:JS文件在
src/下时,路径应写成../assets/nightmapearth.jpg(从当前JS文件向上一级找到assets目录) - 用Webpack:可尝试
./assets/nightmapearth.jpg,需确保assets被配置为静态资源目录 - 通用方案:将图片放在项目的
public目录,直接写/nightmapearth.jpg(从网站根路径加载)
修改后的加载代码示例(Vite项目):
const nightMapEarth = textureLoader.load("../assets/nightmapearth.jpg");
3. 验证加载状态排查问题
添加加载回调,明确图片是否成功加载,排除其他潜在问题:
const textureLoader = new THREE.TextureLoader(); const nightMapEarth = textureLoader.load( "../assets/nightmapearth.jpg", (texture) => { console.log("纹理加载成功"); material.map = texture; material.needsUpdate = true; }, undefined, (error) => { console.error("纹理加载失败:", error); } );
4. 其他注意事项
- 文件名拼写完全匹配(大小写敏感,比如
NightMapEarth.jpg和nightmapearth.jpg是不同文件) - 检查图片是否损坏:直接用浏览器访问图片路径,确认能正常打开
修正后的完整代码示例
import './style.css' import * as THREE from 'three'; const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight); camera.position.z = 3; scene.add(camera); const textureLoader = new THREE.TextureLoader(); const nightMapEarth = textureLoader.load( "../assets/nightmapearth.jpg", () => console.log("纹理加载成功"), undefined, (err) => console.error("加载失败:", err) ); const sphereGeometry = new THREE.SphereGeometry(0.7); const material = new THREE.MeshBasicMaterial({ map: nightMapEarth, }); const earth = new THREE.Mesh(sphereGeometry, material); scene.add(earth); const renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); document.body.append(renderer.domElement); function animate() { window.requestAnimationFrame(animate); earth.rotation.y += 0.005; // 添加旋转效果,更直观验证纹理 renderer.render(scene, camera); } animate();
内容的提问来源于stack exchange,提问作者Renger Bierenga
相关产品推荐
相关产品推荐

