Skip to content

Instantly share code, notes, and snippets.

@kribblo
Last active September 25, 2016 20:08
Show Gist options
  • Save kribblo/9efe3d2e8ea129ee3aac55f343c2f767 to your computer and use it in GitHub Desktop.
Save kribblo/9efe3d2e8ea129ee3aac55f343c2f767 to your computer and use it in GitHub Desktop.
Helper to fit a given size into another, preserving aspect ratio
'use strict';
/**
* @exports sizeFactory
* @private
*
* @param {{width: number, height: number}} size
* @returns {sizeHelper}
*/
function sizeFactory(size) {
var ratio = size.width / size.height;
/**
* Helpers for fitting a game into a specific size.
* This is used for the property 'size' on the object returned from a nolimit.info() call.
* @exports sizeHelper
*/
var sizeHelper = {
width: size.width,
height: size.height,
ratio: ratio,
/**
* Given a width and height, return a new size that fits into that and preserves the orginal aspect ratio.
*
* @param width
* @param height
* @returns {sizeHelper} The new size object
*
*/
fit: function(width, height) {
return width / height < ratio ? this.fitWidth(width) : this.fitHeight(height);
},
/**
* Given a width only, return a new size that fits into that and preserves the orginal aspect ratio.
*
* @param width
* @returns {sizeHelper} The new size object
*/
fitWidth: function(width) {
return sizeFactory({
width: width,
height: Math.round(width / ratio)
});
},
/**
* Given a height only, return a new size that fits into that and preserves the orginal aspect ratio.
*
* @param height
* @returns {sizeHelper} The new size object
*/
fitHeight: function(height) {
return sizeFactory({
width: Math.round(height * ratio),
height: height
});
}
};
return sizeHelper;
}
module.exports = sizeFactory;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment