Last active
August 29, 2015 14:04
-
-
Save mebusila/4525a88a44456ba5da25 to your computer and use it in GitHub Desktop.
MosaicTiles
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
var MosaicTiles = (function() { | |
var _tiles = []; | |
var generate = function(cols, rows) { | |
var _i = 0, _ii = 0; | |
_tiles = []; | |
while (_i < rows) { | |
var height = Math.floor(Math.random() * (rows / 2)) + 1; | |
_ii = 0; | |
while (_ii < cols) { | |
var width = Math.floor(Math.random() * (cols / 2)) + 1; | |
if (width + _ii >= cols) { | |
width = cols - _ii; | |
} | |
if (height + _i >= rows) { | |
height = rows - _i; | |
} | |
_ii += width; | |
_tiles.push({ | |
top: _i, | |
left: _ii - width, | |
width: width, | |
height: height | |
}); | |
} | |
_i += height; | |
} | |
return this; | |
}; | |
var setTiles = function (tiles) { | |
_tiles = tiles; | |
return this; | |
}; | |
var getTiles = function () { | |
return _tiles; | |
}; | |
var prettify = function(ratio) { | |
var tmp = []; | |
for (var i = 0, max = _tiles.length; i < max; i++) { | |
var value = _tiles[i]; | |
var r = value.width / value.height; | |
if (r > ratio) { | |
var _width = 0; | |
while (_width < value.width) { | |
var height = value.height; | |
var width = Math.floor(height * ratio); | |
if (width + _width > value.width) { | |
width = value.width - _width; | |
} | |
var left = value.left + (width * _width); | |
var top = value.top; | |
tmp.push({ | |
top: top, | |
left: left, | |
width: width, | |
height: height | |
}); | |
_width += width | |
} | |
value.width -= _width; | |
} | |
if (value.width > 0) { | |
tmp.push(value); | |
} | |
} | |
return this.setTiles(tmp); | |
}; | |
return { | |
generate: generate, | |
prettify: prettify, | |
setTiles: setTiles, | |
getTiles: getTiles | |
}; | |
}()); | |
// var ratio = 2; | |
// var columns = 6; | |
// var row = 6; | |
// var tiles = MosaicTiles.generate(columns, rows).prettify(ratio).getTiles(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment