js实现水波
实现水波效果的JavaScript方法
使用Canvas绘制水波效果是一种常见的实现方式。以下是一个基本的水波动画实现示例:
const canvas = document.getElementById('waveCanvas');
const ctx = canvas.getContext('2d');
let time = 0;
const waveHeight = 20;
const waveLength = 0.01;
const speed = 0.05;
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/2);
for(let x = 0; x < canvas.width; x++) {
const y = waveHeight * Math.sin(x * waveLength + time) + canvas.height/2;
ctx.lineTo(x, y);
}
ctx.strokeStyle = 'hsl(' + Math.abs(200 * Math.sin(time)) + ', 100%, 50%)';
ctx.stroke();
time += speed;
requestAnimationFrame(animate);
}
animate();
优化水波效果
为了创建更真实的水波效果,可以结合多个波形:
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/2);
for(let x = 0; x < canvas.width; x++) {
const y1 = 10 * Math.sin(x * 0.02 + time);
const y2 = 15 * Math.sin(x * 0.015 + time * 1.2);
const y = y1 + y2 + canvas.height/2;
ctx.lineTo(x, y);
}
ctx.strokeStyle = 'rgba(100, 200, 255, 0.8)';
ctx.stroke();
time += 0.05;
requestAnimationFrame(animate);
}
交互式水波效果
添加鼠标交互可以让水波效果更加生动:
let mouseX = 0;
let mouseY = 0;
canvas.addEventListener('mousemove', (e) => {
mouseX = e.clientX;
mouseY = e.clientY;
});
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/2);
for(let x = 0; x < canvas.width; x++) {
const distanceToMouse = Math.abs(x - mouseX);
const waveEffect = 50 * Math.exp(-distanceToMouse * 0.01);
const y = waveHeight * Math.sin(x * waveLength + time)
+ waveEffect * Math.sin(time * 2)
+ canvas.height/2;
ctx.lineTo(x, y);
}
ctx.strokeStyle = 'rgba(100, 200, 255, 0.8)';
ctx.stroke();
time += speed;
requestAnimationFrame(animate);
}
使用WebGL实现高性能水波
对于更复杂的水波效果,可以考虑使用WebGL:
// 简单的WebGL水波着色器示例
const vertexShader = `
attribute vec2 position;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
}
`;
const fragmentShader = `
precision highp float;
uniform float time;
void main() {
vec2 uv = gl_FragCoord.xy / 500.0;
float wave = sin(uv.x * 10.0 + time) * 0.1;
gl_FragColor = vec4(0.0, wave + 0.5, 1.0, 1.0);
}
`;
// WebGL初始化代码...
CSS实现简单水波效果
如果不需要复杂交互,纯CSS也能实现简单水波动画:
<div class="wave"></div>
<style>
.wave {
width: 200px;
height: 200px;
background: radial-gradient(
circle at 75% 50%,
rgba(100, 200, 255, 0.8),
transparent 70%
);
border-radius: 50%;
animation: wave 2s infinite ease-in-out;
}
@keyframes wave {
0% { transform: scale(1); opacity: 0.8; }
50% { transform: scale(1.2); opacity: 0.5; }
100% { transform: scale(1); opacity: 0.8; }
}
</style>
以上方法提供了从简单到复杂的水波效果实现方案,可以根据项目需求选择合适的实现方式。Canvas方案适合需要精细控制和交互的场景,而CSS方案则更适合简单的装饰性效果。







