js实现水柱
实现水柱效果的JavaScript方法
使用Canvas绘制动态水柱效果是一种常见的实现方式。以下是基于Canvas和JavaScript的详细实现步骤:
创建Canvas基础结构
<canvas id="waterCanvas" width="400" height="200"></canvas>
const canvas = document.getElementById('waterCanvas');
const ctx = canvas.getContext('2d');
定义水柱参数
const wave = {
y: canvas.height / 2,
length: 0.01,
amplitude: 20,
frequency: 0.01
};
let time = 0;
绘制水柱动画
function animate() {
ctx.fillStyle = 'rgba(0, 0, 0, 0.05)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.moveTo(0, canvas.height);
for (let i = 0; i < canvas.width; i++) {
const y = wave.y +
Math.sin(i * wave.length + time) * wave.amplitude *
Math.sin(time * wave.frequency);
ctx.lineTo(i, y);
}
ctx.lineTo(canvas.width, canvas.height);
ctx.fillStyle = '#00a1ff';
ctx.fill();
time += 0.05;
requestAnimationFrame(animate);
}
animate();
增强水柱效果
添加水花飞溅效果可提升真实感:

const drops = [];
function createDrop(x, y) {
drops.push({
x,
y,
size: Math.random() * 3 + 1,
speedY: Math.random() * -3 - 2,
speedX: Math.random() * 2 - 1,
opacity: Math.random() * 0.5 + 0.5
});
}
function updateDrops() {
for (let i = 0; i < drops.length; i++) {
const drop = drops[i];
drop.y += drop.speedY;
drop.x += drop.speedX;
drop.opacity -= 0.01;
if (drop.opacity <= 0) {
drops.splice(i, 1);
i--;
}
}
if (Math.random() < 0.1) {
createDrop(
Math.random() * canvas.width,
wave.y + wave.amplitude
);
}
}
function drawDrops() {
drops.forEach(drop => {
ctx.beginPath();
ctx.arc(drop.x, drop.y, drop.size, 0, Math.PI * 2);
ctx.fillStyle = `rgba(100, 200, 255, ${drop.opacity})`;
ctx.fill();
});
}
整合动画循环
修改后的动画函数:

function animate() {
ctx.fillStyle = 'rgba(0, 0, 0, 0.05)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 绘制水柱
ctx.beginPath();
ctx.moveTo(0, canvas.height);
for (let i = 0; i < canvas.width; i++) {
const y = wave.y +
Math.sin(i * wave.length + time) * wave.amplitude *
Math.sin(time * wave.frequency);
ctx.lineTo(i, y);
}
ctx.lineTo(canvas.width, canvas.height);
ctx.fillStyle = '#00a1ff';
ctx.fill();
// 处理水滴
updateDrops();
drawDrops();
time += 0.05;
requestAnimationFrame(animate);
}
交互式控制
添加鼠标交互控制水柱高度:
canvas.addEventListener('mousemove', (e) => {
wave.y = e.clientY - canvas.offsetTop;
});
性能优化建议
对于复杂场景,可采用以下优化措施:
- 使用离屏Canvas进行预渲染
- 限制重绘区域
- 减少不必要的图形操作
- 适当降低帧率
这种实现方式可以创建流畅的水柱动画效果,通过调整参数可获得不同风格的水柱表现。






