How to keep aspect ratio when scaling an image on HTML5 canvas?

In my project, I use HTML5 Canvas and FabricJS. I have a script to maintain aspect ratio for an image object that I placed in the canvas. when adjusting the angles or scaling the image, I have to update the width or height to maintain the aspect ratio of the image. problem image

The above image will clearly show my problem. I need an algorithm or formula to preserve the aspect of the image.

The image should match the following,

  • If I shrink by adjusting the width or height of the image from the actual size, it will crop and display the image in the same format.
  • , , , .
  • .

, , .

+4
2

, :

lockUniScaling: true

, , , :

centeredScaling: true

"" , ; , , Fabric JS. , , , , , , ..

- , - (, , , ..), clipTo . : Fabric.js

- JS

+14

HTML5, CSS3 :

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

CSS3 .

, , / dpr.

CSS3 : https://developer.mozilla.org/en-US/docs/Web/CSS/transform

-4

All Articles