Skip to content

Instantly share code, notes, and snippets.

@MartinSvarrer
Last active December 24, 2015 10:29
Show Gist options
  • Save MartinSvarrer/6784824 to your computer and use it in GitHub Desktop.
Save MartinSvarrer/6784824 to your computer and use it in GitHub Desktop.
Calculate sizes for one object to fit another and top/left info for alignment. Usage: var sizeObj = fit( 3000, 3500, $('.box').width(), $('.box').height(), { cover: false, align: 'middle center' }); Returns an object like: {scale: 1.2, width: 120, height: 120, top: -10, left: 0 }; Takes two optional params: cover, and align. It works without JQu…
function fit (targetWidth, targetHeight, containerWidth, containerHeight, options) {
var settings = {
cover: options && options.cover !== undefined ? options.cover : true,
align: options && options.align !== undefined ? options.align : 'center middle'
}
var ratioWidth = containerWidth / targetWidth,
ratioHeight = containerHeight / targetHeight,
ratioTarget = targetWidth / targetHeight,
ratioContainer = containerWidth / containerHeight;
var scaleRatioHorizontally = settings.cover ? ratioHeight : ratioWidth,
scaleRatioVertically = settings.cover ? ratioWidth : ratioHeight;
var s = ratioTarget >= ratioContainer ? scaleRatioHorizontally : scaleRatioVertically,
w = Math.round(targetWidth * s),
h = Math.round(targetHeight * s);
var left = 0.0,
top = 0.0;
if (settings.align.indexOf('center') !== -1)
left = Math.round(0.5 * (containerWidth - w));
else if (settings.align.indexOf('right') !== -1)
left = containerWidth - w;
if (settings.align.indexOf('middle') !== -1)
top = Math.round(0.5 * (containerHeight - h));
else if (settings.align.indexOf('bottom') !== -1)
top = containerHeight - h;
return { top: top, left: left, scale: s, width: w, height: h };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment