How do i draw rectangles that initiate, start and end with the mouse button?

edited May 2017 in How To...

This is what I'm after specifically;

There's a white 300x300 window. When you press the mouse in it, a rectangle is initiated. It has opposite corners (top left and bottom right) at that point and at the current location of the mouse respectively. The rectangle is blue and has no borders.

When the mouse is released, the rectangle is finished. The opposite corners are at (x1,y1), where the mouse was pressed, and (x2,y2), where it was released. The final rectangle is red with no borders.

Finally, the area of the rectangle drawn is displayed in integers at the centre of the screen, black, 24 font size, on top of the rectangle. The rectangle and text should both stay on until the mouse is pressed again, which repeats the procedure.

Preferably this would be done only in functions, no classes.

Answers

  • edited May 2017

    Use mousePressed() function to capture x1,y1.
    Use mouseDragged() to draw the temporary red rect from x1,y1 to mouseX,mouseY.
    Use mouseReleased()to draw the final blue rect from x1,y1 to x2,y2.

  • What about the display of the area value?

  • edited May 2017

    You know the top left and lower right corners, so you can DO MATH to get the lengths of the sides. Then you can DO MATH with the lengths of the sides to find the area. Then you can use text() to display some text in the sketch.

  • If you want it to display on mouseDragged, put it in mouseDragged. If on mouseReleased, put it there.

    If both... both!

  • Here is a very simple example to give you the idea -- draw annotated rectangles with the mouse. However, as soon as you want to draw multiple shapes, or edit the shapes, etc. etc. you will need to make a class and create methods of the class. If you really want to avoid class object but are interested in combining this with another sketch layer, use PGraphics.

    // boolean drawing;
    int x1,y1,x2,y2;
    void setup(){
      size(200,200);
      rectMode(CORNERS);
      textAlign(CENTER,CENTER);
    }
    void draw(){
      background(192);
      fill(255);
      rect(x1,y1,x2,y2);
      fill(0);
      text(abs(x2-x1) + "x" + abs(y2-y1), (x2+x1)/2, (y2+y1)/2);
    }
    void mousePressed(){
      x1 = x2 = mouseX;
      y1 = y2 = mouseY; 
    }
    void mouseDragged(){
      x2 = mouseX;
      y2 = mouseY;
    }
    
Sign In or Register to comment.