HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
Any URLs added here will be added as <link>
s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
Any URL's added here will be added as <script>
s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
Search for and use JavaScript packages from npm here. By selecting a package, an import
statement will be added to the top of the JavaScript editor for this package.
Using packages here is powered by esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
<main>
<div class="maze">
<canvas></canvas>
</div>
<button>Create new maze</button>
</main>
html, body {
width: 100%;
height: 100%;
margin: 0;
font-family: Helvetica Neue, sans-serif;
font-size: 14px;
}
main {
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
padding: 2% 5%;
overflow: auto;
}
html * {
box-sizing: border-box;
}
.maze {
width: 100%;
min-width: 200px;
min-height: 100px;
max-width: 1000px;
max-height: 1000px;
display: flex;
align-items: center;
justify-content: center;
flex-grow: 1;
}
canvas {
border: 1px solid black;
}
button {
padding: 8px 20px;
margin-top: 15px;
background: white;
border: 2px solid #2d84da;
border-radius: 8px;
color: #333;
font-size: 16px;
cursor: pointer;
outline: none;
transition: all 100ms ease-in;
}
button:hover {
background: rgba(45, 132, 218, 0.4);
transition: all 100ms ease-out;
}
button[disabled] {
border-color: #aaa;
background: white !important;
color: #666;
cursor: default;
}
(() => {
window.addEventListener('load', () => {
const mazeContainer = document.querySelector('.maze');
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
const pixelRatio = window.devicePixelRatio || 1;
const lineWidth = 2;
let size = 20;
let width = 0;
let height = 0;
let rows = 0;
let cols = 0;
let grid = [];
let current = null;
let animation = null;
let maxDistance = 0;
// check whether two cells are linked
const isLinked = (cellA, cellB) => {
const link = cellA.links.find(l => l.row === cellB.row && l.col === cellB.col);
return !!link;
};
// get all neighbors of a cell
const getNeighbors = cell => {
const list = [];
if (cell.north) list.push(grid[cell.north.row][cell.north.col])
if (cell.south) list.push(grid[cell.south.row][cell.south.col])
if (cell.east) list.push(grid[cell.east.row][cell.east.col])
if (cell.west) list.push(grid[cell.west.row][cell.west.col])
return list;
};
// each step of algorithm — calculate and render
const huntAndKillStep = () => {
const unvisitedNeighbors = getNeighbors(current).filter(n => n.links.length === 0);
const { length } = unvisitedNeighbors;
if (length) {
const rand = Math.floor(Math.random() * length);
const { row, col } = unvisitedNeighbors[rand];
current.links.push({ row, col });
grid[row][col].links.push({ row: current.row, col: current.col });
current = unvisitedNeighbors[rand];
} else {
current = null;
loop:
for (let row of grid) {
for (let cell of row) {
const visitedNeighbors = getNeighbors(cell).filter(n => n.links.length !== 0);
if (cell.links.length === 0 && visitedNeighbors.length !== 0) {
current = cell;
const rand = Math.floor(Math.random() * visitedNeighbors.length);
const { row, col } = visitedNeighbors[rand];
current.links.push({ row, col });
grid[row][col].links.push({ row: current.row, col: current.col });
break loop;
}
}
}
}
renderGrid();
if (current) {
animation = requestAnimationFrame(huntAndKillStep);
} else {
maxDistance = 0;
calculateDistances();
}
};
// start of the algorithm — with a random cell
const huntAndKill = () => {
current = grid[Math.floor(Math.random() * rows)][Math.floor(Math.random() * cols)];
huntAndKillStep();
};
// reqursive walk through links to calculate distances from top left corner and render changes
const calculateDistances = (row = 0, col = 0, value = 0) => {
animation = requestAnimationFrame(() => {
maxDistance = Math.max(maxDistance, value);
grid[row][col].distance = value;
grid[row][col].links.forEach(l => {
const { distance } = grid[l.row][l.col];
if (!distance && distance !== 0) {
calculateDistances(l.row, l.col, value + 1);
}
});
fillGrid();
});
};
// rerender color grid
const fillGrid = () => {
for (let row of grid) {
for (let cell of row) {
const { distance } = cell;
if (distance) {
const intensity = (maxDistance - distance) / maxDistance;
const dark = Math.round(255 * intensity);
const bright = 128 + Math.round(127 * intensity);
const x1 = cell.x1 + (!cell.west || !isLinked(cell, cell.west) ? lineWidth / 2 : 0);
const y1 = cell.y1 + (!cell.north || !isLinked(cell, cell.north) ? lineWidth / 2 : 0);
const x2 = cell.x2 - (!cell.east || !isLinked(cell, cell.east) ? lineWidth / 2 : 0);
const y2 = cell.y2 - (!cell.south || !isLinked(cell, cell.south) ? lineWidth / 2 : 0);
ctx.fillStyle = `rgb(${dark}, ${dark}, ${bright})`;
ctx.fillRect(x1, y1, x2 - x1, y2 - y1);
}
}
}
};
// render borders of cells
const renderBorders = () => {
ctx.strokeStyle = '#000';
ctx.lineWidth = lineWidth;
for (let row of grid) {
for (let cell of row) {
const {
x1, y1, x2, y2,
north, south, west, east,
} = cell;
if (!north) {
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y1);
ctx.stroke();
}
if (!west) {
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x1, y2);
ctx.stroke();
}
if (!south || !isLinked(cell, south)) {
ctx.beginPath();
ctx.moveTo(x1, y2);
ctx.lineTo(x2, y2);
ctx.stroke();
}
if (!east || !isLinked(cell, east)) {
ctx.beginPath();
ctx.moveTo(x2, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
}
}
}
};
// render the main grid on each step of the algorithm
const renderGrid = () => {
ctx.clearRect(0, 0, width * pixelRatio, height * pixelRatio);
for (let row of grid) {
for (let cell of row) {
const { x1, y1, x2, y2 } = cell;
if (cell.links.length === 0) {
ctx.fillStyle = '#ccc';
ctx.fillRect(x1, y1, x2 - x1, y2 - y1);
}
if (current && cell.row === current.row && cell.col === current.col) {
ctx.fillStyle = '#2d84da';
ctx.fillRect(x1, y1, x2 - x1, y2 - y1);
}
}
}
renderBorders();
};
// initialize the grid with not connected cells
const createGrid = () => {
grid = [];
for (let i = 0; i < rows; i++) {
const row = [];
for (let j = 0; j < cols; j++) {
row.push({
row: i,
col: j,
links: [],
})
}
grid.push(row);
}
grid.forEach((row, i) => {
row.forEach((cell, j) => {
if (i > 0) cell.north = { row: i - 1, col: j };
if (i < rows - 1) cell.south = { row: i + 1, col: j };
if (j > 0) cell.west = { row: i, col: j - 1 };
if (j < cols - 1) cell.east = { row: i, col: j + 1 };
});
});
positionCells();
};
// calculate and save cells x and y coordinates
const positionCells = () => {
grid.forEach(row => {
row.forEach(cell => {
cell.x1 = cell.col * size * pixelRatio;
cell.y1 = cell.row * size * pixelRatio;
cell.x2 = (cell.col + 1) * size * pixelRatio;
cell.y2 = (cell.row + 1) * size * pixelRatio;
});
});
};
// resize canvas, grid and cells
const resize = change => {
width = mazeContainer.clientWidth;
height = mazeContainer.clientHeight;
if (change) {
size = Math.min(Math.floor(height / rows), Math.floor(width / cols));
} else {
rows = Math.floor(height / size);
cols = Math.floor(width / size);
}
width = cols * size;
height = rows * size;
canvas.width = width * pixelRatio;
canvas.height = height * pixelRatio;
canvas.style.width = `${width}px`
canvas.style.height = `${height}px`
};
// main method — set sizes, init and prerender grid, start the algorithm
const createMaze = () => {
window.cancelAnimationFrame(animation);
resize();
createGrid();
renderGrid();
huntAndKill();
};
createMaze();
const button = document.querySelector('button');
button.addEventListener('click', () => {
createMaze();
});
window.addEventListener('resize', () => {
resize(true);
positionCells();
renderGrid();
fillGrid();
});
});
})();
Also see: Tab Triggers