代码之家  ›  专栏  ›  技术社区  ›  zalemmm

织物js链接/取消链接2个对象

  •  0
  • zalemmm  · 技术社区  · 7 年前

    1 回复  |  直到 7 年前
        1
  •  0
  •   Durga    7 年前

    var canvas = new fabric.Canvas('c');
    var evented = false;
    var rect1 = new fabric.Rect({
      left: 50,
      top: 30,
      fill: 'blue',
      width: 150,
      height: 150,
      hasBorders:false,
      hasControls:false
    });
    
    var rect2 = new fabric.Rect({
      left: 210,
      top: 30,
      fill: 'magenta',
      width: 150,
      height: 150,
      hasBorders:false,
      hasControls:false
    });
    canvas.add(rect1,rect2);
    
    function rect1MouseDown(option){
     this.mousesDownLeft = this.left;
     this.mousesDownTop = this.top;
     this.rect2Left = rect2.left;
     this.rect2Top = rect2.top;
    }
    
    function rect1MouseMove(option){
     rect2.left = this.rect2Left+ this.left - this.mousesDownLeft ;
     rect2.top = this.rect2Top+ this.top- this.mousesDownTop;
     rect2.setCoords();
    }
    
    function rect2MouseDown(option){
     this.mousesDownLeft = this.left;
     this.mousesDownTop = this.top;
     this.rect1Left = rect1.left;
     this.rect1Top = rect1.top;
    }
    
    function rect2MouseMove(option){
     rect1.left = this.rect1Left+ this.left - this.mousesDownLeft ;
     rect1.top = this.rect1Top+ this.top- this.mousesDownTop;
     rect1.setCoords();
    }
    register();
    function register(){
     if(evented) return;
     rect1.on('moving', rect1MouseMove);
     rect1.on('mousedown', rect1MouseDown);
     rect2.on('moving',rect2MouseMove);
     rect2.on('mousedown',rect2MouseDown);
     evented = true;
    }
    function unRegister(){
     rect1.off('moving');
     rect1.off('mousedown');
     rect2.off('moving');
     rect2.off('mousedown');
     evented = false;
    }
    canvas {
     border: blue dotted 2px;
    }
    <script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
    <button onclick='register()'>Register Event</button>
    <button onclick='unRegister()'>Unregister Event</button><br>
    <canvas id="c" width="400" height="400"></canvas>

    或者,您可以在移动一个对象时将“左”和“顶”设置为另一个对象,因此当您根据该位置移动一个对象时,请设置“静止位置”。