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

How to Resize Images Proportionally with jQuery?

Mary-Kate Olsen
Release: 2024-11-04 07:34:30
Original
754 people have browsed it

How to Resize Images Proportionally with jQuery?

Preserving Image Proportions with jQuery

Resizing images proportionally is crucial to maintain their visual integrity. jQuery offers a straightforward solution to scale images while preserving their aspect ratio.

How to Calculate Proportional Dimensions

The following function determines the appropriate width and height for the resized image:

<code class="js">function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {

    var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);

    return { width: srcWidth*ratio, height: srcHeight*ratio };
 }</code>
Copy after login

This function accepts the original image dimensions (srcWidth, srcHeight) and the maximum available width and height (maxWidth, maxHeight) as parameters. It calculates the minimum ratio between the original and maximum dimensions to preserve the aspect ratio. The new width and height are then determined by multiplying the original values by this ratio.

Applying the Logic with jQuery

Once you have calculated the new dimensions, you can use jQuery to resize the image:

<code class="js">var newDimensions = calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight);

$("img").width(newDimensions.width);
$("img").height(newDimensions.height);</code>
Copy after login

This code dynamically sets the width and height attributes of the selected image element to the calculated values.

The above is the detailed content of How to Resize Images Proportionally with jQuery?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template