procedural labyrinth (not my own)

by John Doe

HTML

<canvas id='c'></canvas>

CSS

canvas {
    border:solid 1px #000;
}

JavaScript

var canvas = document.getElementById('c');
var dim = 10; // size of a cell
var w = 20 * 2 + 1; // number of horizontal cell (20)
var h = 20 * 2 + 1; // number of vertical cell (20)
canvas.width = (w + 2) * dim;
canvas.height = (h + 2) * dim;
var c2d = canvas.getContext('2d');
// clear the canvas
c2d.fillStyle = "#000";
c2d.fillRect(0, 0, canvas.width, canvas.height);
// draw enter and exit
c2d.fillStyle = "#fff";
c2d.fillRect(0, dim, dim, dim);
c2d.fillRect(canvas.width - dim, canvas.height - dim * 2, dim, dim);
// initialize the grid
var grid = [];
grid.length = h;
for (var y = 0; y < h; y++) {
    grid[y] = [];
    grid[y].length = w;
}
var nextCell = [ [0, 0] ];
function AddCell(x,y,onlyFill)
{
    c2d.fillRect((x+1) * dim, (y+1) * dim, dim, dim);
    grid[y][x] = 1;
    if( onlyFill === undefined )
        nextCell.push([x, y]);
}
// add first cell
AddCell(0,0);

function FillCell()
{
    // pick a random cell from list
    var i = Math.floor(Math.random() * nextCell.length);
    var cc = nextCell.splice(i, 1)[0];
    var x = cc[0];
    var y = cc[1];
    // add the neighbors to list if they are not already done.
    var sides = [ [-1, 0], [1, 0], [0, -1], [0, 1] ];
    for (i = 0; i < 4; i++) {
        var nx = x + sides[i][0] * 2;
        var ny = y + sides[i][1] * 2;
        if (nx >= 0 && nx < w && ny >= 0 && ny < h && grid[ny][nx] === undefined) 
        {
            AddCell(x + sides[i][0],y + sides[i][1],true);
            AddCell(nx,ny);
        }
    }
    if (nextCell.length !== 0) requestAnimationFrame(FillCell);
}
//start
FillCell();