AntonAntonoff
AntonAntonoff

Reputation: 197

Can't get proper coordinates for selected objects on canvas

For example let's create two rectangles. Then we select these two rectangles and want to see their coordinates:

var greyBox = new fabric.Rect({
    left:100,
    top:100,
    fill: 'grey',
    width: 100,
    height: 100
});

var redBox = new fabric.Rect({
    left:300,
    top:300,
    fill: 'red',
    width: 100,
    height: 100
});

function createCanvas(id){
    canvas = new fabric.Canvas(id);
    canvas.add(greyBox);
    canvas.add(redBox);

    canvas.on('selection:created', function(e) {
        const activeSelection = e.target;

        console.log(activeSelection._objects[0].left);
        console.log(activeSelection._objects[1].left);
    });

    return canvas;
} 

We know exactly that their lefts are 100 and 300. But instead we see this: -150 and 49: the coords are -150 and 49

How do we get the proper coords?

Upvotes: 1

Views: 1185

Answers (1)

melchiar
melchiar

Reputation: 2862

To find positional properties of an object in a group or multi-selection you can use the calcTransformMatrix() method.

var matrix = activeSelection._objects[0].calcTransformMatrix();
var options = fabric.util.qrDecompose(matrix);
console.log(options.translateX, options.translateY);

The options object will have the transformed values you need. See http://fabricjs.com/using-transformations to better understand the transformMatrix system.

Upvotes: 4

Related Questions