Skip to content

Instantly share code, notes, and snippets.

@weihanglo
Created July 13, 2017 07:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save weihanglo/f7faca965af8055161c765a4f911cf33 to your computer and use it in GitHub Desktop.
Save weihanglo/f7faca965af8055161c765a4f911cf33 to your computer and use it in GitHub Desktop.
Calculate the rendered rect of img content (useful with object-fit: contain)
/**
* 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