Published
Edited
Apr 28, 2019
2 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
numCells = canvasSize / cellSize;
Insert cell
function create2dArray(size, defaultValue) {
return Array(size).fill().map(() => Array(size).fill(defaultValue != null ? defaultValue : 0))
}
Insert cell
grid = {
const size = Math.floor(canvasSize / cellSize);
return create2dArray(size)
}
Insert cell
function drawGrid(ctx, fillStyle) {
ctx.fillStyle = fillStyle;
for (let i = 0; i < numCells; i++) {
for (let j = 0; j < numCells; j++) {
if(grid[j,i]) {
ctx.fillRect(j * cellSize, i * cellSize, 5, 5)
}
}
}
}
Insert cell
function drawEdge(ctx, fromX, fromY, toX, toY, color) {
ctx.strokeStyle = color;
ctx.lineWidth = 5;
ctx.moveTo(fromX * cellSize + cellSize / 2, fromY * cellSize + cellSize / 2)
ctx.lineTo(toX * cellSize + cellSize / 2, toY * cellSize + cellSize / 2)
ctx.stroke()
}
Insert cell
function generate(ctx, startX, startY) {
const visited = create2dArray(numCells, false);
function shuffled(array){
const copy = Array.from(array);
for (let i = 0; i < copy.length; i++) {
const randIdx = i + Math.floor(Math.random() * copy.length - i);
const temp = copy[randIdx];
copy[randIdx] = copy[i];
copy[i] = temp;
}
return copy;
}
function validCell(x,y) {
return x >= 0 && x < numCells && y >= 0 && y < numCells && !visited[y][x]
}
function getNghbrs(x, y) {
return [[x - 1, y], [x + 1, y], [x, y - 1], [x, y + 1]];
}
function dfs(ctx, startX, startY) {
visited[startY][startX] = true;
for (const [x,y] of shuffled(getNghbrs(startX, startY).filter(([x,y]) => validCell(x,y)))) {
if(validCell(x,y)) {
drawEdge(ctx, startX, startY, x, y, "white");
dfs(ctx, x, y);
}
}
}
dfs(ctx, startX, startY)
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more