js实现海浪
使用 Canvas 绘制海浪效果
通过 HTML5 的 Canvas API 可以实现动态的海浪效果。以下是一个简单的实现方法:
const canvas = document.getElementById('waveCanvas');
const ctx = canvas.getContext('2d');
let time = 0;
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) * 20 + canvas.height / 2;
if (x === 0) {
ctx.moveTo(x, y);
} else {
ctx.lineTo(x, y);
}
}
ctx.strokeStyle = '#1a73e8';
ctx.lineWidth = 2;
ctx.stroke();
time += 0.1;
requestAnimationFrame(drawWave);
}
drawWave();
添加渐变和填充效果
为了使海浪看起来更真实,可以添加渐变填充:

function drawFilledWave() {
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) * 20 + canvas.height / 2;
if (x === 0) {
ctx.moveTo(x, y);
} else {
ctx.lineTo(x, y);
}
}
ctx.lineTo(canvas.width, canvas.height);
ctx.lineTo(0, canvas.height);
ctx.closePath();
const gradient = ctx.createLinearGradient(0, 0, 0, canvas.height);
gradient.addColorStop(0, 'rgba(26, 115, 232, 0.7)');
gradient.addColorStop(1, 'rgba(26, 115, 232, 0.2)');
ctx.fillStyle = gradient;
ctx.fill();
time += 0.1;
requestAnimationFrame(drawFilledWave);
}
实现多层波浪效果
创建多个波浪层可以增加视觉效果:

function drawMultiLayerWave() {
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) * 15 + canvas.height / 2;
if (x === 0) {
ctx.moveTo(x, y);
} else {
ctx.lineTo(x, y);
}
}
ctx.strokeStyle = 'rgba(26, 115, 232, 0.8)';
ctx.lineWidth = 2;
ctx.stroke();
// 第二层波浪
ctx.beginPath();
for (let x = 0; x < canvas.width; x++) {
const y = Math.sin(x * 0.03 + time * 1.2) * 10 + canvas.height / 2 + 20;
if (x === 0) {
ctx.moveTo(x, y);
} else {
ctx.lineTo(x, y);
}
}
ctx.strokeStyle = 'rgba(66, 133, 244, 0.6)';
ctx.lineWidth = 1.5;
ctx.stroke();
time += 0.1;
requestAnimationFrame(drawMultiLayerWave);
}
使用贝塞尔曲线创建更自然的波浪
贝塞尔曲线可以产生更平滑的波浪运动:
function drawBezierWave() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
const waveHeight = 30;
const wavelength = 100;
const segments = Math.ceil(canvas.width / wavelength);
ctx.beginPath();
ctx.moveTo(0, canvas.height / 2);
for (let i = 0; i < segments; i++) {
const x = i * wavelength;
const cp1x = x + wavelength * 0.25;
const cp1y = canvas.height / 2 + Math.sin(time + i) * waveHeight;
const cp2x = x + wavelength * 0.75;
const cp2y = canvas.height / 2 + Math.sin(time + i + 0.5) * waveHeight;
const endX = x + wavelength;
const endY = canvas.height / 2;
ctx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, endX, endY);
}
ctx.strokeStyle = '#4285f4';
ctx.lineWidth = 2;
ctx.stroke();
time += 0.05;
requestAnimationFrame(drawBezierWave);
}
响应式调整
确保波浪效果适应不同屏幕尺寸:
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = 200;
}
window.addEventListener('resize', resizeCanvas);
resizeCanvas();
这些方法提供了从基础到进阶的海浪效果实现,可以根据需要调整参数如波浪高度、速度、颜色等来创建不同的视觉效果。






