Shishir Jakati
Shishir Jakati

Reputation: 35

How to resize a background image to match the canvas? FabricJS

So I am currently having a problem. I am using Meteor.js and Fabric.js, and I am trying to figure out how to rescale an image to fit into the canvas. Currently this is my code:

 var canvas = new fabric.Canvas('c1');
 canvas.setWidth(800);
 canvas.setHeight(800);
 var canvasHeight = canvas.height;
 var canvasWidth = canvas.width;

 //Just a debug statement console.log(canvasWidth, canvasHeight);

 var bgImg = new fabric.Image();
 bgImg.setSrc('http://www.aamcocolorado.com/images/Highway-
 Traffic.jpg');
 bgImg.set({
    top: canvasHeight / 2,
    left: canvasWidth / 2,
    scaleX: canvasWidth/bgImg.width,
    scaleY: canvasHeight/bgImg.height,
 });

 canvas.setBackgroundImage(bgImg);

The result of this is that I am getting a snippet of the image, that is not scaled to the correct size. Wondering what I was missing?

(Have already checked out other answers, but was not able how to apply it to Meteor, am a JS beginner)

Upvotes: 2

Views: 2726

Answers (2)

Ivan
Ivan

Reputation: 10382

setSrc is asynchronous. You can provide a function as a callback to run after the image loads:

var

canvas = new fabric.Canvas('c1');
canvas.setWidth(800);
canvas.setHeight(800);
var canvasHeight = canvas.height;
var canvasWidth = canvas.width;

//Just a debug statement console.log(canvasWidth, canvasHeight);

var bgImg = new fabric.Image();
bgImg.setSrc('http://www.aamcocolorado.com/images/Highway-Traffic.jpg', function () {
  bgImg.set({
    top: 0,
    left: 0,
    scaleX: canvasWidth/bgImg.width,
    scaleY: canvasHeight/bgImg.height,
  });
});

canvas.setBackgroundImage(bgImg);

https://jsfiddle.net/upg0tyvz/1/

Upvotes: 3

Jaromanda X
Jaromanda X

Reputation: 1

As .setSrc loads the image asynchronously, you need to wait for the image to finish loading before its dimensions are known

.setSrc has an optional call back argument that is called when the image has completed loading, so perhaps you can do

var bgImg = new fabric.Image();
bgImg.setSrc('http://www.aamcocolorado.com/images/Highway-Traffic.jpg', function() {
    bgImg.set({
        top: canvasHeight / 2,
        left: canvasWidth / 2,
        scaleX: canvasWidth/bgImg.width,
        scaleY: canvasHeight/bgImg.height,
    });
    canvas.setBackgroundImage(bgImg);
});

Upvotes: 0

Related Questions