Three.js 是一个基于 WebGL 的 JavaScript 3D 库,用于在网页上创建和显示动画3D图形。粒子系统是 Three.js 中的一个常见应用,用于模拟大量小颗粒的行为,如烟雾、火焰、雨雪等。
// 引入Three.js库
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);
for (let i = 0; i < particleCount * 3; i++) {
positions[i] = (Math.random() - 0.5) * 10;
}
particles.setAttribute('position', new THREE.BufferAttribute(positions, 3));
const particleMaterial = new THREE.PointsMaterial({ color: 0xffffff, size: 0.1 });
const particleSystem = new THREE.Points(particles, particleMaterial);
scene.add(particleSystem);
camera.position.z = 5;
// 动画循环
function animate() {
requestAnimationFrame(animate);
// 更新粒子位置
const positions = particleSystem.geometry.attributes.position.array;
for (let i = 0; i < particleCount * 3; i += 3) {
positions[i] += (Math.random() - 0.5) * 0.01; // x方向移动
positions[i + 1] += (Math.random() - 0.5) * 0.01; // y方向移动
positions[i + 2] += (Math.random() - 0.5) * 0.01; // z方向移动
}
particleSystem.geometry.attributes.position.needsUpdate = true;
renderer.render(scene, camera);
}
animate();
问题:粒子移动看起来不自然或有卡顿现象。
原因:
解决方法:
通过上述方法,可以有效提升粒子系统的性能和视觉效果。
领取专属 10元无门槛券
手把手带您无忧上云