Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fabric Js - Is it possible to auto scale a image object to the canvas?

We currently upload an image via the below code:

        reader.onload = function (event) {
            fabric.Image.fromURL(event.target.result, function (img) {
                whiteboardService.uploadImageToCanvas(img);
            });
        }

and...

    service.uploadImageToCanvas = function (image) {
        service.canvas.add(image);

        image.id = service.getUniqueId();
        service.objectMap[image.id] = image;

        var data = {
            image: image,
            id: image.id
        };

        signalService.sendMessage(service.recipient, data);
    };

If the image is too large, bigger than our fixed width and height of the canvas would it be possible for that image to be scaled down automatically to fit into the fixed width and height of the canvas?

I should point out that I am using Angular.js as well

ta

like image 857
Max Lynn Avatar asked Feb 16 '16 16:02

Max Lynn


2 Answers

fabricjs put a very simple method to do this. Those methods are scaleToWidth and scaleToHeight that are close to 'apply a scale factor that will fit the image on the specified dimensions'

So you can do

image.scaleToWidth(service.canvas.getWidth());
service.canvas.add(image);

it depends if you want to preserve aspect ratio if you have to scale for the biggest, the smallest or both.

like image 93
AndreaBogazzi Avatar answered Nov 01 '22 19:11

AndreaBogazzi


Inspired by @AndreaBogazzi, I wrote below code to fit image to canvas totally.

var canvas = new fabric.Canvas('canvas');
fabric.Image.fromURL('https://d32ogoqmya1dw8.cloudfront.net/images/NAGTWorkshops/structure/SGT2012/activities/noaa_global_topographic_map.jpg', function(oImg) {
  let imgWidth = oImg.width;
  let imgHeight = oImg.height;
  let canvasWidth = canvas.getWidth();
  let canvasHeight = canvas.getHeight();

  let imgRatio = imgWidth / imgHeight;
  let canvasRatio = canvasWidth / canvasHeight;
  if(imgRatio <= canvasRatio){
    if(imgHeight> canvasHeight){
      oImg.scaleToHeight(canvasHeight);
    }
  }else{
    if(imgWidth> canvasWidth){
      oImg.scaleToWidth(canvasWidth);
    }
  }

  canvas.clear();
  canvas.add(oImg);
  canvas.centerObject(oImg);
});
.image-preview{
    border: solid 1px #979797;
    width: 200px;
    height: 200px;
}
<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.3.1/fabric.min.js"></script>
<div class="image-preview">
  <canvas id="canvas" width='200' height='200'></canvas>
  
  <hr/>
  <p>Origin Image</p>
  <img src="https://d32ogoqmya1dw8.cloudfront.net/images/NAGTWorkshops/structure/SGT2012/activities/noaa_global_topographic_map.jpg" />
</div>
like image 36
Evan Hu Avatar answered Nov 01 '22 20:11

Evan Hu