FabricJs 1.7.18 scaleToWidth() not setting the given width

a 夏天 提交于 2019-12-13 04:22:15

问题


As per this answer I have built fabricJs version 1.7.18 with all features enabled - Built output file.

I am using the following code to change an object's width and height using scaleToWidth(), but the new width value is not set properly. It is setting the width with some other value.

var obj = canvas.getActiveObject();

obj.scaleX = 1;
obj.scaleY = 1;
obj.scaleToWidth(65);
obj.setCoords();

canvas.renderAll();

//This gives a different width value
console.log(obj.getWidth()); 

Can anyone help me out to fix this issue?

My actual requirement is: To set the height relatively when I am setting the object width. Example: I have an object with width 50 and height 40. If I am setting the width as 100 using the function setWidth(), then is there any built-in function to set the height as 80?


回答1:


As mentioned in scaleToWidth Scales an object to a given width, with respect to bounding box (scaling by x/y equally).

And getWidth Returns width of an object bounding box counting transformations.

If you just want to set width of an object use obj.width = value.

You can use scale() or scaleX(),scaleY() to scale an object .

DEMO

(function() {
  var canvas = this.__canvas = new fabric.Canvas('c');
  var rect = new fabric.Rect({
   left:50,top:50,width:50,height:40
  })
  canvas.add(rect);
  rect.scale(2);
  rect.setCoords();
  console.log(rect.height,rect.scaleY)
  
})();
canvas{
  border-width: 1pz;
  border-style: solid;
  border-color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.0.0-rc.3/fabric.js"></script>
<canvas id='c' width=300 height=300></canvas>

As you know the width you are setting. calculate the difference how much percentage its changed set the same to height. You will get the result.



来源:https://stackoverflow.com/questions/47922611/fabricjs-1-7-18-scaletowidth-not-setting-the-given-width

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!