js实现流体
流体动画实现方法
使用JavaScript实现流体效果通常涉及Canvas或WebGL技术,以下是两种常见方法:

Canvas 2D方法 创建基于Canvas的流体模拟需要借助物理算法和粒子系统:

const canvas = document.getElementById('fluidCanvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const particles = [];
for (let i = 0; i < 100; i++) {
particles.push({
x: Math.random() * canvas.width,
y: Math.random() * canvas.height,
size: Math.random() * 5 + 2,
speedX: Math.random() * 3 - 1.5,
speedY: Math.random() * 3 - 1.5
});
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
particles.forEach(particle => {
particle.x += particle.speedX;
particle.y += particle.speedY;
if(particle.x < 0 || particle.x > canvas.width) {
particle.speedX *= -1;
}
if(particle.y < 0 || particle.y > canvas.height) {
particle.speedY *= -1;
}
ctx.beginPath();
ctx.arc(particle.x, particle.y, particle.size, 0, Math.PI * 2);
ctx.fillStyle = 'rgba(0, 150, 255, 0.5)';
ctx.fill();
});
requestAnimationFrame(animate);
}
animate();
WebGL方法 使用WebGL实现更高效的流体效果需要着色器编程:
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 geometry = new THREE.PlaneGeometry(10, 10, 128, 128);
const material = new THREE.ShaderMaterial({
uniforms: {
time: { value: 0 }
},
vertexShader: `
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: `
uniform float time;
varying vec2 vUv;
void main() {
vec2 p = vUv * 10.0;
float intensity = sin(p.x - time) * cos(p.y + time);
gl_FragColor = vec4(0.0, intensity * 0.5, 1.0, 1.0);
}
`
});
const plane = new THREE.Mesh(geometry, material);
scene.add(plane);
camera.position.z = 5;
function animate() {
requestAnimationFrame(animate);
material.uniforms.time.value += 0.05;
renderer.render(scene, camera);
}
animate();
性能优化技巧
降低粒子数量或使用Web Workers进行离屏计算可以提升性能。对于移动设备,建议减少画布分辨率或使用更简单的着色器。
第三方库推荐
- Three.js:适合3D流体效果
- p5.js:简化Canvas操作
- Matter.js:物理引擎支持
- GPU.js:加速GPU计算
这些方法可以根据项目需求进行组合或调整,实现从简单到复杂的各种流体视觉效果。






