class Rectangle {
constructor(left, top, width, height) {
Object.assign(this, {left, top, width, height});
}
splitVertically() {
const width = this.width / 2;
return [
new Rectangle(this.left, this.top, width, this.height),
new Rectangle(this.left + width, this.top, width, this.height)
];
}
splitHorizontally() {
const height = this.height / 2;
return [
new Rectangle(this.left, this.top, this.width, height),
new Rectangle(this.left, this.top + height, this.width, height)
];
}
draw(ctx) {
ctx.rect(this.left+0.5, this.top+0.5, this.width, this.height);
ctx.stroke();
}
}
function splitBlock(n, rect) {
let deque = [rect];
while (n-- > 0) {
const rect = deque.shift();
const arr = rect.splitVertically();
if (n-- > 0) arr.push(...arr.shift().splitHorizontally());
if (n-- > 0) arr.push(...arr.shift().splitHorizontally());
deque.push(...arr);
}
return deque;
}
// Example run
const numSplits = 11;
const blocks = splitBlock(numSplits, new Rectangle(0, 0, 180, 180))
// Output the result on a canvas
const ctx = document.querySelector("canvas").getContext("2d");
for (const block of blocks) block.draw(ctx);
<canvas width="181" height="181"></canvas>