0

I've got an application which displays a webpage in a frame. This frame is supposed to be 1280x720 pixels, but sometimes it renders as 1280x719 or 1281x720. Now i've found this script to calculate a ratio based on any given width and height:

function gcd (a, b) { 
    return (b == 0) ? a : gcd (b, a%b);
}

This works perfectly fine when the viewport is exactly 1280x720 pixels, but when the viewport is 1280x719 or 1281x720, it returns 1280:719 or 1281:720 as the aspect ratio.

What I would like the script to do is to still return 16:9.

I've thought of using an array with some default aspect ratios (16:9, 4:3, ...). This way the array could be checked for every margin difference untill a result is found. I just don't know how I can check for each of these margin values in a fast way. Hopefully anyone in here can help me achieve the above.

ev8
  • 83
  • 9

1 Answers1

-1

I actually just found the following post: Show correct aspect ratio

I converted the PHP script to javascript and came up with the following solution:

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;
}

This seems to work!

Community
  • 1
  • 1
ev8
  • 83
  • 9