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

              
                <canvas></canvas>
              
            
!

CSS

              
                body {
  background-color: black;
}
canvas {
  --di: min(100vw, 100vh);
  display: block;
  height: var(--di);
  left: calc(50% - var(--di) * 0.5);
  position: fixed;
  top: calc(50% - var(--di) * 0.5);
  width: var(--di);
}
              
            
!

JS

              
                const canvas = document.querySelector("canvas");
const context = canvas.getContext("2d");
const PI = Math.PI;

class Packer {
  fit(blocks) {
    this.blocks = {};
    this.idsByWidth = [];
    this.idsByHeight = [];
    let totalArea = 0;
    blocks.forEach((block) => {
      this.idsByHeight.push(block.id);
      this.idsByWidth.push(block.id);
      this.blocks[block.id] = block;
      totalArea += block.area;
    });
    this.idsByHeight.sort(
      (a, b) =>
        this.blocks[b].height - this.blocks[a].height ||
        this.blocks[b].area - this.blocks[a].area
    );
    this.idsByWidth.sort(
      (a, b) =>
        this.blocks[b].width - this.blocks[a].width ||
        this.blocks[b].area - this.blocks[a].area
    );

    return this.performLoop(totalArea, 1.1);
  }

  performLoop(totalArea, factor) {
    return new Promise((resolve) => {
      const fit = this.performCorner(0, 0, Math.sqrt(totalArea * factor));
      resolve(fit ? true : this.performLoop(totalArea, factor + 0.04));
    });
  }

  adjustedDiameterFromDiameterAndPosition(position, diameter) {
    const degrees = (position / diameter) * 45;
    const angle = degrees * (PI / 180);
    return Math.cos(angle) * diameter;
  }

  performCorner(
    startX,
    startY,
    diameter,
    i = 0,
    j = 0,
    used = {},
    loopIndex = 0
  ) {
    let x = startX;
    let y = startY;
    let newX = null;
    let newY = null;
    let firstX = false;
    let firstHeight = null;
    let firstWidth = null;
    const di = this.adjustedDiameterFromDiameterAndPosition(startX, diameter);
    while (x < di && i < this.idsByHeight.length) {
      const block = this.blocks[this.idsByHeight[i]];
      if (!used[block.id]) {
        if (newX === null && !firstX) {
          y += block.height;
        }
        if (firstHeight === null) {
          firstHeight = block.height;
        }
        if (newX === null && firstX) {
          newX = x;
        }
        firstX = true;
        used[block.id] = 1;
        const localY = startY + Math.floor((firstHeight - block.height) * 0.5);
        block.fit = { x, y: localY };
        x += block.width;
      }
      i++;
    }
    while (y < di && j < this.idsByWidth.length) {
      const block = this.blocks[this.idsByWidth[j]];
      if (!used[block.id]) {
        if (firstWidth === null) {
          firstWidth = block.width;
        }
        used[block.id] = 1;
        const localX = startX + Math.floor((firstWidth - block.width) * 0.5);
        block.fit = { x: localX, y };
        if (newY === null) {
          newY = y;
          newX = startX + block.width;
        }
        y += block.height;
      }
      j++;
    }
    if (loopIndex === 0) {
      this.root = { width: x, height: y };
    }
    if (newY !== null && newX !== null) {
      return this.performCorner(
        newX,
        newY,
        diameter,
        i,
        j,
        used,
        loopIndex + 1
      );
    }
    return Object.keys(used).length === Object.keys(this.blocks).length;
  }
}

document.addEventListener("click", run);

run();

async function run() {
  const canvasDi = Math.min(window.innerWidth, window.innerHeight) * 2;
  canvas.height = canvas.width = canvasDi;
  const MAX_DI = canvasDi * 0.033;
  const MIN_DI = MAX_DI * 0.1;
  const DI_DIFF = MAX_DI - MIN_DI;
  const GAP = MAX_DI * 0.1;
  const randomVal = () => Math.round(Math.random() * DI_DIFF + MIN_DI);
  const randomSize = () => ({ width: randomVal(), height: randomVal() });
  const items = [];
  for (let i = 0; i < 1000; i++) {
    const { width, height } = randomSize();
    items.push({
      id: i,
      x: Math.random() * canvasDi,
      y: Math.random() * canvasDi,
      hue: Math.round(Math.random() * 360),
      height: height + GAP,
      width: width + GAP,
      area: (width + GAP) * (height + GAP),
    });
  }
  const groups = [[], [], [], []];
  const sortedByArea = items.sort((a, b) => b.area - a.area);
  sortedByArea.forEach((item, i) => groups[i % 4].push(item));

  await Promise.all(groups.map(pack));
  let time = 0;
  const animationFrame = requestAnimationFrame(loop);

  function loop() {
    draw(groups, Math.min(1, time));
    time += 0.015;
    if (time <= 1.1) requestAnimationFrame(loop);
  }

  async function pack(items, i) {
    const packer = new Packer();
    await packer.fit(items);
    const rootW = packer.root.width;
    const rootH = packer.root.height;
    const flipX = i === 1 || i === 2;
    const flipY = i === 2 || i === 3;
    const offsetX = flipX ? rootW * -1 : 0;
    const offsetY = flipY ? rootH * -1 : 0;
    items.forEach((item) => {
      const itemX = flipX ? rootW - item.fit.x - item.width : item.fit.x;
      const itemY = flipY ? rootH - item.fit.y - item.height : item.fit.y;
      item.finalX = itemX + offsetX + canvasDi * 0.5;
      item.finalY = itemY + offsetY + canvasDi * 0.5;
    });
    return true;
  }

  function draw(groups, time) {
    context.clearRect(0, 0, canvasDi, canvasDi);
    groups.forEach((items, i) => {
      items.forEach((item, j) => {
        context.fillStyle = `hsla(${item.hue}, 100%, 50%, ${time})`;
        const { x, y, finalX, finalY, width, height } = item;
        const newX = x + ((finalX - x) * time);
        const newY = y + ((finalY - y) * time);
        context.fillRect(newX, newY, width - GAP, height - GAP);
      })
    });
  }
}

              
            
!
999px

Console