Skip to content

Instantly share code, notes, and snippets.

@renarsvilnis
Last active May 31, 2017 09:05
Show Gist options
  • Save renarsvilnis/9be523e88716ea9e5e35e9cb6a62bbca to your computer and use it in GitHub Desktop.
Save renarsvilnis/9be523e88716ea9e5e35e9cb6a62bbca to your computer and use it in GitHub Desktop.
Helper functions for calculating fit, fill dimensions of an image, rect,.. in JavaScript
export function calcFitDimensions (target, boundries, upscale = false) {
if (!target.width || !target.height || !boundries.width || !boundries.height) {
return calcCenterPosition(target, boundries);
}
let imgRatio = target.width / target.height;
let newWidth;
let newHeight;
// if image is horizontal
if (imgRatio > 1) {
newWidth = upscale
? Math.max(target.width, boundries.width)
: Math.min(target.width, boundries.width);
newHeight = newWidth / imgRatio;
// maybe needed
if (newWidth > boundries.width) {
newWidth = target.width > boundries.width ? boundries.width : target.width;
newHeight = newWidth / imgRatio;
}
// if image is vertical
} else {
newHeight = upscale
? Math.min(target.height, boundries.height)
: Math.min(target.height, boundries.height);
newWidth = newHeight * imgRatio;
}
if (newWidth > boundries.width) {
newWidth = boundries.width;
newHeight = newWidth / imgRatio;
}
if (newHeight > boundries.height) {
newHeight = boundries.height;
newWidth = newHeight * imgRatio;
}
return calcCenterPosition({
width: newWidth,
height: newHeight
}, boundries);
}
/**
* Calc fill dimension of an image within a given boundry. May upscale the image
* the image if needed
*
* @param {Object} target
* @param {Object} boundries
* @param {Boolean} [upscale=false]
*/
export function calcFillDimensions (target, boundries) {
if (!target.width || !target.height || !boundries.width || !boundries.height) {
return calcCenterPosition(target, boundries);
}
const targetRatio = target.width / target.height;
let newWidth;
let newHeight;
// if image is horizontal
if (targetRatio > 1) {
newHeight = Math.max(target.height, boundries.height);
newWidth = newHeight * targetRatio;
} else {
newWidth = Math.max(target.width, boundries.width);
newHeight = newWidth / targetRatio;
}
return calcCenterPosition({
width: newWidth,
height: newHeight
}, boundries);
}
/**
* Calculate center position of an target within a boundry
* @param {Object} target
* @param {Object} boundries
* @return {Object}
*/
function calcCenterPosition (target, boundries) {
return {
top: (boundries.height - target.height) / 2,
left: (boundries.width - target.width) / 2,
width: target.width,
height: target.height
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment