zalemmm
zalemmm

Reputation: 15

Fabric.js link/unlink 2 objects

I have 2 rectangles objects that i use as background template. Controls are disabled, they just can be dragged onto canvas. I would like them to behave like a group: when one of them is selected, the other one is too so they can be moved only together. I don't want to group them, mainly because at export, i need to remove one of them and i cannot find a way to do this... (unless there is a simple way to select item in a group but neither group.item().remove(), neither functions to ungroup my items or seems to work on my export function)

Upvotes: 0

Views: 707

Answers (1)

Durga
Durga

Reputation: 15614

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>

Alternatively you can set left and top to another object while moving one, so when ever you are moving one object according to that position set position for rest.

Upvotes: 0

Related Questions