# Canvas: 2D Waves

Ciprian on Monday, March 21, 2022 in Canvas

This is the second Canvas visualization I’m experimenting with. The first one was a Julia fractal animation.

Here’s some simple waves generated using a sine function and `Math.PI`. Again, I won’t go into math details or break down the code.

Here’s the JavaScript code:

``````document.addEventListener('DOMContentLoaded', () => {
let canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
width = 500,
height = 500;

canvas.width = width;
canvas.height = height;

ctx.fillRect(0,0,canvas.width,canvas.height);
ctx.lineWidth = 2;

let waves = [];

for (let w =18; w > 10; w-=0.5) {
waves.push({amp : (w * 0.05), freq : 0, move : 0});
}

function render() {
ctx.fillRect(0, 0, canvas.width, canvas.height);

for(w = 0; w < waves.length; w++) {
let i = w + 16,
wave = waves[w];

ctx.beginPath();
ctx.moveTo(width, Math.sin(wave.freq * Math.PI / i));

for (let x = width; x >=0; x--) {
let y = Math.sin(wave.freq * Math.PI / i / 2);
wave.freq += wave.amp;
ctx.lineTo(x, (w * 32) + y * 15);
}
wave.move += (i * 0.1);
wave.freq = wave.move;
ctx.stroke();
}

requestAnimationFrame(render);
}

render();
});
``````

Give it a whirl!