Images packing algorithm in javascript

Viewed 532

I would like to create a list of images packed the same way Facebook is doing when you look at an album:

Facebook packed tiles

So, the input data is:

  1. we have a infinite list of images with known width and height
  2. we have a container with a known width and infinite height
  3. we want to show the images in the order they are listed on a prefered number of columns, adjusting their widths to fit in the container width
  4. sometimes the images are covering one or two or multiple rows as wel portrait or landscape

Some ascii scene covering the possible situations:

|------------------|------------------|------------------|
|                  |                  |                  |
|   Normal tile    |    Normal tile   |    Normal tile   |
|                  |                  |                  |
|------------------|------------------|------------------|
|                                     |                  |
|        Landscape tile               |                  |
|                                     |                  |
|------------|------------------------|------------------|
|            |                        |                  |
| Smaller    |  Landscape tile        |    Normal tile   |
|            |                        |                  |
|------------|--|------------------|--|------------------|
|               |                  |                     |
| Portrait tile |    Normal tile   |    Larger tile      |
|               |                  |                     |
|               |------------------|---------------------|
|               |                     |                  |
|               |    Larger tile      |    Normal tile   |
|               |                     |                  |
|---------------|---------------------|------------------|

I thought about using Treemap algorithm from D3 js but I am not quite sure if that would be the right choice given that in my problem I don't know the height of the container.

Treemap

It is a packing problem.

Any help or idea will be appreciated!

Update

It is acceptable that images to be scaled or clipped to better fit the layout. So, for example, if there is place for a square tile to fill a row and the current image is a portrait one, the algorithm may scale the image to the available width and clip it to the available height, or the other way around.

1 Answers
Related