The size of the photo you upload is unknown. You need to generate a preview. This preview is applied and centered based on the area provided for the preview. If the picture is too large, proportional scaling is required, as shown in.
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:
The Code is 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;
};
Complete Test code:
The Code is as follows:
Proportional adaptive scaling of images
View the original image | returns an article about proportional adaptive scaling of the image»
Script
Window. onload = function (){
Var img = document. getElementById ('img '),
/**
* 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
*/
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;
};
ResizeImg (img, 500,300 );
}
Script