Glen Elkins
Glen Elkins

Reputation: 917

FabricJS 2 - Image isn't stretching to the given width

I have just upgraded from fabric 1.7 to 2 and now the image object is behaving differently.See the screenshot, the image where the arrow is is completely ignoring the fact that i set a width on it, it looks like it's actually scaling it based on the given height to keep the image ratio. I don't want this to happen, the image needs to stretch to the size i tell it to.

Anyone have any idea to stop it doing this? I mean if i set a width in the options for the image object i expect it to respect those dimensions. It should be stretching to fill where the red box is.

This is happening when loading the image initially as a square and setting {width:1000,height:400} for example, but instead it looks like it's taking the height and scaling the width down to keep it square.

enter image description here

Upvotes: 0

Views: 872

Answers (1)

Durga
Durga

Reputation: 15604

You need to set scaleX for width and scaleY for height. It's a breaking change for v2.

DEMO

var canvas = new fabric.Canvas('c');
var index = 0,
  json;
var url = '//fabricjs.com/assets/pug.jpg';

fabric.Image.fromURL(url, function(img) {
  var elWidth = img.naturalWidth || img.width;
  var elHeight = img.naturalHeight || img.height;
  img.set({
    scaleX:200/elWidth,
    scaleY:200/elHeight
  })
  canvas.add(img);
})
canvas{
 border:2px solid #000;
}
<script type="text/javascript" src="
https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas id="c" width="400" height="400"></canvas>

Upvotes: 1

Related Questions