在旋转物体后,是否可以得到垂直矩形的左、上、右位置

2022-04-07 00:00:00 javascript html5-canvas fabricjs

旋转对象后,是否可以获得虚拟矩形的左、上、右位置?


解决方案

您要查找的是对象的绑定矩形:

getBoundingRect(ignoreVpt)对象{→}返回对象的坐标 边框(左、上、宽、高)框的方向为 与画布轴对齐。

返回:具有Left、Top、Width、Height属性的对象Type对象

引用:fabricjs sourcecode

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
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>

由于after:render事件在呈现每一帧后不断激发,因此您可以看到对象在位置、旋转和尺寸方面的每次更新的边界框。

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
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>

供参考Working with events

相关文章