Waves

Waves experiment after seeing on The Coding Train.

by Victor Ribeiro

HTML

<canvas id="canvas"></canvas>

CSS

html, body {
	margin: 0;
	padding: 0;
	background-color: blue;
}
canvas {
	display: block;
	opacity: 0.5;
}

JavaScript

let s = 5; /* size - the bigger the faster (lower quality) */
let canvas = document.getElementById("canvas");
canvas.width = w = Math.floor(innerWidth/s);
canvas.height = h = Math.floor(innerHeight/s);
canvas.style.width = w*s+'px';
canvas.style.height = h*s+'px';
let c = canvas.getContext("2d");
	
let buffer1 = Array(w).fill().map(_=>Array(h).fill(0));
let buffer2 = Array(w).fill().map(_=>Array(h).fill(0));
let damping = 0.99;
let temp;

function animation(){
	
	for(let i = 1; i < w-1; i++){
		for(let j = 1; j < h-1; j++){
			buffer2[i][j] = (buffer1[i-1][j] +
											 buffer1[i+1][j] +
											 buffer1[i][j-1] +
											 buffer1[i][j+1]) / 2 - buffer2[i][j];
			buffer2[i][j] *= damping;
		}
	}
	
	for(let i = 0; i < buffer1.length; i++){
		for(let j = 0; j < buffer1[0].length; j++){
			c.fillStyle = 'rgb('+buffer2[i][j]+','
													+buffer2[i][j]+','
													+buffer2[i][j]+')';
			c.fillRect(i,j,1,1);
		}
	}
	
	temp = buffer2;
	buffer2 = buffer1;
	buffer1 = temp;
	u = requestAnimationFrame(animation);
}

animation();

document.addEventListener("mousedown",function(e){
	let x = Math.floor(e.clientX/s);
	let y = Math.floor(e.clientY/s);
	buffer1[x][y] = 255;
});

window.addEventListener("resize",function(){
	location.reload();
});