简体   繁体   中英

FabricJS: How to manually set object width and height

I have a fabric rectangle and I want to change width & height manually. The problem is the next: When I first resize rect with scaling it makes resize as expected, but when after this I try to change the values in my inputs - the rectangle rerenders with wrong dimensions, but the width & height values in javascript object correct.

Code:

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.3/fabric.min.js"></script>
<canvas id="draw"></canvas>
width:<input type="number" id="w" value="50">
var w = document.getElementById('w');

var c = new fabric.Canvas('draw');

var rect = new fabric.Rect({
  top: 50,
  left: 50,
  width: parseInt(w.value),
  height: parseInt(h.value),
  fill: 'lightblue',
  type: 'rect'
});

c.add(rect);
c.renderAll();

c.on('object:scaling', function(e) {
  var width = parseInt(e.target.width * e.target.scaleX);
  w.value = width;
});

w.addEventListener('change', function(e) {
  rect.set('width', parseInt(e.target.value));
  rect.setCoords();
  c.requestRenderAll();
});

screenshot jsfiddle

Found a solution, maybe this will help someone. When we listen for a change of width/height, we also should take into account the current scale value.

w.addEventListener('change', (e) => {
  const scale = rect.getObjectScaling();
  rect.set('width', parseInt(e.target.value) / scale.scaleX);
  rect.setCoords();
  rect.requestRenderAll();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM