Random Lines
by Marc Malignan
HTML
<button id="start">START</button>
<button id="stop">STOP</button>
<canvas id="cvs"></canvas>
CSS
body {
background: #000;
color: #eee;
}
#cvs {
position: absolute;
top: 50%; left: 50%;
background: #333;
}
JavaScript
var cvs, ctx;
var w = 600;
var h = 600;
var step = 5;
var refresh = 10;
var points;
var game;
var color = 'lime';
function initCvs() {
cvs = document.getElementById("cvs");
ctx = cvs.getContext("2d");
$('#cvs')
.attr('width', w)
.attr('height', h)
.css('width', w+'px')
.css('height', h+'px')
.css('margin', (h/-2)+'px 0 0 '+(w/-2)+'px');
}
function initData() {
points = [];
points.push({ x:w/2, y:h/2, blocked:false });
}
function drawLine(x1, y1, x2, y2) {
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.strokeStyle = color;
ctx.stroke();
}
function clear() {
ctx.fillStyle = "#333";
ctx.fillRect(0, 0, w, h);
}
function gameLoop() {
points.forEach(function(el, i) {
if(!el.blocked) {
var dir = null;
while(dir===null
|| (el.lastDir==0 && dir==2)
|| (el.lastDir==1 && dir==3)
|| (el.lastDir==2 && dir==0)
|| (el.lastDir==3 && dir==1)) {
dir = Math.floor(Math.random() * 4);
}
el.lastDir = dir;
var newX = el.x;
var newY = el.y;
switch(dir) {
case 0: newY = el.y - step; break; // UP
case 1: newX = el.x + step; break; // RIGHT
case 2: newY = el.y + step; break; // DOWN
case 3: newX = el.x - step; break; // LEFT
}
drawLine(el.x, el.y, newX, newY);
if(newX==0 || newY==0 || newX==w || newY==h) {
el.x = w/2;
el.y = h/2;
}
else {
el.x = newX;
el.y = newY;
}
}
});
}
function stopGame() {
clear();
if(game) clearInterval(game);
}
function startGame() {
stopGame();
initData();
game = setInterval(gameLoop,...