首先要有六张图片对应天空盒的六个面
// 创建天空盒
addPanorama() {
//相应面对应相应图片
const imgUrl = [
'Image/Skybox03_textures/sanlan2.jpg',
'Image/Skybox03_textures/sanlan4.jpg',
'Image/Skybox03_textures/sanlan5.jpg',
'Image/Skybox03_textures/sanlan6.jpg',
'Image/Skybox03_textures/sanlan1.jpg',
'Image/Skybox03_textures/sanlan3.jpg']
// 调用getTexturesFromAtlasFile() 给每个材质加上相应的图片
const textures = this.getTexturesFromAtlasFile(imgUrl, 6)
const materials = []
for (let i = 0; i < 6; i++) {
// 创造六个面的材质
materials.push(new THREE.MeshBasicMaterial({ map: textures[ i ] }))
}
//创造包围盒
const skyBox = new THREE.Mesh(new THREE.BoxBufferGeometry(1024, 1024, 1024), materials)
// skyBox.position.set(0, 0, 0);
skyBox.geometry.scale(1, 1, -1)
scene.add(skyBox)
},
// 六个面添加图片
getTexturesFromAtlasFile(atlasImgUrl, tilesNum) {
const textures = []
for (let i = 0; i < tilesNum; i++) {
textures[ i ] = new THREE.Texture()
}
for (let i = 0; i < textures.length; i++) {
const imageObj = new Image()
imageObj.src = atlasImgUrl[i]
imageObj.onload = () => {
let context = ''
// let tileWidth = imageObj.height;
// let tileWidth = 5000;
const canvas = document.createElement('canvas')
// const canvas: HTMLCanvasElement = this.canvasRef.nativeElement; // 得到canvas 元素
context = canvas.getContext('2d')
const canvasHeight = 720
canvas.height = canvasHeight
canvas.width = canvasHeight
// context.drawImage( imageObj, canvasHeight * i, 0, canvasHeight, canvasHeight, 0, 0, canvasHeight, canvasHeight );
context.drawImage(imageObj, 0, 0, canvasHeight, canvasHeight)
textures[ i ].image = canvas
textures[ i ].needsUpdate = true
}
}
return textures
},
调用addPanorama() 方法给场景添加天空盒