Skip to content

Instantly share code, notes, and snippets.

@mmansion
Last active August 29, 2015 14:06
Show Gist options
  • Select an option

  • Save mmansion/a3b0beba06daafd81180 to your computer and use it in GitHub Desktop.

Select an option

Save mmansion/a3b0beba06daafd81180 to your computer and use it in GitHub Desktop.
Unit and group drawing distribution// source http://jsbin.com/kayut/30

Units within groups - row & column drawing distribution

<!DOCTYPE html>
<html>
<head>
<meta name="description" content="Unit and group drawing distribution" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
<style id="jsbin-css">
.unit {
position: absolute;
display: inline-block;
width: 10px !important;
height: 10px;
left: 0;
margin: 0;
padding: 0;
}
.group {
position: absolute;
height: 10px;
width: 10px;
margin: 0;
padding: 0;
border: thin black solid;
}
</style>
</head>
<body>
<script id="jsbin-javascript">
var size = 10;
var space = 3;
var groups = 30;
var unitsPerGroup = [2,3,3,4,6,6,6,6,7,7,7,7,7,8,8,8,8,8,9,9,9,9,9,9,9,9,9,9,10,10];
var palette = [ // primary <-> secondary colors
['#FB7422', '#FDAC7A'],
['#FEDF3A', '#FEEC89'],
['#BED948', '#D8E891'],
['#268368', '#7DB5A4'],
['#0A5C7D', '#6C9DB1']
];
var col = 0;
var row = 0;
var maxUnitsPerCol = avgArray(unitsPerGroup);
var offsetX = 0;
var unitsInCol = 0;
// determine number of rows and columns
var cols = Math.ceil(Math.sqrt(groups));
var rows = Math.floor(groups/cols);
for(var g =0; g < groups; g++) {
//assign group color
var primary = palette[g % palette.length][0];
var secondary = palette[g % palette.length][1];
var group = $('<div class="group"></div>');
for(var u = 0; u < unitsPerGroup[g]; u++) {
var unit = $('<div class="unit"></div>');
unit.css( 'left', u * (size + space) );
unit.css( 'background-color', primary );
unit.appendTo(group);
unitsInCol++;
}
group.css( 'width', unitsPerGroup[g] * (size + space) - space);
group.css( 'left', col * (size + space) + offsetX);
offsetX += (size + space) * (unitsPerGroup[g] -1);
group.css( 'top', row * (size + space) );
group.appendTo('body');
col++;
if(col >= cols || unitsInCol > maxUnitsPerCol) {
unitsInCol = 0;
col = 0;
offsetX = 0;
row++;
}
}
function sumArray(arr) {
return arr.reduce( function(a,b) { return a + b; } );
}
function avgArray(arr) {
return Math.round(sumArray(arr) / arr.length);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment