What formula would I use to scale multiple images to fit in a canvas?

211 Views Asked by At

I’m trying to tile random square images with a fixed width and height on a rectangular canvas.

The number of images that need to be tiled is a variable. All of the images need to show on the canvas. Image sizes need to be scaled down or up depending on the number of images that need to be fitted.

What formula would I use to scale multiple images to fit in canvas, while preserving aspect ratio for each image?

I tried different scaling formulas around StackOverflow but they focus on scaling a single image. I have X number of images that need to be scaled and fitted into the canvas.

I need the canvas to look like this :

outcome

Here is a jsfiddle of what I got. http://jsfiddle.net/7eh4adjn/1/