2

I am trying to make a webpage that resizes based on the size of the window and the code below seems to be the solution.

var scale = Math.min( availableWidth / contentWidth, availableHeight / contentHeight );

Could Somebody Tell me why this works and what exactly are we doing with this?

Plz refer this for More Info.

1
  • You would need to give more context than this. Commented Jan 11, 2022 at 18:39

2 Answers 2

3

The code you posted is taking the percentage ratio between the width of a certain component and the width of the whole page and the height of the same component with the height of the whole page, but it only gets the smaller proportion between the two calculated to consider whether the page is in landscape or portrait layout.

Apparently this number resulting from this line you posted is to be used for you to be able to calculate the value you want to get given the change in the default screen you used to draw. Assuming the canvas you are drawing the default layout on is 1024px by 768px, we would do it like this:

var scale = Math.min(
    availableWidth /   /*1024px*/
    contentWidth,      /*500px => (100 / 2048) = 48.82% of available height */
    availableHeight /  /*768px/*
    contentHeight      /*145px (100 / 5.2965) = 19.02% of available height*/
);

In this case your line would bring 19.02%, because the Math.min method brings the smallest of the array. So you would use the height of this object as a reference to determine its width too, in order to try to maintain the aspect ratio of the page. But the ideal thing, in my opinion, is that you learn to deal with flex layout, maybe even with bootstrap, to build responsive grids with less work, since the CSS will scale for you according to the screen size natively , without the need for calculations. ;D

Sign up to request clarification or add additional context in comments.

Comments

2

I think this code is trying calculate the scale proportion that it should adjust the content based on the different window.size.

For example, you design the website at the window of size 1600* 960px , but some of the content could not fully showed when you go to a window at 300*200, so you need to have a proportion to scale to make the content could be shown in the right style

The availableHeight and availableWidth is the size of the window. The contentWidth and contentHeight is the size of a specific content (div in the doc)

You divide the size of window to the size of content and get the smaller one of them using Math.min() will make sure you use the most space of the window, but won't make the content oversize or doesn't follow the effect you want.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.