Three.js Journey — Learn WebGL with Three.jsThe ultimate Three.js course whether you are a beginner or a more advanced developerhttps://threejs-journey.com/?c=p3
使用原生 JavaScript
首先是静态页面的放置位置,如果使用Vite模版配置,可以直接放在 /static/ 文件夹中,引用参考:
const imageSource = '/files/image.png'console.log(imageSource)
简单带过一下使用原生JavaScript的步骤:
- 创建 Image 实例
- 监听 image 的 load 事件
- 将texture变量提升为全局变量,并使用 Texture 类创建纹理
- 设置 image.src 属性加载图片,再将texture变量提升为全局变量
- 将texture应用到material中
const image = new Image()
const texture = new THREE.Texture(image)
texture.colorSpace = THREE.SRGBColorSpace // 修正 `sRGB` 颜色空间造成的纹理色值偏差
image.addEventListener('load', () =>
{texture.needsUpdate = true // 更新在函数外部创建的纹理
})
image.src = '/textures/door/color.jpg'// ...const material = new THREE.MeshBasicMaterial({ map: texture })
用于材质的 map 或 matcap 属性的纹理应该以 sRGB 编码,需要将 colorSpace 设置为 THREE.sRGBColorSpace,但仅限于这些纹理。
总结关键点:
1. texture.colorSpace = THREE.SRGBColorSpace
2. texture.needsUpdate = true
【效果图】
使用 TextureLoader
将上面原生JavaScript的引入改为 THREE.TextureLoader() 引入:
const textureLoader = new THREE.TextureLoader()
const texture = textureLoader.load('/textures/door/color.jpg')
texture.colorSpace = THREE.SRGBColorSpace
可以使用一个 TextureLoader 实例加载任意多的纹理(一对多)。如果现在有多个图片需要加载,并且希望共享事件(比如在所有图片加载完成后接收通知),可以使用THREE.LoadingManager() 与THREE.TextureLoader() 配合:
const loadingManager = new THREE.LoadingManager()
const textureLoader = new THREE.TextureLoader(loadingManager)
如果想要显示加载器并在所有资源加载完成后隐藏它,LoadingManager 对这点非常有用,可以通过将以下属性替换为自己的函数来监听各种事件。
// LoadingManager的使用
const loadingManager = new THREE.loadingManager()
// 可以通过将以下属性替换为自己的函数来监听各种事件
loadingManager.onStart = ()=> {console.log('loading started!');
}
loadingManager.onLoad = ()=> {console.log('loading finished!');
}
loadingManager.onProgress = ()=> {console.log('loading progressing!');
}
loadingManager.onError = ()=> {console.log('loading error!');
}
const TextureLoader = new THREE.TextureLoader(loadingManager)
【扩展】ExrLoader
这次下载的素材中有以 .exr 后缀结尾的文件,经查需要通过 ExrLoader 进行导入,直接用