Home > Web Front-end > JS Tutorial > body text

How to implement adaptive scaling of JS web page images_javascript skills

WBOY
Release: 2016-05-16 17:03:43
Original
1407 people have browsed it

The user uploads a photo, and the size of the photo is unknown; a preview needs to be generated. This preview image must be applied according to the area provided to the user for preview and centered; if the image is too large, it needs to be scaled proportionally. As shown below.

How to implement adaptive scaling of JS web page images_javascript skills

Having a quick look, centering can be achieved using text-align:center;. However, proportional scaling cannot be solved by using the width and height attributes of the default . Because the user picture may be very long or very wide. I thought about their relationship online and judged it based on the conditions:

if(actual width > preview maximum width) {
Zoom width = preview maximum width
}

if(actual height> preview maximum height) {
Scaled height = preview maximum height
}
But there will be problems, such as when the width and height are both scaled, if the scaling is different, The image will not be scaled proportionally and will become very ugly. In order to make it scale proportionally, various judgments need to be made. Then this goes against the principle of automating the program we want. Thinking about it again, although I don’t like mathematics, mathematics is still very useful, and there should be other ways. And since it is scaled proportionally, why not use the ratio between the actual image and the width of the preview area to calculate their relationship? hmmmm... It's really OK. In fact we only ever need to scale either width or height. Because the ratio is only for large and small species. Specifically, write a function to implement it:

Copy the code The code is as follows:

/ **
* Image adaptive scaling
* @param img {Element} User uploaded image
* @param maxWidth {Number} Maximum width of the preview area
* @param maxHeight {Number} Preview The maximum height of the area
*/

var resizeImg = function(img, maxWidth, maxHeight){
var w = img.width,
h = img.height;

// When the picture does not make any changes than the preview area,
IF (w & lt; maxwidth && h & lt; maxheight) Return;

// When the actual picture ratio is greater than the width ratio of the preview area,
// Scaling picture width, otherwise the width of the zoom
w/h & gt; maxwidth/maxheight? Img.width = maxwidth: img.height = maxHeight;

Related labels:
js
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template