Fabric Js - 是否可以将图像对象自动缩放到 canvas?

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

我们目前通过以下代码上传图片:

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

和...

    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);
    };

如果图片太大,大于我们固定的宽度和高度 canvas 是否可以自动缩小该图片以适应 [=] 的固定宽度和高度24=]?

我应该指出我也在使用 Angular.js

ta

fabricjs 提供了一个非常简单的方法来做到这一点。 这些方法是接近 'apply a scale factor that will fit the image on the specified dimensions'

scaleToWidthscaleToHeight

所以你可以做到

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

如果您必须缩放最大、最小或两者,则取决于您是否要保持纵横比。

受到@AndreaBogazzi 的启发,我写了下面的代码使图像完全适合 canvas。

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>