结果图
threejs比例不变自适应
首先是设置相机和render,要注意的就是相机要加上aspect不然如果页面不是正方形看到的样式就会失调。
// ---------相机设置-------------
// 实例化一个透视投影相机对象
const camera = new THREE.PerspectiveCamera();
//相机在Three.js三维坐标系中的位置
// 根据需要设置相机位置具体值
const cameraPostion = [20, 20, 20];
camera.position.set(...cameraPostion);
camera.lookAt(mesh.position);//指向mesh对应的位置
// 更新相机的宽高比
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
// ----------渲染器设置------------
// 创建渲染器对象
const renderer = new THREE.WebGLRenderer();
// 定义threejs输出画布的尺寸(单位:像素px)
const width = window.innerWidth; //宽度
const height = window.innerHeight; //高度
renderer.setSize(width, height); //设置three.js渲染区域的尺寸(像素px)
// renderer.setPixelRatio(window.devicePixelRatio)
renderer.render(scene, camera); //执行渲染操作
在onmounted中加入resize事件的监听,这样即使缩放也不会又问题
window.addEventListener('resize', () => {
const width = window.innerWidth; //宽度
const height = window.innerHeight; //高度
// camera.position.set(20, 20, 20);
camera.lookAt(mesh.position);//指向mesh对应的位置
// 更新相机的宽高比
camera.aspect = width / height;
// 更新摄像机的投影矩阵
camera.updateProjectionMatrix();
renderer.setSize(width, height); //设置three.js渲染区域的尺寸(像素px)
renderer.render(scene, camera); //执行渲染操作
});
鼠标控制视角
禁止拖拽和缩放是为了以防超出天空盒或者进入地球模型中,也可以设置这两个的范围
const controls = new MapControls(camera, renderer.domElement);
controls.enablePan = false; //禁止右键拖拽
controls.enableZoom = false;//禁止缩放
controls.addEventListener('change', function () {
// 鼠标右键旋转时候,查看.position变化
// 鼠标左键拖动的时候,查看.position、.target的位置会变化
console.log('camera.position', camera.position);
renderer.render(scene, camera); //执行渲染操作
// console.log('controls.target', controls.target);
});
天空盒
这边我采用了球体来制作天空盒,因为cube要6张图很难找,刚好我看到了一个长图,就直接用了
//----------天空盒-----------
// 加载天空球纹理
// 创建TextureLoader加载天空盒纹理
let texture = new THREE.TextureLoader().load([
require('../assets/longbk.jpeg')
]);
// 创建立方体几何体并应用天空盒材质
createGeometry(scene, 'Sphere', [