Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fabricjs , After rotating object is it possible to get left,top and right position of viritual rectagle

preview

After rotating object is it possible to get left,top and right position of virtual rectangle?

like image 424
DM007 Avatar asked Nov 27 '16 08:11

DM007


1 Answers

What you are looking for is the bounding rect of your object:

getBoundingRect(ignoreVpt) → {Object} Returns coordinates of object's bounding rectangle (left, top, width, height) the box is intented as aligned to axis of canvas.

Returns: Object with left, top, width, height properties Type Object

reference: fabricjs sourcecode

var canvas = this.__canvas = new fabric.Canvas('c');
fabric.Object.prototype.transparentCorners = false;
var rect = new fabric.Rect({
  left: 120,
  top: 30,
  width: 100,
  height: 100,
  fill: 'green',
  angle: 20
});

canvas.on('after:render', function() {
  canvas.contextContainer.strokeStyle = '#555';
  canvas.forEachObject(function(obj) {
    var bound = obj.getBoundingRect(); // <== this is the magic
    console.log(bound);
    canvas.contextContainer.strokeRect(
      bound.left,
      bound.top,
      bound.width,
      bound.height
    );

  });

});
canvas.add(rect);
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas height=200 width=300 id="c" style="border:1px solid black"></canvas>

Since the after:render event is fired continuously after each frame is rendered you can see the updated bounding box of your object for every update, in position, rotation and dimensions.

var canvas = this.__canvas = new fabric.Canvas('c');
fabric.Object.prototype.transparentCorners = false;
var rect = new fabric.Rect({
  left: 120,
  top: 30,
  width: 100,
  height: 100,
  fill: 'green',
  angle: 20
});
canvas.add(rect);
canvas.on('after:render', function() {
  canvas.contextContainer.strokeStyle = '#555';
  var ao = canvas.getActiveObject();
  if (ao) {
    var bound = ao.getBoundingRect();

    canvas.contextContainer.strokeRect(
      bound.left,
      bound.top,
      bound.width,
      bound.height
    );
    console.log(bound);

  }
});
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas height=200 width=300 id="c" style="border:1px solid black"></canvas>

For reference Working with events

like image 97
alessandro Avatar answered Nov 18 '22 08:11

alessandro