Skip to content

Instantly share code, notes, and snippets.

@mentatxx
Created July 26, 2013 12:03
Show Gist options
  • Save mentatxx/6088351 to your computer and use it in GitHub Desktop.
Save mentatxx/6088351 to your computer and use it in GitHub Desktop.
JS 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 x = Math.ceil(e.clientX / stretch);
var y = Math.ceil(e.clientY / 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()">
<canvas id="canv" onclick="handleCanvasClick(event)">
</canvas>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment