返回专栏
Creative Code
2026年4月14日2 分钟阅读
Three.js 粒子系统实战
学习如何使用 Three.js 和 React Three Fiber 创建交互式 3D 粒子效果,为你的网站增添视觉冲击力。
Three.jsWebGL3D
Creative CodeThree.js / WebGL
Three.js 粒子系统实战
学习如何使用 Three.js 和 React Three Fiber 创建交互式 3D 粒子效果,为你的网站增添视觉冲击力。
Three.jsWebGL3D
为什么选择 Three.js
Three.js 是目前最流行的 WebGL 库,它让创建 3D 网页体验变得简单。结合 React Three Fiber (R3F),可以在 React 应用中声明式地构建 3D 场景。
粒子系统基础
创建粒子系统的核心是 Points 和 BufferGeometry:
function Particles({ count = 2000 }) {
const positions = useMemo(() => {
const pos = new Float32Array(count * 3);
for (let i = 0; i < count; i++) {
pos[i * 3] = (Math.random() - 0.5) * 10;
pos[i * 3 + 1] = (Math.random() - 0.5) * 10;
pos[i * 3 + 2] = (Math.random() - 0.5) * 10;
}
return pos;
}, [count]);
return (
<points>
<bufferGeometry>
<bufferAttribute
attach="attributes-position"
count={count}
array={positions}
itemSize={3}
/>
</bufferGeometry>
<pointsMaterial size={0.02} color="#5EEAD4" />
</points>
);
}
自定义着色器
使用自定义着色器可以实现更复杂的视觉效果:
// Vertex Shader
uniform float uTime;
uniform float uSize;
void main() {
vec3 pos = position;
pos.y += sin(uTime + position.x * 2.0) * 0.3;
pos.x += cos(uTime + position.z * 2.0) * 0.2;
vec4 mvPosition = modelViewMatrix * vec4(pos, 1.0);
gl_PointSize = uSize * (300.0 / -mvPosition.z);
gl_Position = projectionMatrix * mvPosition;
}
性能考量
- 限制粒子数量(移动端 < 1000,桌面 < 5000)
- 使用
useFrame的 delta 参数进行时间相关动画 - 离屏时暂停渲染(IntersectionObserver)
- 使用
devicePixelRatio但限制最大值为 2
总结
Three.js 粒子系统可以为网站 Hero 区域创建引人注目的 3D 视觉效果。结合鼠标交互和滚动驱动动画,可以打造出令人难忘的第一印象。