(A little preview of what we're creating - but way more hypnotic!)
Have you ever wanted to make your website background say "ooooh, fancy!" without actually saying it? Let's create some smooth, undulating line waves using JavaScript's Canvas API. It's easier than you think, and the result looks like digital seaweed dancing in the virtual ocean!
The Magic Ingredients 🧙
We'll need just three basic components:
- A
<canvas>
element as our digital sketchpad - Some wave configuration magic
- An animation loop to make it all move
// Let's start by creating our canvas
const canvas = document.createElement('canvas');
canvas.classList = 'wave';
const c = canvas.getContext('2d');
document.body.append(canvas);
// Set dimensions to match viewport
canvas.width = 130;
canvas.height = innerHeight * 2;
("Wait, why 130px width?" - Because we want vertical waves!)
Wave Configuration 🌊
Here's where the fun begins. We create multiple waves with random properties:
const waves = Array.from({ length: 4 }, () => ({
x: 65,
length: Math.random() * 0.002 + 0.005,
amplitude: Math.random() * 15 + 20,
frequency: Math.random() * 0.02 + 0.005,
}));
Let's break down these wave properties:
-
x
: center position (65 = middle of 130px canvas) -
length
: how squiggly the wave is -
amplitude
: wave height -
frequency
: how fast it undulates
The Animation Loop 🔄
This is where we bring our waves to life:
function animate() {
requestAnimationFrame(animate);
c.clearRect(0, 0, canvas.width, canvas.height);
waves.forEach((wave, index) => {
// Drawing magic happens here
c.beginPath();
c.moveTo(wave.x, 0);
// Create wave path
for (let y = 0; y < canvas.height; y++) {
c.lineTo(
wave.x + Math.sin(y * wave.length + increments[index]) * wave.amplitude,
y
);
}
c.stroke();
increments[index] += wave.frequency;
});
}
(Our code making waves (literally))
See It in Action 🎬
Check out this CodePen demo to see the final result. Feel free to play with the values!
Level Up! 🚀
Want to make it even cooler? Try:
- Adding mouse interaction
- Changing colors dynamically
- Creating horizontal waves
- Adding gradient effects
(You after customizing these waves)
Remember: The best way to learn is to break things! Try changing values randomly and see what happens.
Happy coding! 🌊💻
Top comments (0)