[JAVASCRIPT] How to cover a rectangle with a circle when the circle's center is not at the same position as the rectangle's center
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Circle in rectangle</title> | |
</head> | |
<body> | |
<!-- | |
By Dani Guardiola | |
The diameter() function calculates the diameter that a circle | |
must have to cover a rectangle based on its center position and | |
the rectangle's dimensions. | |
The run() function reflects it into the DOM for demonstration purposes. | |
Further explanation: | |
Imagine that we want to cover a rectangle completely with a circle with | |
the same center as the rectangle. To find the correct diameter in this | |
case, we just have to calculate the diagonal of the rectangle and use it | |
as the circle's diameter. | |
This is very easy to calculate just by using the Pythagoras' Theorem: | |
outer_radius = 0.5 * sqrt(width * width + height * height) | |
Source: | |
http://stackoverflow.com/questions/2891222/choosing-circle-radius-to-fully-fill-a-rectangle | |
But what happens when the center of the circle is not at the same | |
position as the center of the rectangle? | |
Well in that case, we must readjust the width and the height used to | |
calculate the radius by "simulating" another rectangle with the same | |
center position as the circle. | |
The way to do this is simple, we just have to find out what distance to | |
the edge from the circle center position is greater in X and Y, and | |
duplicate it to find out the new rectangle dimensions. | |
For example, to find out the width of the new rectangle, we must first | |
find the distance from X to the left edge (which is X itself) and to | |
the right edge (initial width minus X). | |
Then we duplicate the greater value of those two and we have the width | |
we are gonna use to calculate the radius of the circle. | |
--> | |
<div id="rectangle" style="margin: 150px; height: 100px; width: 100px; background-color: blue; position: relative;"> | |
<div id="circle" style="border-radius: 50%; height: 50px; width: 50px; background-color: rgba(0, 0, 0, 0.5); top: 25px; left: 25px; position: absolute;"></div> | |
</div> | |
<script type="text/javascript"> | |
function run(x, y) { | |
var rectangle = document.querySelector("#rectangle"); | |
var circle = document.querySelector("#circle"); | |
var rect = rectangle.getBoundingClientRect(); | |
var d = diameter(rect.width, rect.height, x, y); | |
circle.style.height = circle.style.width = d + "px"; | |
circle.style.top = y - (d / 2) + "px"; | |
circle.style.left = x - (d / 2) + "px"; | |
} | |
function diameter(w, h, x, y) { | |
var width = Math.max(w - x, x) * 2; | |
var height = Math.max(h - y, y) * 2; | |
var diameter = Math.sqrt(width * width + height * height); | |
return diameter; | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment