htmlintermediatemit
Fluid Waves
Animated layered sine waves.
6.8k925575285
About this module
Three sine waves with different colors, speeds and amplitudes layered into a smooth fluid motion.
#canvas#2d#waves#fluid#sine
Source code
Installation
- 1
Create the files
Create `index.html`, `style.css` and `script.js` in the same folder.
- 2
Paste the code
Copy each file's source into its matching file.
- 3
Open in the browser
Open `index.html` in any modern browser.
Usage
- 1
Copy the HTML
Paste the canvas markup where you need it.
<link rel="stylesheet" href="style.css" /> <script src="script.js"></script> <div class="mh-canvas-wrap"> <canvas id="mh-canvas"></canvas> </div> - 2
Wire up the script
Include `script.js` before the closing body tag.
const canvas = document.getElementById("mh-canvas"); const ctx = canvas.getContext("2d"); let w, h, dpr = Math.min(window.devicePixelRatio || 1, 2), t = 0; const WAVES = [ { color: "rgba(99,102,241,0.5)", amp: 26, speed: 0.012, off: 0 }, { color: "rgba(168,85,247,0.4)", amp: 34, speed: 0.018, off: 1.5 }, { color: "rgba(236,72,153,0.3)", amp: 20, speed: 0.009, off: 3 } ]; function resize() { const rect = canvas.parentElement.getBoundingClientRect(); w = rect.width; h = rect.height; canvas.width = w * dpr; canvas.height = h * dpr; canvas.style.width = w + "px"; canvas.style.height = h + "px"; ctx.setTransform(dpr, 0, 0, dpr, 0, 0); } function tick() { ctx.clearRect(0, 0, w, h); WAVES.forEach((wave, idx) => { const base = h * (0.35 + idx * 0.18); ctx.beginPath(); ctx.moveTo(0, base); for (let x = 0; x <= w; x += 4) { const y = base + Math.sin(x * 0.012 + t * wave.speed + wave.off) * wave.amp; ctx.lineTo(x, y); } ctx.lineTo(w, h); ctx.lineTo(0, h); ctx.closePath(); ctx.fillStyle = wave.color; ctx.fill(); }); t += 0.5; requestAnimationFrame(tick); } resize(); window.addEventListener("resize", resize); tick();