简体   繁体   中英

How to maintain the aspect ratio while scaling the image on HTML5 Canvas?

In my project i'm using HTML5 Canvas and FabricJS. I have scenario to maintain the aspect ratio for the image object that i have placed in canvas. while adjusting corners or scaling the image i have to update width or height to maintain the aspect ratio for the image. 问题形象

The above image will clearly show my problem. i need an algorithm or formula to maintain the aspectratio of the image.

The image should meet the following,

  1. if i do shrinking by adjusting the width or height of the image from the actual size it will crop and display the picture in the same aspect ratio.
  2. if i do expand by adjusting the width or height of the image from the actual size it will expand the image height or width respectively and cropped for the viewport height and width to maintain the aspect ratio.
  3. the hidden parts are panned and viewed.

please give me some solution, thanks.

To ensure that resizing is done proportinatly, you can simply add the following properties to your image object:

lockUniScaling: true

I will typically want the image to scale from the center, and thus set this as well:

centeredScaling: true

To "crop" the image however; this takes more effort as this isn't a default functionality offered by Fabric JS. I've done a fair bit of work around this and have yet to come up with a bullet-proof solution that works for text, images, rectangles, polygons, circles, rotation angles, etc.

The basis behind this is to create two elements - one being your image, and the second being your clipping mask (a shape typically, such as a rectangle, polygon, etc.) than then is applied as the clipTo property to your image element. This solution is covered in: Multiple clipping areas on Fabric.js canvas

References - Fabric JS Documentation

As you're using HTML5, you could just apply a CSS3 transformation to the canvas with:

canvas {
    -ff-transform: scale(2); 
    -ms-transform: scale(2); 
    -webkit-transform: scale(2); 
}

Using the CSS3 transform property with the scale method should resize the canvas, and maintaining you're aspect ratio. It's also

You may, however, need to work around separate scaling issues caused by retina/high dpr displays.

More information about the CSS3 transform property can be found here: https://developer.mozilla.org/en-US/docs/Web/CSS/transform

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM