简体   繁体   中英

Given circle that is centered on bottom-left corner of a rect, calculate width of circle's bounding rect so its radius touches the top-right corner

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 https://www.omnicalculator.com/math/diagonal-of-rectangle :

function getCircleWidth(width: number, height: number): number {
    return (Math.sqrt(Math.pow(width, 2) + Math.pow(height, 2)) * 2);
}

要求

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM