'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



Solution 1:[1]

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>

Solution 2:[2]

it looks like the reason is that the browser still treats $message as "WINDOWS-256" encoded. Everything else is UTF8 encoded!

So iconv resolved the issue.

$message=urlencode($message);

Should be:

$message=urlencode(iconv("WINDOWS-256", "UTF-8", $message));

I don't really know why, but it has done the trick!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Evan Hu
Solution 2 Quest