Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

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.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

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.

+ add another resource

Packages

Add Packages

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.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <svg 
  viewBox="0 0 1000 1000" 
  width="1000" 
  height="1000" 
  role="img"
>
  <title>
    A square maze.
  </title>
  
  <style> 
    g {  
      --cell-size: 50px;
      --stroke-width: 10px;
    }
    
    .grid-line {
      fill: none;
      stroke: var(--maze-stroke-color);
      stroke-width: var(--stroke-width);
      stroke-linecap: square;
    }

    .maze-path {
      fill: none;
      stroke: red;
      stroke-width: 10;
      stroke: white;
      stroke-width: calc(var(--cell-size) - var(--stroke-width));
      stroke-linecap: square;
    }
  </style>

  <g class="grid"></g>
  <g class="pattern">
    <!-- 
      Our graphics code goes here 
    -->
  </g>
</svg>

<div class="buttons">
  <button class="randomize">Randomize</button>
</div>
              
            
!

CSS

              
                html, body {
  --hue: 205;
  
  display: grid;
  place-items: center;
  min-height: 100%;
  --maze-bg-color: hsl(270deg, 15%, 44%);
  --maze-stroke-color: hsl(270deg, 15%, 40%);
}

svg {
  background: #fff;
  max-width: 90vw;
  max-height: 85vh;
  width: auto;
  height: auto;
  overflow: visible;
  background: var(--maze-bg-color);
}


button {
  
  /* Text Colors */
  --text-saturation: 90%;
  --text-lightness: 40%;
  
  --text-saturation-hover: calc(var(--text-saturation) + 10%);
  --text-lightness-hover: calc(var(--text-lightness) - 5%); ;
  
  --text-saturation-active: var(--text-saturation-hover);
  --text-lightness-active: calc(var(--text-lightness) - 10%); ;
  
  --text-saturation-disabled: calc(var(--text-saturation) - 60%);
  --text-lightness-disabled: calc(var(--text-lightness) + 10%);
  
  /* Background Colors */
  --background-saturation: 0%;
  --background-lightness: 100%;
  
  --background-saturation-hover: calc(var(--background-saturation) + 80%);
  --background-lightness-hover: calc(var(--background-lightness) - 5%);
  
  --background-saturation-active: var(--background-saturation-hover);
  --background-lightness-active: calc(var(--background-lightness) - 10%);
  
  --background-saturation-disabled: calc(var(--background-saturation) + 30%);
  --background-lightness-disabled: calc(var(--background-lightness) - 10%);
  
  /* Border Colors */
  --border-saturation: 90%;
  --border-lightness: 60%;
  
  --border-saturation-hover: calc(var(--border-saturation) + 10%);
  --border-lightness-hover: calc(var(--border-lightness) - 10%);
  
  --border-saturation-active: var(--border-saturation-hover);
  --border-lightness-active: calc(var(--border-lightness) - 20%);
  
  --border-saturation-disabled: calc(var(--border-saturation) - 60%);
  --border-lightness-disabled: calc(var(--border-lightness) + 20%);
  
  /* Focus shadow styles */
  --shadow-saturation-focus: 100%;
  --shadow-lightness-focus: 85%;
  
  /* Color Styles */
  color: hsl(var(--hue), var(--text-saturation), var(--text-lightness));
  background-color: hsl(var(--hue), var(--background-saturation), var(--background-lightness)); 
  border:0.1em solid hsl(var(--hue), var(--border-saturation), var(--border-lightness)); 
  
  /* Misc. Styles */
  border-radius: 0.25em;
  cursor: pointer;
  display: inline-block;
  font-size: 1em;
  padding: 0.5em 1em;
  transition-property: box-shadow, background-color, border-color, color;
  transition-timing-function: ease-out;
  transition-duration: 0.2s;
}

button:hover {
  color: hsl(
    var(--hue), 
    var(--text-saturation-hover), 
    var(--text-lightness-hover)
  );
  
  background-color: hsl(
    var(--hue), 
    var(--background-saturation-hover), 
    var(--background-lightness-hover)
  );
  
  border-color: hsl(
    var(--hue), 
    var(--border-saturation-hover), 
    var(--border-lightness-hover)
  );
}

button:active {
  color: hsl(
    var(--hue), 
    var(--text-saturation-active), 
    var(--text-lightness-active)
  );
  
  background-color: hsl(
    var(--hue), 
    var(--background-saturation-active), 
    var(--background-lightness-active)
  );
  
  border-color: hsl(
    var(--hue), 
    var(--border-saturation-active), 
    var(--border-lightness-active)
  );
}

button:focus {
  outline: none;
  box-shadow: 0 0 0 0.25em hsl(
    var(--hue), 
    var(--shadow-saturation-focus),
    var(--shadow-lightness-focus)
  );
}

.buttons {
  display: flex;
  gap: 0.5em;
}
              
            
!

JS

              
                import { randomInt, randomItemInArray, randomChance } from 'https://unpkg.com/randomness-helpers@0.0.1/dist/index.js';

const svgEl = document.querySelector('svg');
const patternEl =  document.querySelector('.pattern');
const gridEl = document.querySelector('.grid');

const gridWidth = 20;
const gridHeight = 20;
const scale = 50;
const splittingChance = 0.1;
const animationSpeed = 20;
const retryLimit = 30;

