Skip to content

Instantly share code, notes, and snippets.

@KrofDrakula
Last active August 7, 2018 23:25
Show Gist options
  • Save KrofDrakula/16a8a9e1106aa6408866 to your computer and use it in GitHub Desktop.
Save KrofDrakula/16a8a9e1106aa6408866 to your computer and use it in GitHub Desktop.
// shorter vars for brevity
var a = image.naturalWidth,
b = image.naturalHeight,
c = maxImageWidth,
d = maxImageHeight,
r1 = a / b, // image aspect ratio
r2 = c / d; // container aspect ratio
// determine which dimension is the limiting factor
// according to the aspect ratio comparison and
// calculate the scale ratio
var s = (r1 > r2) ? a / c : b / d;
// calculated the scaled dimensions
var w = a / s;
var h = b / s;
// position the image
imageStyle.marginLeft = -Math.round(w / 2) + 'px';
imageStyle.marginRight = -Math.round(h / 2) + 'px';
imageStyle.left = imageStyle.top = '50%';
imageStyle.width = Math.round(w) + 'px';
imageStyle.height = Math.round(h) + 'px';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment