Resize An Existing Rectangle On Mouse Hover

341 views Asked by At

I tried to follow a tutorial and finally came to a solution, almost. Here's the link for stackblitz - Resize SVG Rectangle

So here's the scenario, a rectangle is drawn using SVG with default perimeters that's working fine. My requirement is to resize the existing rectangle when I hover the mouse on it and if I click in any other section rather than the rectangle, then it should be drawn from scratch. So right now, whatever I do, it starts the drawing from scratch rather than resizing the existing one.

For a reference, this is what I am trying for resizing only: Resize Rectangle

So these are the events that are attached to the svg element:

//This section starts drawing rectangle from scratch
startDrawing(evt: MouseEvent) {
    this.createdShape = {
      type: this.shapeType,
      x: evt.offsetX,
      y: evt.offsetY,
      w: 0,
      h: 0,
  };

  this.shapesToDraw.fill(this.createdShape); //This fills with the created shape
}

//This does the resizing but only when I start drawing a rectangle from scratch, doesn't imply resizing for existing rectangle
keepDrawing(evt: MouseEvent) {
   this.createdShape.w = evt.offsetX - this.createdShape.x;
   this.createdShape.h = evt.offsetY - this.createdShape.y;
}

//This stops drawing and sets **createdShape** to null
stopDrawing() {
   this.createdShape = null;
}

I am thinking to check if there are any certain conditions to check for resizing as follows:

private resizeConMeet(evt: MouseEvent) {
    
}

But I am not sure if there's any way I can do so? Would expect a suggestion or guidance to make it work.

1

There are 1 answers

1
Arnaud Denoyelle On BEST ANSWER

Nice work :)

So, thanks to the StackBlitz, I could adapt the code.

The main ideas :

  • When you start drawing, try to use the previous shape if
    • this.createdShape.x < evt.x < this.createdShape.x + w
    • this.createdShape.y < evt.y < this.createdShape.y + h
  • This means that you should not erase the previous shape (this.createdShape = null) when you stop drawing
  • But this will create a bug because it will continue editing the shape when the mouse moves. Solve this by adding a variable (isDrawing) that you set to true when you start drawing and set to false when you stop drawing. Use this variable to prevent redrawing the rectangle when you are not drawing

Please try to do it by yourself. Here is my version