用three.js代码实现烟花绽放
时间: 2024-06-21 20:01:42 浏览: 189
在Three.js中,你可以使用粒子系统(Particle System)来模拟烟花绽放的效果。以下是创建简单烟花动画的基本步骤:
1. 导入Three.js库和相关模块:
```javascript
import * as THREE from 'three';
import { ParticleSystem, Emitter } from 'three/examples/jsm/particles/ParticleSystem';
```
2. 创建场景、相机和渲染器:
```javascript
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
```
3. 创建粒子系统和粒子发射器:
```javascript
const particleCount = 1000;
const particleSystem = new THREE.ParticleSystem();
const emitter = new Emitter(new THREE.Vector3(0, 0, -5), {
count: particleCount,
duration: 2,
rate: 100,
onEmit: (particle, index) => {
particle.position.x = Math.random() * 20 - 10;
particle.position.y = Math.random() * 20 - 10;
particle.position.z = -10;
particle.velocity.x = Math.random() * 2 - 1;
particle.velocity.y = Math.random() * 2 - 1;
particle.velocity.z = Math.random() * 2 + 1;
particle.color = new THREE.Color(Math.random(), Math.random(), Math.random());
}
});
particleSystem.emitter = emitter;
```
4. 设置粒子系统的生命周期和更新:
```javascript
function animate() {
requestAnimationFrame(animate);
scene.rotation.x += 0.01;
scene.rotation.y += 0.01;
particleSystem.update();
renderer.render(scene, camera);
}
animate();
```
5. 安装粒子系统到场景中:
```javascript
scene.add(particleSystem);
```
阅读全文