[英]Fabric.js: Find the center of an object (rect) in a group
我需要找到已放置到組中的對象的中心點。 我嘗試過的事情:
•getCenterPoint():返回中心點,就像對象位於0,0一樣。
•使用組和對象的getTop()和getLeft()計算中心點。 不幸的是,當組值起作用時,發現對象返回負值。
•使用對象的高度/寬度計算值。 在下面列出的情況下這很接近,但這僅是因為我的示例的特性非常具體,並且不能一概而論。
下面的對象是我當前正在使用的對象,具體地說,我正在尋找rect2的中心:
// create a rectangle object
var rect = new fabric.Rect({
top: 10,
fill: 'white',
stroke: 'black',
width: 20,
height: 20
});
// create a rectangle object
var rect2 = new fabric.Rect({
top: 10,
left: 20,
fill: 'white',
stroke: 'black',
width: 20,
height: 20
});
var line = new fabric.Line([ 20, 20, 40, 20],
{
top: 0,
left: 0,
stroke: 'black'
});
var group = new fabric.Group([ rect, rect2, line ],{
top: 100,
left: 100,
hasRotatingPoint: false
});
使用類似items = group._objects;
東西items = group._objects;
在組的項目中運行一個循環,找到您的對象,並獲取組內對象的坐標。
例如: items[i].oCoords.tr.x
,其余為數學, tr.x
和br.x = center x
同樣找到y
。
如果要找到畫布的中心, group.left
執行以下操作:將group.top
, group.left
添加到這些值。
您仍然可以在已添加到組中的對象上使用obj.getCenterPoint()。 但是,將對象添加到組中會從原始obj引用中刪除getCenterPoint方法。
如果像下面那樣重新分配obj引用,則可以在每個引用上使用getCenterPoint。
var allObjs = group.getObjects(),
rect1 = allObjs[0],
rect2 = allObjs[1],
line = allObjs[2];
return rect2.getCenterPoint();
這是一個工作示例: https : //jsfiddle.net/ns9zLxeu/25/
這是我用來獲取給定Rect中心的數學
var x1 = e.target.oCoords.oCoords.mt.x;
var y1 = e.target.oCoords.oCoords.mt.y;
var x2 = e.target.oCoords.oCoords.mb.x;
var y2 = e.target.oCoords.oCoords.mb.y;
var centerX = (x1 + x2) / 2;
var centerY = (y1 + y2) / 2;
然后在我的情況下,我使用中心坐標來創建一條線,方法是:
var line = makeLine([centerx, centery, 250, 175]);
canvas.add(line);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.