daveycroqet - 2 months ago 16

Javascript Question

When the viewport is at a 1:1 width-to-height ratio (e.g. 1000x1000 resolution), I want a variable to be set to 0.22.

When the viewport is at a 2:1 width-to-height ratio (e.g. 2000x1000 resolution), I want that variable to be 0.33.

This should **scale smoothly** both up and down to any resolution (e.g. 500x1000 is 0.11; 4000x1000 is 0.55, etc.) after a resize event. How could I go about accomplishing this?

`window.addEventListener('resize', scaleViewport);`

function scaleViewport() {

w = window.innerWidth;

h = window.innerHeight;

// ...no idea how to write this formula...

}

Answer Source

The formula seems to be

```
0.11 * (2 + Math.log2(w/h))
```

Internet Exploder does not have Math.log2

So, you'll need this polyfill from MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log2#Polyfill

```
Math.log2 = Math.log2 || function(x) {
return Math.log(x) * Math.LOG2E;
};
```

```
const formula = (w, h) => .11 * (2 + Math.log2(w/h));
console.log(formula(1000, 1000)); // should be 0.22
console.log(formula(2000, 1000)); // should be 0.33
console.log(formula(500, 1000)); // should be 0.11
// unfortunately that's where this formula ends being right
console.log(formula(3000, 1000)); // should be 0.44
console.log(formula(4000, 1000)); // should be 0.55
```

Given the new information about what 3000:1000 and 4000:1000 should be

```
const formula = (w,h) => {
if (w/h < 1) {
return w/h * 0.22;
} else {
return (w/h + 1) * 0.11;
}
};
console.log(formula(1000, 1000)); // should be 0.22
console.log(formula(2000, 1000)); // should be 0.33
console.log(formula(500, 1000)); // should be 0.11
console.log(formula(3000, 1000)); // should be 0.44
console.log(formula(4000, 1000)); // should be 0.55
```