We often encounter examples of scaling with the width and length of the window varying, such as video cases in the middle of the video network, the box image scaling, and so on.

The formula

We already know that the formula for the length and width according to the ratio is:

Find the width w = h/ratio

Find the height h is equal to w times ratio

To prepare

So what we’re going to do, according to the formula, is we’re going to have an external container dom and a container DOM that we’re going to scale in proportion

The core code

if (w > wrapW) {
  cW = wrapW;
  cH = wrapW * ratio;
}
if (h > wrapH) {
  cW = wrapH / ratio;
  cH = wrapH;
}
Copy the code

In the above code, wrapW and wrapH are external containers, while cW and cH are containers to be regulated by proportion. First, we need to calculate the scaling width in one direction to determine whether it is beyond the outer container. If it is not, then it means that the scaling is in the outer container. If it is, then the calculation is reversed.

The source code

@param width * @param height * @param minWidth * @param minHeight * @param minHeight * @param minHeight * @param maxWidth * @param maxHeight * @returns {{residueH: number, residueW: number, width: number, height: number}} */ function computeBox({ width, height, minWidth, minHeight, maxWidth, maxHeight }) { minWidth = minWidth === void 0 ? 0 : Math.max(0, minWidth); minHeight = minHeight === void 0 ? 0 : Math.max(0, minHeight); maxWidth = maxWidth === 'none' ? width : Math.max(minWidth, maxWidth); maxHeight = maxHeight === 'none' ? height : Math.max(minHeight, maxHeight); // w = h / ratio, h = w * ratio const ratio = height / width; if (width < minWidth) { width = minWidth; height = minWidth * ratio; } if (height < minHeight) { width = minHeight / ratio; height = minHeight; } if (width > maxWidth) { width = maxWidth; height = maxWidth * ratio; } if (height > maxHeight) { width = maxHeight / ratio; height = maxHeight; } const length = Math.pow(10, 5); width = Math.round((width * length)) / length; height = Math.round((height * length)) / length; return { width: width, height: height, residueW: maxWidth - width, residueH: maxHeight - height }; }; Const box = computeBox({width: 1920, // cw height: 1080, // cH maxWidth: 500, // wrapW maxHeight: 500 // wrapH }); // => {{ width: number, height: number, residueW: number, residueH: number }}Copy the code

Running effect diagram

widescreen

The kaoping river

Square screen

* Copyright notice: This article is an original article, shall not be reproduced without permission.