js实现3D烟花特效
实现3D烟花特效的方法
使用Three.js库可以高效实现3D烟花效果。Three.js是基于WebGL的JavaScript 3D图形库,适合创建复杂的3D动画效果。
安装Three.js:
npm install three
基础场景搭建
创建场景、相机和渲染器:
import * as THREE from 'three';
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);
烟花粒子系统
创建粒子系统模拟烟花爆炸:
const particleCount = 1000;
const particles = new THREE.BufferGeometry();
const positions = new Float32Array(particleCount * 3);
const colors = new Float32Array(particleCount * 3);
for (let i = 0; i < particleCount; i++) {
positions[i*3] = (Math.random() - 0.5) * 2;
positions[i*3+1] = Math.random() * 5;
positions[i*3+2] = (Math.random() - 0.5) * 2;
colors[i*3] = Math.random();
colors[i*3+1] = Math.random();
colors[i*3+2] = Math.random();
}
particles.setAttribute('position', new THREE.BufferAttribute(positions, 3));
particles.setAttribute('color', new THREE.BufferAttribute(colors, 3));
const particleMaterial = new THREE.PointsMaterial({
size: 0.1,
vertexColors: true
});
const particleSystem = new THREE.Points(particles, particleMaterial);
scene.add(particleSystem);
动画与物理效果
实现粒子运动轨迹和重力效果:
function animate() {
requestAnimationFrame(animate);
const positions = particles.attributes.position.array;
for (let i = 0; i < particleCount; i++) {
positions[i*3+1] -= 0.01; // 重力效果
positions[i*3] += (Math.random() - 0.5) * 0.02; // 随机漂移
positions[i*3+2] += (Math.random() - 0.5) * 0.02;
}
particles.attributes.position.needsUpdate = true;
renderer.render(scene, camera);
}
animate();
交互触发烟花
添加点击事件触发新烟花:
window.addEventListener('click', () => {
const explosionPosition = new THREE.Vector3(
(Math.random() - 0.5) * 10,
0,
(Math.random() - 0.5) * 10
);
createExplosion(explosionPosition);
});
function createExplosion(position) {
const explosionParticles = new THREE.BufferGeometry();
// 类似上面的粒子创建代码,但初始位置设为爆炸点
// 添加爆炸后的扩散效果
}
性能优化建议
使用InstancedMesh提高大量粒子性能:
const instancedMesh = new THREE.InstancedMesh(geometry, material, count);
// 为每个实例设置不同位置和颜色
考虑使用GPU加速计算:
// 通过ShaderMaterial编写自定义着色器
const shaderMaterial = new THREE.ShaderMaterial({
uniforms: {...},
vertexShader: `...`,
fragmentShader: `...`
});
视觉效果增强
添加后期处理效果:
import { EffectComposer } from 'three/examples/jsm/postprocessing/EffectComposer';
import { RenderPass } from 'three/examples/jsm/postprocessing/RenderPass';
import { GlitchPass } from 'three/examples/jsm/postprocessing/GlitchPass';
const composer = new EffectComposer(renderer);
composer.addPass(new RenderPass(scene, camera));
composer.addPass(new GlitchPass());
实现拖尾效果:

// 使用自定义着色器或在每帧更新时保留粒子历史位置






