Home > Article > Web Front-end > How to Resize Images Proportionally with jQuery: Maintaining Aspect Ratio?
Resizing Images Proportionally with jQuery: Preserving Aspect Ratio
jQuery's resizing capabilities come in handy when dealing with large images. To maintain image proportions while scaling, utilize the following approach:
Logic:
The calculateAspectRatioFit function employed here calculates new dimensions for the image based on the desired max width and height, effectively conserving the original aspect ratio.
Implementation:
<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>
Example Usage:
<code class="js">// Calculate and apply new dimensions to the image var newDimensions = calculateAspectRatioFit(originalWidth, originalHeight, maxWidth, maxHeight); $(imageSelector).width(newDimensions.width).height(newDimensions.height);</code>
By using this method, images can be proportionally scaled while maintaining their original shape and proportions.
The above is the detailed content of How to Resize Images Proportionally with jQuery: Maintaining Aspect Ratio?. For more information, please follow other related articles on the PHP Chinese website!