Search code examples
javascriptfabricjs

Getting x/y shift in Fabric object move event


In this jsFiddle I have a Fabric rect that can be dragged. What I need to know is how much the rect was dragged horizontally (X) and vertically (Y).

I'm capturing the moving event, but I have trouble finding the shift in X and Y. How to print the X/Y measure taken from the event? Note that the initial position is x=50, y=50. if I move the rect, then stop and then move again, the shift should be relative to x=50, y=50.

var canvas = new fabric.Canvas('c');

var coords = new fabric.Textbox("not moved yet", {
  fontSize: 16,
  width: 300
});

var text = new fabric.Textbox("Drag me", {
  left: 50,
  top: 50,
  width: 100,
  backgroundColor: 'yellow',
});

canvas.add(coords,text);

canvas.on('object:moving', function(e) {
     console.log(e);
     var x = e.target.transform.ex;
     var y = e.target.transform.ey;
     coords.text = 'Moved x = ' + x + ', y = ' + y;
});

Solution

  • You can keep track of the change yourself, just save the initial coordinates into separate variables.

    let lastX = text.left
    let lastY = text.top
    
    canvas.on('object:moving', function (e) {
      const diffX = e.target.left - lastX
      const diffY = e.target.top - lastY
      coords.text = 'Moved x = ' + diffX + ', y = ' + diffY
    })