Created
July 13, 2017 07:08
-
-
Save weihanglo/f7faca965af8055161c765a4f911cf33 to your computer and use it in GitHub Desktop.
Calculate the rendered rect of img content (useful with object-fit: contain)
This file contains 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
/** | |
* Calculate the rendered rect of img content (useful with object-fit: contain) | |
* @param {HTMLImageElement} img | |
* @return {object} rect of the object (the coordinate origin is top-left). | |
*/ | |
export function getRenderedRect (img) { | |
const style = window.getComputedStyle(img) | |
const pos = style.getPropertyValue('object-position').split(' ') | |
const contains = style.getPropertyValue('object-fit') === 'contain' | |
const ratio = { | |
intrinsic: img.naturalWidth / img.naturalHeight, | |
element: img.width / img.height | |
} | |
const rect = { width: img.width, height: img.height } | |
const isElementRatioHigher = ratio.element > ratio.intrinsic | |
if (contains ? isElementRatioHigher : !isElementRatioHigher) { | |
rect.width = img.height * ratio.intrinsic | |
} else { | |
rect.height = img.width / ratio.intrinsic | |
} | |
rect.left = (img.width - rect.width) * parseFloat(pos[0]) / 100 | |
rect.right = rect.left + rect.width | |
rect.top = (img.height - rect.height) * parseFloat(pos[1]) / 100 | |
rect.bottom = rect.top + rect.height | |
return rect | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment