I want to make an interface with a container where the user choose a number of squares to showing in. The squares have to use the maximum of space, with a minimum lost. So, the width of a square have must to be calculated from the container's width and height.
Starting with this problem, I quickly arrived at this function:
function calcSquareWidth(nbSquares = 1) { //items is the number of squares
let width = $('#container').width(); //width of the container
let height = $('#container').height(); //height of the container
return Math.sqrt((width * height) / nbSquares); //width of a square
}
In theory this works, but this function does not take into account the wasted space of the container. In other words, it gives the side of one of the squares, if we want to use the whole container. But we only want to use the maximum portion of the container to display them, not the whole thing.
So I started from the principle that I had to find a way to recover the excess surface, then subtract it from the total surface of the container and apply my function.
function calcSquareWidth(nbSquares = 1) {
let width = $('#container').width(); //width of the container
let height = $('#container').height(); //height of the container
let surface = width * height; //surface of the container
let x = Math.sqrt( surface / nbSquares); //side of a square use the whole container
// To get the excess, I divide the container width and height by the side of a square and I get the integer part
let eWidth = Math.floor(width / x) * x; //width of the excess
let eHeight = Math.floor(height / x) * x; //height of the excess
let eSurface = eWidth * eHeight; //surface of the excess
return x - (Math.sqrt(surface - eSurface) / nbSquares);
}
That's the best result I have. But that's not perfect. Some squares can exit the container.
I have made some other experiment, but nothing to show here. I have made some tests with css but I didn't get there either.
If someone has an idea, I'm interested!
P.S : My English is not bad at all, but I have to learn more ! So, don't be shy to claim some details if needed.
Thanks !