Skip to content

Instantly share code, notes, and snippets.

@FreddyFY
Last active October 23, 2018 12:25
Show Gist options
  • Save FreddyFY/3e04da42e79fd7adad5165dd84bb993b to your computer and use it in GitHub Desktop.
Save FreddyFY/3e04da42e79fd7adad5165dd84bb993b to your computer and use it in GitHub Desktop.
Animating to/from backgroundSize: "contain" or "cover"
/**
* Source: from: https://greensock.com/forums/topic/18144-animating-tofrom-backgroundsize-contain-or-cover/
*/
//this function converts the backgroundSize of an element from "cover" or "contain" or "auto" into px-based dimensions. To set it immediately, pass true as the 2nd parameter.
function getBGSize (element, setInPx) {
var e = (typeof(element) === "string") ? document.querySelector(element) : element,
cs = window.getComputedStyle(e),
imageUrl = cs.backgroundImage,
size = cs.backgroundSize,
image, w, h, iw, ih, ew, eh, ratio;
if (imageUrl && !/\d/g.test(size)) {
image = new Image();
image.setAttribute("src", imageUrl.replace(/(^url\("|^url\('|^url\(|"\)$|'\)$|\)$)/gi, "")); //remove any url() wrapper. Note: some browsers include quotes, some don't.
iw = image.naturalWidth;
ih = image.naturalHeight;
ratio = iw / ih;
ew = e.offsetWidth;
eh = e.offsetHeight;
if (!iw || !ih) {
console.log("getBGSize() failed; image hasn't loaded yet.");
}
if (size === "cover" || size === "contain") {
if ((size === "cover") === (iw / ew > ih / eh)) {
h = eh;
w = eh * ratio;
} else {
w = ew;
h = ew / ratio;
}
} else { //"auto"
w = iw;
h = ih;
}
size = Math.ceil(w) + "px " + Math.ceil(h) + "px";
if (setInPx) {
e.style.backgroundSize = size;
}
}
return size;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment