Skip to content

Instantly share code, notes, and snippets.

@krizpoon
Last active August 29, 2015 14:19
Show Gist options
  • Save krizpoon/33316758701c7fec7fac to your computer and use it in GitHub Desktop.
Save krizpoon/33316758701c7fec7fac to your computer and use it in GitHub Desktop.
Image Utils
function TSFitImage(img)
{
if (!img) return;
// get the basic metrics
var iw = img.naturalWidth, ih = img.naturalHeight, ww = img.offsetParent.offsetWidth, wh = img.offsetParent.offsetHeight;
if (!iw || !ih || !ww || !wh) return;
// calculate the scale by fitting image to align container's width and height
var sw = ww/iw, sh = wh/ih;
// calculate scaled image width / height under the above scales
var sih = ih * sw, siw = iw * sh;
var x=0,y=0,w=ww,h=wh;
if (sih < wh)
{
// if scaled image height fits inside the container:
h = sih;
y = (wh - h)/2;
}
else
{
// if scaled image width fits inside the container:
w = siw;
x = (ww - w) / 2;
}
img.style.position = 'relative';
img.style.left = x + 'px';
img.style.top = y + 'px';
img.style.width = w + 'px';
img.style.height = h + 'px';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment