js实现水波
水波动画实现方法
使用JavaScript实现水波动画可以通过Canvas绘制结合数学函数模拟波纹效果。以下是两种常见实现方式:

基于Canvas的波纹效果
const canvas = document.getElementById('waveCanvas');
const ctx = canvas.getContext('2d');
let time = 0;
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = 200;
}
resizeCanvas();
function drawWave() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
for (let x = 0; x < canvas.width; x++) {
const y = Math.sin(x * 0.02 + time) * 10 + canvas.height / 2;
ctx.lineTo(x, y);
}
ctx.lineTo(canvas.width, canvas.height);
ctx.lineTo(0, canvas.height);
ctx.closePath();
ctx.fillStyle = 'rgba(64, 158, 255, 0.5)';
ctx.fill();
time += 0.05;
requestAnimationFrame(drawWave);
}
drawWave();
使用三角函数模拟复杂波纹
function complexWave() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
for (let x = 0; x < canvas.width; x++) {
const y1 = Math.sin(x * 0.01 + time) * 10;
const y2 = Math.cos(x * 0.015 + time * 1.3) * 8;
const y = (y1 + y2) + canvas.height / 2;
ctx.lineTo(x, y);
}
ctx.lineTo(canvas.width, canvas.height);
ctx.lineTo(0, canvas.height);
ctx.closePath();
ctx.fillStyle = 'rgba(100, 180, 255, 0.6)';
ctx.fill();
time += 0.04;
requestAnimationFrame(complexWave);
}
添加交互效果的波纹
let points = [];
canvas.addEventListener('click', (e) => {
points.push({
x: e.clientX,
y: e.clientY,
size: 5,
alpha: 1
});
});
function interactiveWave() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制基础波形
ctx.beginPath();
for (let x = 0; x < canvas.width; x++) {
let y = canvas.height / 2;
points.forEach(point => {
const distance = Math.sqrt(Math.pow(x - point.x, 2) + Math.pow(y - point.y, 2));
y += Math.sin(distance * 0.1 - time * 3) * point.size * point.alpha;
});
ctx.lineTo(x, y);
}
ctx.lineTo(canvas.width, canvas.height);
ctx.lineTo(0, canvas.height);
ctx.closePath();
ctx.fillStyle = 'rgba(70, 130, 180, 0.5)';
ctx.fill();
// 更新点击波纹
points = points.filter(p => {
p.alpha -= 0.01;
p.size += 0.2;
return p.alpha > 0;
});
time += 0.05;
requestAnimationFrame(interactiveWave);
}
性能优化建议
使用requestAnimationFrame替代setInterval确保动画流畅
对于复杂场景可考虑使用WebGL实现
限制波纹数量避免过多计算影响性能
使用transform代替重绘整个画布

实现要点
通过组合不同频率和相位的正弦波可创建更自然的水波效果 添加衰减系数使波纹逐渐消失更符合物理规律 使用缓动函数改善动画视觉效果 通过颜色渐变增强立体感
以上代码需要配合HTML中的canvas元素使用:
<canvas id="waveCanvas"></canvas>






