Ratio example image

I am doing some web design, and I need a way to dynamically figure out what to set a circle's diameter to so that it exactly covers a rectangle, as shown in the above image. In the first scenario (in the image), I calculated that the diameter of the circle was 12% greater than the width of the rectangle, and thought this would work for all rectangles, but it does not. The problem is that the width of the rectangle is dynamic, so I never know what it's value will be ahead of time, I have to size the circle based off of whatever dimensions the rectangle is at the time.

This is probably a fairly simple formula, but I am far from being a mathematician, clearly. If I can do anything to clarify my question, please ask! Thanks!


The diameter of the circle is equal to the diagonal of the rectangle. Let $w$ and $h$ be, respectively, the width and height of the rectangle. Then the diameter of the circle $d$ satisfies

$$d^2=w^2+h^2\iff d=\sqrt{w^2+h^2}.$$

Or, letting $a$ denote the ratio of the rectangle's height to its width, i.e. $a=\frac{h}{w}$, we have:

$$d^2=(1+a^2)w^2 \iff d=w\sqrt{1+a^2}.$$

  • $\begingroup$ So to clarify, here's what I came up with in JavaScript: a = rectangleHeight / rectangleWidth, circleWidth = rectangleWidth * Math.sqrt(1 + a*a) circleWidth being the diameter of the circle required, and Math.sqrt() being the JavaScript square root function. Is this correct? $\endgroup$ – Eric David Sartor Aug 16 '16 at 21:14
  • $\begingroup$ It looks fine to me. There is no need to use $a$ as in the second formula. I just gave it as another way to write the first formula. If you are not going to use $a$ elsewhere, probably you should use the first formula. $\endgroup$ – smcc Aug 17 '16 at 10:22
  • $\begingroup$ The reason I used the second formula is because I needed d, not d squared, and that seemed more direct and readable in my code :P Thanks very much! $\endgroup$ – Eric David Sartor Aug 18 '16 at 17:46
  • $\begingroup$ One other question...what is the purpose of the "1"? Is that an arbitrary number? $\endgroup$ – Eric David Sartor Aug 18 '16 at 17:47
  • 1
    $\begingroup$ $d^2=w^2+h^2=w^2+(aw)^2=w^2+a^2w^2=(1+a^2)w^2$ $\endgroup$ – smcc Aug 18 '16 at 17:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.