Created
September 23, 2018 20:31
-
-
Save jiayihu/65aea2151d744e7a0b38bf3bf818b75b to your computer and use it in GitHub Desktop.
Determine the intersection of a segment, having ad edge in the center of circle, with the circle itself
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Determine the intersection of a segment, having ad edge in the center of circle, | |
* with the circle itself | |
*/ | |
function intersect( | |
xc: number, | |
yc: number, | |
radius: number, | |
x1: number, | |
y1: number | |
): { x: number; y: number } | null { | |
const distanceFromCenter = Math.sqrt((x1 - xc) ** 2 + (y1 - yc) ** 2); | |
const isInside = distanceFromCenter < radius; | |
if (isInside) return null; | |
// Segment ends on the circumference | |
if (distanceFromCenter === radius) return { x: x1, y: y1 }; | |
const slopeRad = Math.atan2(y1 - yc, x1 - xc); | |
const x = xc + radius * Math.cos(slopeRad); | |
const y = yc + radius * Math.sin(slopeRad); | |
return { x, y }; | |
} | |
const inside = intersect(0, 0, 3, 1, 1); | |
const circumferenceRight = intersect(0, 0, 3, 3, 0); | |
const circumferenceTop = intersect(0, 0, 3, 0, 3); | |
const circumferenceTopRight = intersect( | |
0, | |
0, | |
3, | |
2.121320343559643, | |
2.121320343559643 | |
); | |
const outsideTopRight = intersect(0, 0, 3, 4, 4); | |
const outsideX = intersect(0, 0, 3, 4, 0); | |
const outsideTopLeft = intersect(0, 0, 3, -4, 4); | |
console.log({ | |
inside, | |
circumferenceRight, | |
circumferenceTop, | |
circumferenceTopRight, | |
outsideTopRight, | |
outsideX, | |
outsideTopLeft | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment