Reputation: 319
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,
please give me some solution, thanks.
Upvotes: 6
Views: 6757
Reputation: 1233
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
Upvotes: 16
Reputation: 4329
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
Upvotes: -5