Fabricjs, After turning the object, you can get the left, top and right positions of the wind rectangle

preview

After turning the object, you can get the left, top and right positions of the virtual rectangle?

+4
source share
1 answer

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

getBoundingRect (ignoreVpt) → {Object} Returns the coordinates of the object bounding box (left, top, width, height). Aligned to the axis of the canvas.

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

link: filejs 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>
Run codeHide result

after:render , , , .

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>
Hide result

+4

Source: https://habr.com/ru/post/1662055/


All Articles