This article mainly introduces the implementation of proportional adaptive scaling for JS webpage images. If you need it, you can refer to the photos uploaded by users. The size of the photos is unknown. You need to generate a preview, this preview image is applied and centered based on the area provided for the user to preview. If the image is too large, it needs to be scaled proportionally. For example.
You can use text-align: center; to center. Proportional scaling cannot be solved by using the predefined width and height attributes. Because the user picture may be very long or wide. I thought about their relationship online and determined by the conditions as follows:
If (actual width> maximum preview width ){
Zoom width = preview max width
}
If (actual height> maximum preview height ){
Zoom Height = preview max height
}
However, this may cause problems. For example, if the width and height are scaled differently, the image will not be scaled proportionally and will become ugly. To scale it proportionally, you need to make various judgments. That violates the principle of program automation. Think about it. Although I do not like mathematics, it is still very useful. There should be other ways. Since it is proportional scaling, why not calculate the relationship between the actual image and the width of the preview area? Hmmmm... Sure enough. In fact, we always need to scale one of the widths or heights. Because the ratio is only large and small. Specifically, write a function to implement it:
The Code is as follows:
/**
* Proportional adaptive scaling of images
* @ Param img {Element} the image uploaded by the user
* @ Param maxWidth {Number} maximum width of the preview area
* @ Param maxHeight {Number} maximum height of the preview area
*/
Var resizeImg = function (img, maxWidth, maxHeight ){
Var w = img. width,
H = img. height;
// When the image is smaller than the preview area, no changes are made.
If (w <maxWidth & h <maxHeight) return;
// When the actual image proportion is greater than the preview area width proportion
// Scale the image width, and vice versa.
W/h> maxWidth/maxHeight? Img. width = maxWidth: img. height = maxHeight;