three.js使用正方体加图片实现全景看房效果
实现方法
创建一个正方体 加载6张纹理贴图 正方体z轴缩放-1 调整相机位置
图例
代码
< template> < div class = "app" > < div ref= "canvesRef" class = "canvas-wrap" > < / div> < / div>
< / template> < script setup>
import { ref, onMounted } from "vue" ;
import * as THREE from "three" ;
import { OrbitControls } from "three/addons/controls/OrbitControls.js" ; const canvesRef = ref ( null ) ;
const canvasWidth = window. innerWidth;
const canvasHeight = window. innerHeight;
let scene;
let camera;
let renderer;
let axesHelper;
let cameraControls; init ( ) ;
render ( ) ;
function init ( ) { scene = new THREE. Scene ( ) ; addModel ( ) ; camera = new THREE. PerspectiveCamera ( 75 , canvasWidth / canvasHeight, 0.1 , 3000 ) ; camera. position. set ( 0 , 0 , - 1 ) ; axesHelper = new THREE. AxesHelper ( 200 ) ; scene. add ( axesHelper) ; renderer = new THREE. WebGLRenderer ( ) ; renderer. setSize ( canvasWidth, canvasHeight) ; cameraControls = new OrbitControls ( camera, renderer. domElement) ; cameraControls. minDistance = 2 ; cameraControls. maxDistance = 10 ;
}
function addModel ( ) { const geometry = new THREE. BoxGeometry ( 100 , 100 , 100 ) ; const imgs = [ "4_l" , "4_r" , "4_u" , "4_d" , "4_b" , "4_f" ] ; const textureLoader = new THREE. TextureLoader ( ) ; const materialArr = imgs. map ( ( item ) => { const texture = textureLoader. load ( ` ../src/assets/img/room/ ${ item} .jpg ` ) ; if ( item === "4_u" || item === "4_d" ) { texture. rotation = Math. PI ; texture. center = new THREE. Vector2 ( 0.5 , 0.5 ) ; } return new THREE. MeshBasicMaterial ( { map : texture } ) ; } ) ; const cube = new THREE. Mesh ( geometry, materialArr) ; cube. geometry. scale ( 1 , 1 , - 1 ) ; scene. add ( cube) ;
}
function render ( ) { renderer. render ( scene, camera) ; requestAnimationFrame ( render) ;
}
onMounted ( ( ) => { canvesRef. value. appendChild ( renderer. domElement) ;
} ) ;
< / script> < style lang= "scss" scoped>
. app { position : relative;
}
< / style>