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

Viewed 2157

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)

2 Answers
Related