Skip to content

Instantly share code, notes, and snippets.

@arturparkhisenko
Last active September 21, 2015 18:16
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 arturparkhisenko/7ff56c149324ffe6ef89 to your computer and use it in GitHub Desktop.
Save arturparkhisenko/7ff56c149324ffe6ef89 to your computer and use it in GitHub Desktop.
fitelement(something with aspect), script for rAF.js
var fitElement = function fitElement(elementSelector, elementAspect) {
var element = (typeof elementSelector === 'string' || elementSelector instanceof String) ? document.querySelector(elementSelector) : elementSelector,
parW = element.parentNode.clientWidth,
parH = element.parentNode.clientHeight,
parAsp = parW / parH,
aspect = elementAspect || 16 / 9,
elW, elH;
if (aspect > parAsp) {
elW = parW;
elH = elW / aspect;
} else {
elH = parH;
elW = elH * aspect;
}
//only if changed on frame
if (element.clientHeight !== parseInt(elH.toFixed())) {
element.style.height = elH.toFixed() + 'px';
}
if (element.clientWidth !== parseInt(elW.toFixed())) {
element.style.width = elW.toFixed() + 'px';
}
};
var elementObj = document.querySelector('.element-class');
(function animloop() {
fitElement(elementObj);
requestAnimationFrame(animloop);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment