Skip to content

Instantly share code, notes, and snippets.

@krizpoon
Last active August 29, 2015 14:07
Show Gist options
  • Save krizpoon/f34faf6c2ae88a6cac76 to your computer and use it in GitHub Desktop.
Save krizpoon/f34faf6c2ae88a6cac76 to your computer and use it in GitHub Desktop.
Javascript Image Utils
function TSCenterImage(img)
{
if (!img || !img.offsetParent) 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.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