Last active
December 28, 2015 06:29
-
-
Save icodeforlove/7457646 to your computer and use it in GitHub Desktop.
getBlocksFromRect.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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