-
-
Save oguzhanaslan/984ba81defd8a7d8252c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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