Pirs01
Pirs01

Reputation: 135

fabric.js Stop object dragging programmatically

In my mouse:down event listener under certain conditions I want to deactivate the object that user just activated with mouse:down. In other words when user tries to drag an object in some cases I want to execute some code and prevent the dragging.

Simply calling

fabric.deactivateAll();

will deselect the object (object control disappears) but the dragging functionality will be uninterrupted.

I tried to:

fabric.fire('mouse:up');

to simulate user letting go of object and it fires but it has no effect on dragging.

How can I programmatically disable dragging? Also how would I active it on another object if the two methods are not the same?

 

Context: I have a group of objects that user can manipulate normally. However there is one special object in that group in that when user tries to drag by clicking on that special object it should be removed from group, added to canvas and the dragging should be applied to special object instead of entire group. After the special object is deselected it gets added to group again. I have everything working except the part where dragging functionality is transferred from entire group to special object.

Upvotes: 5

Views: 16832

Answers (2)

Grim
Grim

Reputation: 1986

I was looking for the same solution. I had a discussion with a fabricjs dev that this will lead to bad ux-experience on smartphones.

Instead I do animate now that the block moves itself back to a valid position.

Upvotes: 0

leroydev
leroydev

Reputation: 2945

I made a JSFiddle in which an object that is dragged is stopped after 500 milliseconds. You can set rect.lockMovementX = true; and rect.lockMovementY = true; to stop dragging and set them false to allow dragging again.

Regarding your need to only apply it to certain objects: just add a stopDragging variable, which has true as value for the objects that you want to stop dragging, false for the ones you don't want to stop dragging. Then check in the onMoving function whether or not e.target.stopDragging is true or false.

(function() {
  var canvas = new fabric.Canvas("canvas");
  fabric.Object.prototype.transparentCorners = false;

  var rect = new fabric.Rect({
    width: 100,
    height: 100,
    top: 100,
    left: 100,
    fill: 'rgba(255,0,0,0.5)'
  });

  canvas.add(rect);

  var timeoutTriggered = false;

  function stopDragging(element) {
    element.lockMovementX = true;
    element.lockMovementY = true;
  }

  function onMoving(e) {
    if (!timeoutTriggered) {
      setTimeout(function() {
        stopDragging(e.target);
      }, 500);
      timeoutTriggered = true;
    }
  }
  canvas.on({
    'object:moving': onMoving
  });
})();

Upvotes: 12

Related Questions