Skip to content

Instantly share code, notes, and snippets.

@kyletimmermans
Last active April 10, 2024 13:58
Show Gist options
  • Select an option

  • Save kyletimmermans/78a7ba326a93cb909df9b656a30f5c77 to your computer and use it in GitHub Desktop.

Select an option

Save kyletimmermans/78a7ba326a93cb909df9b656a30f5c77 to your computer and use it in GitHub Desktop.
The Python code and math for finding the coordinates of a point on the edge of a circle where a line between two points intersects on the circle, the two points being: the center of the circle (A) and the point outside of the circle (B). This math can be used to draw a line cleanly from the edge of a circle without it overlapping the circle itself.
from math import sqrt
# https://math.stackexchange.com/questions/127613/closest-point-on-circle-edge-from-point-outside-inside-the-circle
def circle_edge_point(x1, y1, x2, y2, r):
try:
cx = x1 + (r * (x2 - x1) / sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2))
except ZeroDivisionError:
# Add 0.0001 if divisor is 0
cx = x1 + (r * (x2 - x1) / sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2) + 0.0001)
try:
cy = y1 + (r * (y2 - y1) / sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2))
except ZeroDivisionError:
cy = y1 + (r * (y2 - y1) / sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2) + 0.0001)
# Return x,y of C-coord as a list
return [cx, cy]
c_coords = circle_edge_point(0, 0, 3.6, 4, 3)
print(c_coords)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment