成品
通过在物体对象上贴图就可以完成上面的地球制作和全景看房效果。
方法
加载
var texture = new THREE.TextureLoader().load ( url : String, onLoad : Function, onProgress : Function, onError : Function )
使用纹理贴图的第一步就是导入,three.js专门提供了纹理加载函数THREE.TextureLoader()
代码示例(官方)
var texture = new THREE.TextureLoader().load( 'textures/land_ocean_ice_cloud_2048.jpg' );
// 立即使用纹理进行材质创建
var material = new THREE.MeshBasicMaterial( { map: texture } );
Code Example with Callbacks
// 初始化一个加载器
var loader = new THREE.TextureLoader();
// 加载一个资源
loader.load(
// 资源URL
'textures/land_ocean_ice_cloud_2048.jpg',
// onLoad回调
function ( texture ) {
// in this example we create the material when the texture is loaded
var material = new THREE.MeshBasicMaterial( {
map: texture
} );
},
// 目前暂不支持onProgress的回调
undefined,
// onError回调
function ( err ) {
console.error( 'An error happened.' );
}
);
贴图
纹理加载完就可以贴在材质上了,具体代码如下:new THREE.MeshBasicMaterial({map:loader.load('texture/./assets/earth_atmos_2048.jpg'),side:DoubleSide})
side属性用于控制贴图贴的地方:
side:BackSide->贴图贴在物体内部
side:FrontSide->贴图贴在物体外面
side:DoubleSide->贴图在物体内外都会贴上
注意:需要引入import { DoubleSide, BackSide, FrontSide } from 'three';
多贴图使用
也许你想使用多张贴图应用于物体的不同面上,那么可以这样用:
var material =[
//定义多个导入贴图的材质,放到一个数组里
new THREE.MeshBasicMaterial({map:loader.load(require('../assets/earth_atmos_2048.jpg')),side:DoubleSide})
new THREE.MeshBasicMaterial({map:loader.load(require('../assets/1592795651401.jpg')),side:DoubleSide}),
new THREE.MeshBasicMaterial({map:loader.load(require('../assets/1592795684735.jpg')),side:DoubleSide}),
new THREE.MeshBasicMaterial({map:loader.load(require('../assets/1592795684735.jpg')),side:DoubleSide}),
new THREE.MeshBasicMaterial({map:loader.load(require('../assets/1592795651401.jpg')),side:DoubleSide}),
new THREE.MeshBasicMaterial({map:loader.load(require('../assets/1592795651401.jpg')),side:DoubleSide})
]
//直接使用材质数组来构建物体,数组里的材质分别对应物体的右、左、上、下、前、后
var cube = new THREE.Mesh( geometry, material );