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

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

Barbara Streisand
Barbara StreisandOriginal
2024-11-05 08:03:01763browse

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!

Statement:
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