JavaScript 水波动画是一种常见的网页动画效果,它模拟了水面上的波纹扩散的效果。这种动画通常用于增强用户界面的视觉吸引力和交互体验。
水波动画主要依赖于以下几个基础概念:
requestAnimationFrame
方法来实现流畅的动画效果。以下是一个简单的 JavaScript 水波动画实现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Water Wave Animation</title>
<style>
canvas {
display: block;
background: #0099ff;
}
</style>
</head>
<body>
<canvas id="waveCanvas"></canvas>
<script>
const canvas = document.getElementById('waveCanvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let waves = [];
const waveCount = 5;
const waveSpeed = 0.05;
const waveAmplitude = 50;
class Wave {
constructor(x, y) {
this.x = x;
this.y = y;
this.radius = 0;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.strokeStyle = 'rgba(255, 255, 255, 0.5)';
ctx.lineWidth = 2;
ctx.stroke();
}
update() {
this.radius += waveSpeed;
}
}
function createWaves() {
for (let i = 0; i < waveCount; i++) {
waves.push(new Wave(canvas.width / 2, canvas.height / 2));
}
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
waves.forEach(wave => {
wave.draw();
wave.update();
});
requestAnimationFrame(animate);
}
createWaves();
animate();
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
canvas.addEventListener('click', (event) => {
const rect = canvas.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
waves.push(new Wave(x, y));
});
</script>
</body>
</html>
通过上述方法,可以有效地创建和控制水波动画,提升网页的用户体验。
领取专属 10元无门槛券
手把手带您无忧上云