Home > Net >  Given circle that is centered on bottom-left corner of a rect, calculate width of circle's boun
Given circle that is centered on bottom-left corner of a rect, calculate width of circle's boun

Time:06-06

Given a circle that is centered on the bottom-left corner of any rectangle (square, horizontal, vertical), calculate the width of the circle's bounding rectangle so its radius touches the top-right corner of the sizing rectangle in JavaScript.

Considering the image below, I am looking for 1 JS function that can handle all 3 scenarios, given the known width and height of the rectangle.

function getCircleWidth(width: number, height: number): number {
    // return width of circle's bounding rectangle
}

UPDATE:

See the accepted answer below for the bullet proof logic for this problem, Ended up with the following with help from here Requirements

CodePudding user response:

The width of a circle's bounding rectangle, is the circle's diameter (and that bounding rectangle is a square).

A circle's diameter is the double of its radius.

The diagonal of the given rectangle has a length that is equal to that radius.

The length of the diagonal can be derived from the right triangle it forms with the sides of that rectangle, using the Pythagorean theorem

So:

function getCircleWidth(width: number, height: number): number {
    return (width**2   height**2)**0.5 * 2;
}
  • Related