Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/428.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript JS:使用X像素的边距获取纵横比_Javascript_Height_Width_Margin_Aspect Ratio - Fatal编程技术网

Javascript JS:使用X像素的边距获取纵横比

Javascript JS:使用X像素的边距获取纵横比,javascript,height,width,margin,aspect-ratio,Javascript,Height,Width,Margin,Aspect Ratio,我有一个应用程序,它在一个框架中显示一个网页。此帧应为1280x720像素,但有时渲染为1280x719或1281x720。现在我发现这个脚本可以根据任何给定的宽度和高度计算一个比率: function gcd (a, b) { return (b == 0) ? a : gcd (b, a%b); } 当视口正好为1280x720像素时,此操作非常有效,但当视口为1280x719或1281x720时,它返回1280:719或1281:720作为纵横比 我希望脚本仍然返回16:9 我

我有一个应用程序,它在一个框架中显示一个网页。此帧应为1280x720像素,但有时渲染为1280x719或1281x720。现在我发现这个脚本可以根据任何给定的宽度和高度计算一个比率:

function gcd (a, b) { 
    return (b == 0) ? a : gcd (b, a%b);
}
当视口正好为1280x720像素时,此操作非常有效,但当视口为1280x719或1281x720时,它返回1280:719或1281:720作为纵横比

我希望脚本仍然返回16:9


我曾经考虑过使用一个默认纵横比为16:9、4:3的数组。。。。通过这种方式,可以检查阵列的每一个边距差异,直到找到结果为止。我只是不知道如何快速检查每一个边距值。希望这里的任何人都能帮助我实现上述目标。

我实际上刚刚找到了以下帖子:

我将PHP脚本转换为javascript,并提出了以下解决方案:

function findBestMatch(numerator, denominator) {
    commonRatios = [
        [1, '1:1'], [(4 / 3), '4:3'], [(3 / 2), '3:2'],
        [(5 / 3), '5:3'], [(16 / 9), '16:9'], [3, '3']
    ];

    value = numerator / denominator;

    end = (commonRatios.length - 1);
    for (i = 0; i < end; i++) {
        if (value == commonRatios[i][0]) {
            // we have an equal-ratio; no need to check anything else!
            return commonRatios[i][1];
        } else if (value < commonRatios[i][0]) {
            // this can only happen if the ratio is `< 1`
            return commonRatios[i][1];
        } else if ((value > commonRatios[i][0]) && (value < commonRatios[i + 1][0])) {
            // the ratio is in-between the current common-ratio and the next in the list
            // find whichever one it's closer-to and return that one.
            return ((value - commonRatios[i][0]) < (commonRatios[i + 1][0] - value)) ? commonRatios[i][1] : commonRatios[i + 1][1];
        }
    }

    // we didn't find a match; that means we have a ratio higher than our biggest common one
    // return the original value
    return ratio;
}
这似乎有效