以视口的特定比例缩放变量
Scaling a variable at a specific ratio of the viewport
当视口处于 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...
}
公式好像是
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
当视口处于 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...
}
公式好像是
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
的这个 polyfillMath.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