Tuesday, February 9, 2016

JavaScript to get Aspect Ratio

The following is just a simple calclator for gaining Aspect Ratio.

This will allow you to find 4th value if needed, or simply tell you what the aspect ratio between two sets of measurements is, provided they match. An AR of 4/3 isn't going to match 9/7, thus you'd get a false return. In this way, you can check that an Aspect Ratio was adjusted correctly.

Easy Uses!

  • aspectRatioHD({ "height": 600, "width": 800 }, { "height": 1200 }); // would return 1600, which would be your new "width"
  • aspectRatioHD({ "height": 600, "width": 800 }, { "width": 1600 }); // would return 1200, which would be your new "height"
  • aspectRatioHD({ "height": 600 }, { "height": 1200, "width": 1600 }); // would return 800, which would be your new "width"
  • aspectRatioHD({ "width": 800 }, { "height": 1200, "width": 1600 }); // would return 600, which would be your new "height"
  • aspectRatioHD({ "height": 600, "width": 800 }, { "height": 1200, "width": 1600 }); // would return [4,3], The spect Ratio in Array Format being [W,H]
  • aspectRatioHD({ "height": 600, "width": 800 }, { "height": 1200, "width": 1600 }); // would return [4,3], The spect Ratio in Array Format being [W,H]
  • aspectRatioHD({ "height": 3, "width": 4 }, { "height": 7, "width": 9 }); // would return false, since these 2 aspect ratios do not match

Code

function aspectRatioHD(){if(2==arguments.length){var d=function(a){a=parseFloat((""+a).replace(/[^0-9.]/g,""));return a==a?a:void 0},a=function(a){var b={},c;for(c in a)if(a.hasOwnProperty(c))switch(c.toLowerCase()){case "height":b.h=d(a[c]);break;case "width":b.w=d(a[c])}if("number"!=typeof b.h||b.h!=b.h)b.h=void 0;if("number"!=typeof b.w||b.w!=b.w)b.w=void 0;return b},b=a(arguments[0]),a=a(arguments[1]);if(b.w&&b.h&&a.w&&a.h)return Math.round(a.w/a.h*100)/100==Math.round(b.w/b.h*100)/100?(b=function e(a,
b){return b?e(b,a%b):a},b=b(a.w,a.h),[a.w/b,a.h/b]):a.w/a.h==b.w/b.h;if(b.w&&b.h&&!a.w&&a.h)return Math.round(b.w/b.h*a.h);if(b.w&&b.h&&a.w&&!a.h)return Math.round(a.w/(b.w/b.h));if(!b.w&&b.h&&a.w&&a.h)return Math.round(a.w/a.h*b.h);if(b.w&&!b.h&&a.w&&a.h)return Math.round(b.w/(a.w/a.h))}else throw Error("Invalid Amount of Arguments. Must have 2 arguments such as: [{height:1,width:2},{height:3}]");};

Go play with it here!

Or see the Result below

No comments:

Post a Comment