答案 0 :(得分:4)
您正在寻找的是对象的边界矩形:
getBoundingRect ( ignoreVpt )→{Object}返回对象的坐标 意图为框的边界矩形(左,顶部,宽度,高度) 与画布轴对齐。
返回:具有left,top,width,height属性的对象Type Object
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
事件,因此您可以在每次更新时查看对象的更新边界框,包括位置,旋转和尺寸。
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>