Home > Article > Web Front-end > 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>
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>
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!