alexc
alexc

Reputation: 1310

Objects move position automatically when trying to select all on mousedown (Fabric.JS)

When I use a button to select all objects I am able to move everything fine, and it all stays in position. However if I want to fire the event when I click on a object on the canvas, it does not work as intended.

Here is a Plnk;

http://plnkr.co/edit/iqn5QpBRe30eftoI1z8p?p=preview

I am using this as snippet of code to selectAll;

function selectAllCanvasObjects(){
var objs = canvas.getObjects().map(function(o) {
  return o.set('active', true);
});

var group = new fabric.Group(objs, {
  originX: 'center', 
  originY: 'center'
});

canvas._activeObject = null;

canvas.setActiveGroup(group.setCoords()).renderAll();

}

When I activate it through a button click, I am able to move all objects on the canvas okay, and they also do not move position on click.

If I activate it the following way;

triangle.on('mousedown', function(e){
  selectAllCanvasObjects();
})

It will not initialise moving all objects straight away.

If I use;

canvas.on('mouse:down', function(e){
  selectAllCanvasObjects();
})

It will make the objects automatically jump position.

I am wondering if there is a way I can use the two previous methods so the function behaves like when clicked?

Upvotes: 2

Views: 2190

Answers (1)

Ben
Ben

Reputation: 979

If I'm understanding this right, I think I answered a pretty similar question a little while back: Fabricjs - how do I deselect an object and select a group without releasing the mouse button.

I modified your Plunkr towards that end (example code below): http://plnkr.co/edit/5FN5HYWNjU5I3sZO9ixI?p=preview. Hopefully this helps you out.

triangle.on('mousedown', function(evt) {
  canvas.deactivateAll();
  var objs = canvas.getObjects();

  var group = new fabric.Group(objs, {
    status: 'moving'
  });
  // Relevant code
  var originalX = triangle.left,
    originalY = triangle.top,
    mouseX = evt.e.pageX,
    mouseY = evt.e.pageY;

  triangle.on('moving', function(evt) {
    triangle.left = originalX;
    triangle.top = originalY;
    group.left += evt.e.pageX - mouseX;
    group.top += evt.e.pageY - mouseY;
    originalX = triangle.left;
    originalY = triangle.top;
    mouseX = evt.e.pageX;
    mouseY = evt.e.pageY;
  });

  triangle.on('mouseup', function() {
    triangle.off('moving');
  })

  canvas.setActiveGroup(group.setCoords()).renderAll();
});

Upvotes: 3

Related Questions