Reputation: 31
I need to find the center point of an object that has been placed into a group. Things l have tried:
• getCenterPoint(): returns the center point as if the object were at 0,0.
• Calculating the center point using getTop() and getLeft() of both the group and the object. Unfortunately while the group values work find the object returns negative values.
• Calculated the values using heights/widths of objects. This gets close in the case listed below, but that’s only because of the very specific properties of my example, and would not generalize.
The object below is what I’m currently working with, specifically I’m looking to find the center of 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
});
Upvotes: 1
Views: 5848
Reputation: 24488
Here is the math that I used to get the center of a given 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;
Then in my case I used the center coor to create a Line using:
var line = makeLine([centerx, centery, 250, 175]);
canvas.add(line);
Upvotes: -1
Reputation: 1086
You can still use obj.getCenterPoint() on objects that have been added to a group; however, adding an object to a group removes the getCenterPoint method from the original obj reference.
If you reassign the obj references like below, you can then use getCenterPoint on each of them.
var allObjs = group.getObjects(),
rect1 = allObjs[0],
rect2 = allObjs[1],
line = allObjs[2];
return rect2.getCenterPoint();
Here is a working example: https://jsfiddle.net/ns9zLxeu/25/
Upvotes: 2
Reputation: 19
Use something like
items = group._objects;
Run a loop in items of group, find your object, and get the co-ordinates of object inside a group.
eg : items[i].oCoords.tr.x
the rest is mathematics , mid point of tr.x
and br.x = center x
similarly find y
.
if you want to find the center to canvas : add group.top
, group.left
to these values.
Upvotes: 1