javiertoledos of Creative Science Labs
10/6/2016 - 9:16 PM

This function return an object of parameters where the image should be to fit inside the container. Typically used for image inside containe

This function return an object of parameters where the image should be to fit inside the container. Typically used for image inside containers but it works for any rectangle object inside another rectangle object. The returned object is formatted to a easy assignation to the function jQuery.style().

/* ****
 * @param {Object} params
 * @param {Number} params.containerWidth - The container's width
 * @param {Number} params.containerHeight - The container's height
 * @param {Number} params.imageWidth - The image's width
 * @param {Number} params.imageHeight - The image's height
 *
 * @returns {Object} returnObject
 * @returns {Number} returnObject.height - The resized height to fit in the container.
 * @returns {Number} returnObject.width - The resized width to fit in the container.
 * @returns {Number} returnObject.left - The left position to fit in the container
 * @returns {Number} returnObject.top - The rop position to fit in the container
 */
function imageInside(params){
    var returnO = {};
    var containerWidth  = params.containerWidth;
    var containerHeight = params.containerHeight;
    var imageWidth      = params.imageWidth;
    var imageHeight     = params.imageHeight;

    // new width, height, top and left
    var newWidth, newHeight, newTop, newLeft;

    newHeight = containerWidth * ( imageHeight / imageWidth );

    if( newHeight < containerHeight){
        newHeight   = containerHeight;
        newWidth    = containerHeight * ( imageWidth / imageHeight );
        newLeft     = (containerWidth - newWidth)/2;
        newTop      = 0;
    } else {
        newWidth    = containerWidth;
        newTop      = (containerHeight - newHeight)/2;
        newLeft     = 0;
    }

    returnO = {
        width   : newWidth,
        height  : newHeight,
        top     : newTop,
        left    : newLeft
    }

    return returnO;
}