math/algorithm Fit image to screen retain aspect r

2019-01-10 06:36发布

问题:

I understand the accepted answer and it works, but I've always found the following method to be simpler and succinct for "best fit":

// prep
let maxWidth = 190,
    maxHeight = 150;
let imgWidth = photo.width,
    imgHeight = photo.height;

// calc
let widthRatio = maxWidth / imgWidth,
    heightRatio = maxHeight / imgHeight;
let bestRatio = Math.min(widthRatio, heightRatio);

// output
let newWidth = imgWidth * bestRatio,
    newHeight = imgHeight * bestRatio;