Home > Web Front-end > JS Tutorial > How to Resize Images Proportionally with jQuery: Maintaining Aspect Ratio?

How to Resize Images Proportionally with jQuery: Maintaining Aspect Ratio?

Barbara Streisand
Release: 2024-11-05 08:03:01
Original
997 people have browsed it

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>
Copy after login

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>
Copy after login

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!

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