Set object drag limit in Fabric.js

前端 未结 5 1224
面向向阳花
面向向阳花 2020-12-24 00:24

i am new in fabric js want to set the drag limit\"enter

i have also try with https://

5条回答
  •  借酒劲吻你
    2020-12-24 01:01

    While Orangepill's answer is correct, it produces a "stuttering" when your object hits the object bounds. If you have a rectangular bounding box (and not a complex bounding object) an alternative is to allow the object to be dragged along the bounds and "slide" along the bounding box. You do this by capping the coordinates values and letting the other dimension move as usual. An example snippet would look like so:

    var canvas = new fabric.Canvas("bounded");
    
    var boundingBox = new fabric.Rect({
      fill: "none",
      width: 600,
      height: 400,
      hasBorders: false,
      hasControls: false,
      lockMovementX: true,
      lockMovementY: true,
      evented: false,
      stroke: "red"
    });
    
    var movingBox = new fabric.Rect({
      width: 100,
      height: 100,
      hasBorders: false,
      hasControls: false
    });
    
    canvas.on("object:moving", function() {
      var top = movingBox.top;
      var bottom = top + movingBox.height;
      var left = movingBox.left;
      var right = left + movingBox.width;
    
      var topBound = boundingBox.top;
      var bottomBound = topBound + boundingBox.height;
      var leftBound = boundingBox.left;
      var rightBound = leftBound + boundingBox.width;
    
      // capping logic here
      movingBox.setLeft(Math.min(Math.max(left, leftBound), rightBound - movingBox.width));
      movingBox.setTop(Math.min(Math.max(top, topBound), bottomBound - movingBox.height));
    });
    
    canvas.add(boundingBox);
    canvas.add(movingBox);
    

    See this example in JSFiddle here

提交回复
热议问题