Skip to content

Instantly share code, notes, and snippets.

@icodeforlove
Last active December 28, 2015 06:29
Show Gist options
  • Select an option

  • Save icodeforlove/7457646 to your computer and use it in GitHub Desktop.

Select an option

Save icodeforlove/7457646 to your computer and use it in GitHub Desktop.
getBlocksFromRect.js
function getBlocksFromRect(width, height, blockCount) {
var blocks = [], cols, rows;
if (Math.sqrt(blockCount) === Math.floor(Math.sqrt(blockCount))) {
cols = rows = Math.sqrt(blockCount);
} else {
cols = blockCount / 2 === Math.floor(blockCount / 2) ? 2 : 1;
rows = blockCount / cols;
}
var blockWidth = Math.ceil(width/cols),
blockHeight = Math.ceil(height/rows);
for (var row = 0; row < rows; row++) {
for (var col = 0; col < cols; col++) {
var x = col * blockWidth,
y = row * blockHeight,
w,
h;
if (width - (col * blockWidth) >= blockWidth) {
w = blockWidth;
} else {
w = width - (col * blockWidth);
}
if (height - (row * blockHeight) >= blockHeight) {
h = blockHeight;
} else {
h = height - (row * blockHeight);
}
blocks.push({x: x, y: y, width: w, height: h});
}
}
return blocks;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment