Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to auto scale big image with aspect ratio on canvas using fabric js

I have added an image to a FabricJS canvas. If the image is too big then it goes to outside of the canvas. I want to fit the image within the canvas without losing the aspect ratio of the image.

fabric.Image.fromURL(image_url, function(img) {
  var oImg = img.set({ left: 0, top: 0 }).scale(1);
  fabricCanvas.add(oImg).setActiveObject(oImg);        
}, {
  crossOrigin: "anonymous"
});
like image 771
Pavan Hukerikar Avatar asked Jan 22 '26 02:01

Pavan Hukerikar


1 Answers

Scale image in canvas I assume cw as canvas width and ch as canvas height, you can scale your image as you need,

fabric.Image.fromURL(imgURL, function(img) {
  var oImg = img.set({ left: 0, top: 0 }).scale(1);
  oImg.scaleToWidth(cw/2);
  oImg.scaleToHeight(ch/2);
  canvas.add(oImg).setActiveObject(oImg);        
}, {
  crossOrigin: "anonymous"
});
like image 71
AJAY MAURYA Avatar answered Jan 23 '26 19:01

AJAY MAURYA