Created
March 29, 2017 01:44
-
-
Save mitchellbutler/2aa155daf4b92b75983ae9a1c2ddaf54 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
// Choose the area constraint. | |
// Here the image can't occupy more than 20% of its container. | |
const maxArea = container.width * container.height * 0.2; | |
// Choose the height and width constraints. | |
// In this case the container minus 20px on each side for padding. | |
const maxWidth = container.width - 20 * 2; | |
const maxHeight = container.height - 20 * 2; | |
// Get the native aspect ratio of the image. | |
const aspectRatio = image.width / image.height; | |
// Get the height and width that the image will be resized to | |
// assuming that it will be constrained by area. | |
let newHeight = Math.sqrt(A / R); | |
let newWidth = areaHeight * R; | |
// Compare the area height and widths to the maximums. | |
const diffWidth = areaWidth - maxWidth; | |
const diffHeight = areaHeight - maxHeight; | |
// Decide if the max height and width constraints outweigh | |
// the area constraint, if so then recalculate the dimensions. | |
if (diffWidth >= diffHeight and diffWidth > 0) { | |
newWidth = maxWidth; | |
newHeight = newWidth / R; | |
} else if (diffHeight > 0) { | |
newHeight = maxHeight; | |
newWidth = newHeight * R; | |
} | |
// Position and center the image at the calculated size. | |
image.left = (container.width - newWidth) / 2; | |
image.top = (container.height - newHeight) / 2; | |
image.height = newHeight; | |
image.width = newWidth; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment