Skip to content

Instantly share code, notes, and snippets.

@mentatxx
Last active February 24, 2022 07:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mentatxx/6088455 to your computer and use it in GitHub Desktop.
Save mentatxx/6088455 to your computer and use it in GitHub Desktop.
Waves
<html>
<head>
<title>Waves</title>
<script>
var buffer;
var sizeX = 100;
var sizeY = 75;
var stretch = 8;
// tune render performance here
var movesAtTick = 50;
var waveDeque;
var colors;
function initBuffers() {
// init two-dimensional buffer with zeroes
buffer = new Array(sizeY);
for (var i = 0; i < sizeY; i++) {
buffer[i] = new Array(sizeX);
for (var j = 0; j < sizeX; j++)
buffer[i][j] = 0;
}
;
// init wave deque and colors array
waveDeque = new Array();
colors = new Array();
colors.push('#EBEBEB');
}
function initCanvas() {
var c = document.getElementById("canv");
c.width = sizeX * stretch;
c.height = sizeY * stretch;
}
function getRandomColor() {
return '#' + Math.random().toString(16).substring(4);
}
function drawRectAtCanvas(x, y) {
var c = document.getElementById("canv");
var ctx = c.getContext("2d");
ctx.fillStyle = colors[ buffer[y][x] ];
ctx.fillRect(x * stretch, y * stretch, stretch, stretch);
}
function handleCanvasClick(e) {
var c = document.getElementById("canv");
var x = Math.ceil((e.x - c.offsetLeft) / stretch);
var y = Math.ceil((e.y - c.offsetTop) / stretch);
if ((x >= 0) && (x < sizeX) && (y >= 0) && (y < sizeY))
addWave(x, y);
}
function addWave(x, y) {
var newWave = colors.length;
colors.push(getRandomColor());
addToDeque(x, y, newWave);
}
function markPoint(x, y, value) {
buffer[y][x] = value;
drawRectAtCanvas(x, y);
}
function addToDeque(x, y, value) {
waveDeque.push({x: x, y: y, value: value});
}
function tickHandler() {
for (var i = 0; i < movesAtTick; i++) {
var newPoint = waveDeque.shift();
// are there any points in deque?
if (typeof newPoint == 'undefined')
break;
var x = newPoint.x;
var y = newPoint.y;
var value = newPoint.value;
//
if (buffer[y][x] >= value)
continue;
markPoint(x, y, value);
//
for (var j = -1; j <= 1; j++)
for (var k = -1; k <= 1; k++)
{
var xNew = x + j;
var yNew = y + k;
//
if ((xNew >= 0) && (xNew < sizeX) && (yNew >= 0) && (yNew < sizeY) && (buffer[yNew][xNew] < value)) {
//
addToDeque(xNew, yNew, value);
}
}
}
}
function init() {
initBuffers();
initCanvas();
setInterval(tickHandler, 0);
}
</script>
</head>
<body onload="init()">
<div>
<h1>Waves</h1>
<small>Click canvas below</small>
</div>
<canvas id="canv" onclick="handleCanvasClick(event)" style="border: 1px solid black;">
</canvas>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment