Skip to content

Instantly share code, notes, and snippets.

@TomckySan
Created May 11, 2014 13:53
Show Gist options
  • Save TomckySan/6a0062a34678aa839bcd to your computer and use it in GitHub Desktop.
Save TomckySan/6a0062a34678aa839bcd to your computer and use it in GitHub Desktop.
var adjustAspectRatio = function (rectObj, wRetio, hRetio) {
if ((typeof rectObj.width === 'undefined' || rectObj.width === null)
|| (typeof rectObj.height === 'undefined' || rectObj.height === null)) {
console.error('Error : Object is not rect!');
return;
}
if (rectObj.width > rectObj.height * wRetio / hRetio) {
rectObj.width = rectObj.height * wRetio / hRetio;
}
else if (rectObj.height > rectObj.width * hRetio / wRetio) {
rectObj.height = rectObj.width * hRetio / wRetio
}
return rectObj;
};
// --------
// TestCode
// --------
var aspectWidth = 64, aspectHeight = 39;
var rectOverWidth = { width: 1000, height: 390 };
var rectOverHeight = { width: 640, height: 640 };
var rectError = { hoge: '', foo: '' };
var rectNoneWidth = { height: 100 };
var rectNoneHeight = { width: 100 };
console.log(adjustAspectRatio(rectOverWidth, aspectWidth, aspectHeight)); // {width:640, heigt:390}
console.log(adjustAspectRatio(rectOverHeight, aspectWidth, aspectHeight)); // {width:640, heigt:390}
console.log(adjustAspectRatio(rectError, aspectWidth, aspectHeight)); // 'Error : Object is not rect!'
console.log(adjustAspectRatio(rectNoneWidth, aspectWidth, aspectHeight)); // 'Error : Object is not rect!'
console.log(adjustAspectRatio(rectNoneHeight, aspectWidth, aspectHeight)); // 'Error : Object is not rect!'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment