How to calculate the center of a rectangle in JavaScript

1 Answer

0 votes
class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
}

class Rectangle {
  constructor(topLeft, bottomRight) {
    this.topLeft = topLeft;
    this.bottomRight = bottomRight;
  }
}

function getCenter(rect) {
  const centerX = (rect.topLeft.x + rect.bottomRight.x) / 2.0;
  const centerY = (rect.topLeft.y + rect.bottomRight.y) / 2.0;

  return new Point(centerX, centerY);
}

const rect = new Rectangle(new Point(10.0, 20.0), new Point(110.0, 70.0));
const center = getCenter(rect);

console.log(`Center of the rectangle: (${center.x.toFixed(2)}, ${center.y.toFixed(2)})`);


     
/*
run:
     
Center of the rectangle: (60.00, 45.00)
     
*/

 



answered Jun 23, 2025 by avibootz
edited Jun 23, 2025 by avibootz

Related questions

...