vue使用three.js实现星云效果
时间: 2023-08-28 19:05:10 浏览: 215
实现星云效果需要用到 Three.js 中的点云(PointCloud)和着色器(Shader)。
首先,在 Vue 项目中安装 Three.js:
```
npm install three --save
```
然后,创建一个 Vue 组件,并在 mounted 钩子函数中创建 Three.js 场景和相机:
```javascript
<template>
<div ref="container"></div>
</template>
<script>
import * as THREE from 'three';
export default {
name: 'Nebula',
mounted() {
// 创建场景
const scene = new THREE.Scene();
// 创建相机
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;
// 创建渲染器
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setClearColor('#000000');
renderer.setSize(window.innerWidth, window.innerHeight);
// 将渲染器添加到页面中
this.$refs.container.appendChild(renderer.domElement);
// 渲染场景
const render = () => {
renderer.render(scene, camera);
requestAnimationFrame(render);
};
render();
},
};
</script>
<style>
canvas {
width: 100%;
height: 100%;
}
</style>
```
接下来,创建一个点云和着色器:
```javascript
mounted() {
// ...
// 创建点云
const geometry = new THREE.BufferGeometry();
const positions = [];
for (let i = 0; i < 10000; i++) {
const x = Math.random() * 2000 - 1000;
const y = Math.random() * 2000 - 1000;
const z = Math.random() * 2000 - 1000;
positions.push(x, y, z);
}
geometry.addAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
const material = new THREE.PointsMaterial({ size: 5 });
const points = new THREE.Points(geometry, material);
scene.add(points);
// 创建着色器
const vertexShader = `
uniform float time;
attribute vec3 displacement;
void main() {
vec3 newPosition = position + displacement * sin(time);
gl_Position = projectionMatrix * modelViewMatrix * vec4(newPosition, 1.0);
}
`;
const fragmentShader = `
uniform vec3 color;
void main() {
gl_FragColor = vec4(color, 1.0);
}
`;
const shaderMaterial = new THREE.ShaderMaterial({
uniforms: {
time: { value: 0 },
color: { value: new THREE.Color('#ffffff') },
},
vertexShader,
fragmentShader,
});
// 将着色器应用到点云上
const shaderGeometry = new THREE.BufferGeometry();
const shaderPositions = [];
for (let i = 0; i < 10000; i++) {
const x = Math.random() * 2000 - 1000;
const y = Math.random() * 2000 - 1000;
const z = Math.random() * 2000 - 1000;
shaderPositions.push(x, y, z);
}
shaderGeometry.addAttribute('position', new THREE.Float32BufferAttribute(shaderPositions, 3));
shaderGeometry.addAttribute('displacement', new THREE.Float32BufferAttribute(positions, 3));
const shaderPoints = new THREE.Points(shaderGeometry, shaderMaterial);
scene.add(shaderPoints);
// 更新着色器
const update = () => {
shaderMaterial.uniforms.time.value += 0.05;
};
render();
setInterval(update, 50);
},
```
最后,可以在着色器中添加一些特效,比如星云的颜色、大小、运动轨迹等等。
阅读全文