js实现波浪
使用 Canvas 实现波浪效果
通过 HTML5 的 Canvas API 可以绘制动态波浪效果。以下是基础实现代码:
const canvas = document.getElementById('waveCanvas');
const ctx = canvas.getContext('2d');
let time = 0;
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = 200;
}
function drawWave() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'rgba(100, 150, 255, 0.5)';
ctx.beginPath();
const waveHeight = 20;
const waveLength = 0.01;
const xOffset = 0;
for (let x = 0; x < canvas.width; x++) {
const y = waveHeight * Math.sin(x * waveLength + time) + canvas.height/2;
ctx.lineTo(x, y);
}
ctx.lineTo(canvas.width, canvas.height);
ctx.lineTo(0, canvas.height);
ctx.closePath();
ctx.fill();
time += 0.05;
requestAnimationFrame(drawWave);
}
resizeCanvas();
window.addEventListener('resize', resizeCanvas);
drawWave();
使用 CSS 动画实现波浪
通过 SVG 和 CSS 动画可以创建性能更优的波浪效果:
<div class="wave-container">
<svg viewBox="0 0 1200 120" preserveAspectRatio="none">
<path d="M0,0V46.29c47.79,22.2,103.59,32.17,158,28,70.36-5.37,136.33-33.31,206.8-37.5C438.64,32.43,512.34,53.67,583,72.05c69.27,18,138.3,24.88,209.4,13.08,36.15-6,69.85-17.84,104.45-29.34C989.49,25,1113-14.29,1200,52.47V0Z" class="shape-fill"></path>
</svg>
</div>
<style>
.wave-container {
position: relative;
height: 150px;
overflow: hidden;
}
.wave-container svg {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 100%;
}
.shape-fill {
fill: #4a90e2;
animation: wave 8s cubic-bezier(0.36, 0.45, 0.63, 0.53) infinite;
}
@keyframes wave {
0% {
transform: translateX(0);
}
100% {
transform: translateX(-50%);
}
}
</style>
使用 WebGL 实现高性能波浪
对于更复杂的3D波浪效果,可以使用Three.js库:
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(20, 20, 128, 128);
const material = new THREE.MeshBasicMaterial({
color: 0x00ffff,
wireframe: true
});
const plane = new THREE.Mesh(geometry, material);
scene.add(plane);
camera.position.z = 15;
function animate() {
requestAnimationFrame(animate);
const time = Date.now() * 0.001;
const positions = plane.geometry.attributes.position;
for (let i = 0; i < positions.count; i++) {
const x = positions.getX(i);
const y = positions.getY(i);
positions.setZ(i, Math.sin(x * 0.5 + time) * Math.cos(y * 0.5 + time) * 2);
}
positions.needsUpdate = true;
renderer.render(scene, camera);
}
animate();
使用现成的波浪库
可以考虑使用专门的水波动画库,如:
- Waves.js - 轻量级的波浪动画库
import Waves from 'waves.js';
const waves = new Waves({ el: '#wave-container', color: 'rgba(255, 255, 255, 0.5)', waveHeight: 20, speed: 0.15 });
waves.init();

2. tsParticles - 支持多种粒子效果包括波浪
```javascript
tsParticles.load("tsparticles", {
particles: {
shape: {
type: "wave"
},
move: {
enable: true,
speed: 2,
direction: "none",
out_mode: "out"
}
}
});






