Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. problem 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.

like image 684
Pravinkumar Avatar asked Nov 12 '14 12:11

Pravinkumar


People also ask

How do you preserve aspect ratio when scaling images?

The Simple Solution Using CSSBy setting the width property to 100%, you are telling the image to take up all the horizontal space that is available. With the height property set to auto, your image's height changes proportionally with the width to ensure the aspect ratio is maintained.

How do you maintain aspect ratio in HTML?

In the HTML, put the player <iframe> in a <div> container. In the CSS for the <div>, add a percentage value for padding-bottom and set the position to relative, this will maintain the aspect ratio of the container. The value of the padding determines the aspect ratio. ie 56.25% = 16:9.


1 Answers

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

like image 56
PromInc Avatar answered Sep 22 '22 01:09

PromInc