water waves
by velo_ninja
HTML
<div id="water-container">
<canvas id="wave-canvas"></canvas>
</div>
<script>
const canvas = document.getElementById('wave-canvas');
const ctx = canvas.getContext('2d');
// Set canvas size
canvas.width = 300;
canvas.height = 150;
// Wave parameters
const waveHeight = 10; // Maximum height of each wave
const waveLength = 20; // Length of each wave (distance between peaks)
const waveSpeed = 0.05; // Speed of wave movement
let time = 0; // Time variable for animation
function drawWaves() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Loop through each "row" of waves
for (let y = 0; y < canvas.height; y += waveHeight) {
ctx.beginPath();
ctx.moveTo(0, y);
// Draw each wave segment horizontally
for (let x = 0; x < canvas.width; x += 1) {
const offsetY = waveHeight * Math.sin((x / waveLength) + time + y * 0.1);
ctx.lineTo(x, y + offsetY);
}
// Stroke the wave line
ctx.strokeStyle = 'rgba(0, 162, 255, 0.6)';
ctx.stroke();
}
// Update time for the next frame
time += waveSpeed;
// Request the next animation frame
requestAnimationFrame(drawWaves);
}
// Start the wave animation
drawWaves();
</script>