let interval;

let failedCount = 0;
let mainPathPoints = [];
let otherPaths = [];

let gridData = buildFreshGrid();

function drawGrid() {
  let gridMarkup = '';
  for(let y = 0; y <= gridHeight; y++) {
    gridMarkup += `
      <line 
        class="grid-line"
        x1="0" 
        x2="${gridWidth * scale}"
        y1="${y * scale}"
        y2="${y * scale}"
      />
    `;
  }
  for(let x = 0; x <= gridWidth; x++) {
    gridMarkup += `
      <line 
        class="grid-line"
        y1="0" 
        y2="${gridHeight * scale}"
        x1="${x * scale}"
        x2="${x * scale}"
      />
    `;
  }
  return gridMarkup;
}

function buildFreshGrid() {
  return new Array(gridHeight).fill().map(
    () => new Array(gridWidth).fill(0)
  );
}

function adjustMazePoint(point) {
  return {
    x: scale / 2 + point.x * scale,
    y: scale / 2 + point.y * scale
  }
}

function buildPathData(points) {
  points = points.map(adjustMazePoint);
  
  const firstPoint = points.shift();

  let commands = [`M ${firstPoint.x}, ${firstPoint.y}`];
  
  points.forEach(point => {
    commands.push(`L ${point.x}, ${point.y}`);
  });
  
  return commands.join(' ');
}

function drawLine(points, className = '') {
  return `
    <path
      class="maze-path ${className}" 
      d="${buildPathData(points)}"
    />
  `;
}

function mainPathStartPoints() {
  const yStart = randomInt(0, gridHeight - 1);
  
  return [
    {
      x: -1, 
      y: yStart
    },
    {
      x: 0, 
      y: yStart
    }
  ]
}

function markPointAsTaken(point, value = 1) {
  gridData[point.y][point.x] = value;
}

function findNextPoint(point) {
  const potentialPoints = [];
  
  if(gridData[point.y - 1]?.[point.x] === 0) {
    potentialPoints.push({
      y: point.y - 1,
      x: point.x
    });
  }
  
  if(gridData[point.y + 1]?.[point.x] === 0) {
    potentialPoints.push({
      y: point.y + 1,
      x: point.x
    });
  }
  
  if(gridData[point.y]?.[point.x - 1] === 0) {
    potentialPoints.push({
      y: point.y,
      x: point.x - 1
    });
  }
  
  if(gridData[point.y]?.[point.x + 1] === 0) {
    potentialPoints.push({
      y: point.y,
      x: point.x + 1
    });
  }
  
  if(potentialPoints.length === 0) {
    return undefined;
  }
  
  return randomItemInArray(potentialPoints);
}

function refreshState() {
  mainPathPoints = mainPathStartPoints();
  gridData = buildFreshGrid();
  markPointAsTaken(mainPathPoints.at(-1));
  otherPaths = [];
  failedCount = 0;
}

function drawLines() {
  let markup = '';
  
  markup += otherPaths.map(drawLine).join('');
  
  markup += drawLine(mainPathPoints, 'main');
  
  patternEl.innerHTML = markup;
}

function buildMainPath() {
  refreshState();
  
  drawLines();
  
  interval = setInterval(() => {
    const nextPoint = findNextPoint(mainPathPoints.at(-1));
  
    if(!nextPoint) {
      if(failedCount > retryLimit) {
        refreshState(); 
      } else {
        failedCount++;
        for(let i = 0; i < failedCount; i++) {
          markPointAsTaken(mainPathPoints.pop(), 0);
        }
      }
    } else {
      mainPathPoints.push(nextPoint);
      markPointAsTaken(nextPoint);
      
      if(nextPoint.x === gridWidth - 1) {
        mainPathPoints.push({
          x: nextPoint.x + 1,
          y: nextPoint.y
        })
        clearInterval(interval);
        
        buildOtherPaths();
      }
    }
    
    drawLines();
  }, animationSpeed);
}

function addMorePaths() {
  gridData.forEach((row, y) => {
    row.forEach((cell, x) => {
      if(cell && randomChance(splittingChance)) {
        otherPaths.push([{
          y,
          x,
        }]);
      }
    })
  })
}

function mazeComplete() { 
  return gridData.flat().every(cell => cell === 1);
}

function buildOtherPaths() {
  interval = setInterval(() => {
    addMorePaths();
  
    otherPaths.forEach((path) => {
      const nextPoint = findNextPoint(path.at(-1));
      
      if(nextPoint) {
        path.push(nextPoint);
        markPointAsTaken(nextPoint);
      }
    });
  
    drawLines();
  
    if(mazeComplete()) {
      clearInterval(interval);
      console.log('maze done');
    }
  }, animationSpeed);
}

function draw() { 
  
  gridEl.innerHTML = drawGrid();
  
  const mazeWidth = gridWidth * scale;
  const mazeHeight = gridHeight * scale;
  svgEl.setAttribute('viewBox', `0 0 ${mazeWidth} ${mazeHeight}`);
  svgEl.setAttribute('width', mazeWidth);
  svgEl.setAttribute('height', mazeHeight);
  
  patternEl.innerHTML = '';
  
  clearInterval(interval);
  buildMainPath();
}

draw();

document.querySelector('.randomize').addEventListener('click', draw);

              
            
!
999px

Console