Calculate number images in a row to fit container while keeping aspect ratio
23:23 08 Jan 2020

I want to create a masonry horizontal layout like this library. It contain collection of images with different height and width each other.

The layout can have one or more rows, as long as it meets this criteria:

  • Row width fit to the masonry container width
  • Row can have different height each other
  • Row have restriction minimum and maximum height value

A row can have one or more columns (the image), as long as it meets this criteria:

  • Image keep their aspect ratio
  • Image in same row must be same height Has fixed gap width each image

Here the illustration:

enter image description here

Here is the more real example of Canva images tab:

enter image description here

I'm starting to code this using JavaScript (React Hook), but I'm stuck with the logic.

Imagine there is lot of images with different dimension, that has inline-block display style. My current logic to that case is:

  • Get images width and height for keeping aspect ratio Modify images
  • height with minimum row height value, while keeping aspect ratio
  • Now all images has same height, but row width isn't fit to container
  • And then i'm stuck on this

Part of current progress

function Masonry({ minHeight, children }) {
  const _originalDimension = [];
  const _tempDimension = [];

  children.forEach(({ props: { height, width } }) => {
    const newWidth = (width / height) * minHeight;
    const newHeight = minHeight;

    _originalDimension.push({ height, width });
    _tempDimension.push({ height: newHeight, width: newWidth });
  });

  const { container } = useStyles();
  return (
    
{children.map((child, i) => cloneElement(child, { key: i, ..._tempDimension[i] }) )}
); }

I can't reach how possibly a row can fit to the container width and how can a row calculate number of images to fit minimum or maximum row height.

Please help me out, thanks in advance.

javascript reactjs algorithm logic masonry