Simple PhotoCollage

by Michael Zhuk

HTML

<div id="collage" class="clear">
    <img width="300" height="400" src="http://placehold.it/300x400/ffdd00/ffffff" alt=""/>
    <img width="255" height="120" src="http://placehold.it/255x120/37dcff/ffffff" alt=""/>
    <img width="300" height="300" src="http://placehold.it/300x300/28c933/ffffff" alt=""/>
    <img width="425" height="222" src="http://placehold.it/425x222/0069ff/ffffff" alt=""/>
    <img width="148" height="254" src="http://placehold.it/148x254/ff5e00/ffffff" alt=""/>
    <img width="456" height="321" src="http://placehold.it/456x321/ff9959/ffffff" alt=""/>
</div>

CSS

#collage{ width: 600px;}
#collage img{ display: block; float: left;}

JavaScript

var collage = document.getElementById('collage');
var images = collage.getElementsByTagName('img');
var options = {averageRowHeight: 175, gap: 3};
var widths = [], rows = [], rowNumber = 0, index = 0;
for(var i = 0; i < images.length; i++){
    widths.push(Math.round(images[i].width / images[i].height * options.averageRowHeight));
}
Array.prototype.sum = function(){
    return this.reduce( function(prev,current){ return  +current + prev; }, 0);
}
while(rowNumber < Math.ceil(widths.sum() / collage.clientWidth)){
    rows[rowNumber] = [];
    while(index < widths.length && rows[rowNumber].sum()+(rows[rowNumber].length * options.gap) < collage.clientWidth + options.gap){
        rows[rowNumber].push(widths[index]);
        index++;
        if(index == widths.length - 1){
            rows[rowNumber].push(widths[index]);
            rowNumber++;
            break;
        }
    }
    rowNumber++;
}
index = 0;
for(var i = 0; i < rows.length; i++){
    for(var j = 0; j < rows[i].length; j++){
        images[index].style.width = rows[i][j] * ((collage.clientWidth - ((rows[i].length - 1) * options.gap)) / rows[i].sum()) + 'px';
        images[index].style.height = ((collage.clientWidth - ((rows[i].length - 1) * options.gap)) / rows[i].sum()) * options.averageRowHeight + 'px';
        if(j < rows[i].length - 1) images[index].style.marginRight = options.gap + 'px';
        if(i < rows.length - 1) images[index].style.marginBottom = options.gap + 'px';
        index++;
    }
}