按视口

时间:2017-08-28 00:33:24

标签: javascript math formula

当视口的宽高比为1:1(例如1000x1000分辨率)时,我希望将变量设置为0.22。

当视口的宽高比为2:1(例如2000x1000分辨率)时,我希望该变量为0.33。

在调整大小事件后,这应该平滑地向上和向下扩展到任何分辨率(例如500x1000是0.11; 4000x1000是0.55等)。我怎么能完成这个?

window.addEventListener('resize', scaleViewport);

function scaleViewport() {
    w = window.innerWidth;
    h = window.innerHeight;

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

1 个答案:

答案 0 :(得分:4)

公式似乎是

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

Internet Exploder没有Math.log2

因此,您需要来自MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log2#Polyfill

的此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

鉴于有关3000:1000和4000:1000应该

的新信息

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