vue实现3d宇宙
Vue实现3D宇宙效果
要实现3D宇宙效果,可以使用Vue结合Three.js库。Three.js是一个强大的JavaScript 3D库,适合创建复杂的3D场景。
安装依赖
需要安装vue和three.js:
npm install vue three
基本结构
创建一个Vue组件来承载3D宇宙场景。组件需要包含一个容器元素用于渲染3D内容。
<template>
<div ref="container" class="universe-container"></div>
</template>
<script>
import * as THREE from 'three';
export default {
name: 'UniverseScene',
mounted() {
this.initScene();
},
methods: {
initScene() {
const container = this.$refs.container;
// 场景初始化代码将在这里
}
}
}
</script>
<style>
.universe-container {
width: 100%;
height: 100vh;
}
</style>
创建3D场景
在initScene方法中设置基本的Three.js场景:
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
camera.position.z = 30;
添加星空背景
创建星空背景效果:
const starGeometry = new THREE.BufferGeometry();
const starMaterial = new THREE.PointsMaterial({
color: 0xffffff,
size: 0.1
});
const starVertices = [];
for (let i = 0; i < 10000; i++) {
const x = (Math.random() - 0.5) * 2000;
const y = (Math.random() - 0.5) * 2000;
const z = (Math.random() - 0.5) * 2000;
starVertices.push(x, y, z);
}
starGeometry.setAttribute('position', new THREE.Float32BufferAttribute(starVertices, 3));
const stars = new THREE.Points(starGeometry, starMaterial);
scene.add(stars);
添加行星系统
创建旋转的行星和轨道:
// 太阳
const sunGeometry = new THREE.SphereGeometry(5, 32, 32);
const sunMaterial = new THREE.MeshBasicMaterial({ color: 0xffff00 });
const sun = new THREE.Mesh(sunGeometry, sunMaterial);
scene.add(sun);
// 地球
const earthGeometry = new THREE.SphereGeometry(2, 32, 32);
const earthMaterial = new THREE.MeshBasicMaterial({ color: 0x3498db });
const earth = new THREE.Mesh(earthGeometry, earthMaterial);
earth.position.x = 15;
scene.add(earth);
// 动画循环
const animate = () => {
requestAnimationFrame(animate);
sun.rotation.y += 0.005;
earth.rotation.y += 0.01;
earth.position.x = Math.cos(Date.now() * 0.001) * 15;
earth.position.z = Math.sin(Date.now() * 0.001) * 15;
renderer.render(scene, camera);
};
animate();
响应式处理
添加窗口大小变化的响应处理:
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
性能优化
对于更复杂的宇宙场景,考虑以下优化:
- 使用THREE.LOD(Level of Detail)根据距离切换不同细节模型
- 实现视锥体剔除
- 使用实例化渲染处理大量相似对象
进阶效果
可以添加更多宇宙元素:

- 星云效果(使用粒子系统和着色器)
- 星系螺旋结构
- 行星纹理贴图
- 光照效果(太阳光)
这个实现提供了基本的3D宇宙场景,可以根据需求进一步扩展和定制。






