Fabric.js: Problem while resizing the rectangle

Code: https://codepen.io/eajithkumar128/pen/poNwJJv?editors=0010

I have a table like structure in the canvas drawn using a rectangle, I have drawn lines in the row and column ends like below (lines in blue color are rectangle and red color lines are the fabric line object)

enter image description here

I am trying to adjust the size of the rectangles by moving the lines, whenever I am moving the column lines I could see the entire rectangle itself moving wherein I am only trying to update the width, Also I could see an imaginary rectangle drawn behind it which has correct width, but the original rectangle is not resizing correctly. Please refer to the image below.

enter image description here

Code to get the rect object before and after lines while selecting the line:

canvas.on('selection:created', function(e){
        let targetEle = e.target;
    initialPosition = e.left;
    selectedBoxesLeft = []
        selectedBoxesRight = []
    canvas.forEachObject((v)=>{
        if(v.left+v.width === targetEle.left && v.type==="rect"){
        selectedBoxesLeft.push(v);
      }
      if(v.left === targetEle.left && v.type==="rect"){
        selectedBoxesRight.push(v);
      }
    });
    console.log(selectedBoxesLeft);
    console.log(selectedBoxesRight);
});

Code to resize while moving:

canvas.on('object:moving',function(e){
    let target = e.target;
  if(target.left < initialPosition){
    selectedBoxesLeft.forEach((v)=>{
      v.width =target.left - v.left
    })
    
    selectedBoxesRight.forEach((v)=>{
      let left = v.left
      v.left = target.left;
      v.width = v.width + (left- target.left)
    });
    canvas.renderAll()
  }else{
    // selectedBoxesLeft.forEach((v)=>{
    //   v.width = v.width + (target.left - v.width)
    // })
    // selectedBoxesRight.forEach((v)=>{
    //   // v.width = v.width + (v.left - target.left)
    //   v.left = target.left;
    //   v.width = v.width - target.left;
    // })
  }
});

40 thoughts on “Fabric.js: Problem while resizing the rectangle”

Leave a Comment