121k views
0 votes
Create a program that draws a rectangle whenever you click the mouse. The rectangle should have a width of 30 and a height of 50 and be centered at the place where the user clicks. Remember, the position of a rectangle is the top left corner. To place the rectangle at the center of the click, you will need to adjust the position.

1 Answer

4 votes

Final answer:

To center a rectangle at a mouse click position, you must calculate the top-left coordinates by subtracting half the rectangle's width and height from the click's coordinates. Then, use these adjusted coordinates to draw the rectangle with the given dimensions.

Step-by-step explanation:

To create a program that draws a rectangle centered at the mouse click location, we need to calculate the top-left corner position of the rectangle accordingly. Since rectangles are traditionally defined by their top-left corner coordinates, and we want our rectangle to have a width of 30 and a height of 50, we must offset the mouse click coordinates by half the dimensions of the rectangle.

Here's a simple formula to calculate the position of the top-left corner of the rectangle:

  • x_position = mouse_click_x - (rectangle_width / 2)
  • y_position = mouse_click_y - (rectangle_height / 2)

The program would then use these x_position and y_position to draw the rectangle. Here's how it might look in pseudocode:

OnClick(mouse_event):
mouse_click_x = mouse_event.x
mouse_click_y = mouse_event.y
rectangle_width = 30
rectangle_height = 50
top_left_corner_x = mouse_click_x - (rectangle_width / 2)
top_left_corner_y = mouse_click_y - (rectangle_height / 2)
DrawRectangle(top_left_corner_x, top_left_corner_y, rectangle_width, rectangle_height)

User Yuval Atzmon
by
5.8k points