简体   繁体   中英

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.

fabric.deactivateAll();

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
  });
})();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM