简体   繁体   中英

Programmatically calculate width and height given area and ratio in JavaScript

OK, so I need to create an "auto fit" feature when a button is clicked.

Pretend you have an area, which is variable in size due to the responsive nature of the page.

This area can contain a number of rectangles (specified by how many logged in clients there are).

What I need to calculate, programmatically in JavaScript, is the appropriate width and height of each client in order to "fit" them all within that area.

var area = $('.client-container').width() * $('.client-container').height();
var noOfClients = 3; // normally calculated dynamically

// Ratio (1.25:1)
var r1 = 1.25;
var r2 = 1;

How can I work out what width and height I should apply to each client rectangle?

I assume you have full freedom to resize the N clients and that their natural aspect ratio can simply reflect that of the screen. You won't always be able to make all clients the same size without wasting space. Take the square root of N, round it down, and that's your number of rows R. It's also your number of columns except that X=NR*R clients don't fit. X is less than R. Just choose the bottom X rows and divide them into R+1 columns instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM