2

I was trying to snap the rect to show up a perfect square upon transform. i.e when resizing if width and height becomes same I'll show lines indicating it's a square.

but, while doing the height or width of the rect is growing unexpectedly as shown in gif

enter image description here

The codesandbox link was https://codesandbox.io/s/snapex-forked-919s83

Here for snapping the rect around 3px margin, I wrote the below code.

boundBoxFunc={(oldPos, newPos) => {
       if (Math.abs(newPos.width - newPos.height) <= 3) {
           if (Math.abs(oldPos.width - oldPos.height) <= 3) return newPos
           let square = Math.max(newPos.width, newPos.height)
           newPos.width = square
           newPos.height = square
       }
       return newPos
}}

I knew this logic is what causing the issue. can anyone kindly help me to write better logic so the rect wont grow upon snapping.

Vikas Acharya
  • 3,550
  • 4
  • 19
  • 52

1 Answers1

2

the inherit Problem is, that youre changing the height while moving the width. But you probably only want to move that direction youre already moving on.

So the most simplest solution would be to look if youre moving the height or width.

So my solution would be this function:

boundBoxFunc={(oldPos, newPos) => {  
 if (Math.abs(newPos.width - newPos.height) <= 3) {
   if (Math.abs(oldPos.width - oldPos.height) <= 3) return newPos;
     // Find out if you moved the width or height.
     if(newPos.height - oldPos.height != 0){
       // We have moved the height and shouldnt manipulate the width
       newPos.height = newPos.width;
     }else{
       // vice verca
       newPos.width = newPos.height;
     }
  }
  return newPos;
}
Raqha
  • 754
  • 4
  • 17
  • 1
    I agree the conclusion of the issue and the suggested fix. – Vanquished Wombat Apr 03 '23 at 20:14
  • 1
    I tried my best to achieve exactly as in adobe illustrator. where the snap is so good. but still It's not smooth. but this answered the issue I raised. MARKED IT AS ANSWER AND GAVE THE BOUNTY. – Vikas Acharya Apr 10 '23 at 02:38
  • Can anyone of you help me out with the related issue on https://stackoverflow.com/questions/76525337/ . I need to display the line with dimensions of frame – Deep Kakkar Jun 22 '23 at 06:06