Search code examples
javascriptangularjsfabricjs

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

  • 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.