given a circle and a point outside of circle get tangent point on circle edge in typescript

To find the tangent point on the edge of a circle from a given point outside the circle, you can use the following approach in TypeScript:

index.ts
interface Point {
  x: number;
  y: number;
}

interface Circle {
  center: Point;
  radius: number;
}

function getTangentPoint(circle: Circle, point: Point): Point[] {
  const dx = point.x - circle.center.x;
  const dy = point.y - circle.center.y;
  const distance = Math.sqrt(dx * dx + dy * dy);

  if (distance < circle.radius) {
    // Point is inside the circle, there is no tangent.
    return [];
  } else if (distance === circle.radius) {
    // Point is on the circle edge, there is a single tangent point.
    return [{ x: point.x, y: point.y }];
  } else {
    // Point is outside the circle, there are two tangent points.
    const angle = Math.atan2(dy, dx);
    const tangentAngle = Math.asin(circle.radius / distance);

    const tangentPoint1: Point = {
      x: circle.center.x + circle.radius * Math.cos(angle + tangentAngle),
      y: circle.center.y + circle.radius * Math.sin(angle + tangentAngle)
    };

    const tangentPoint2: Point = {
      x: circle.center.x + circle.radius * Math.cos(angle - tangentAngle),
      y: circle.center.y + circle.radius * Math.sin(angle - tangentAngle)
    };

    return [tangentPoint1, tangentPoint2];
  }
}

// Example usage:
const circle: Circle = {
  center: { x: 0, y: 0 },
  radius: 5
};

const point: Point = { x: 10, y: 0 };

const tangentPoints = getTangentPoint(circle, point);
console.log(tangentPoints);
1376 chars
51 lines

This approach first calculates the distance between the given point and the center of the circle. If the distance is less than the radius of the circle, it means the point is inside the circle and there are no tangent points. If the distance is equal to the radius, it means the point is on the edge of the circle and there is a single tangent point. If the distance is greater than the radius, it means the point is outside the circle and there are two tangent points.

To find the tangent points, we calculate the angle between the point and the center of the circle using Math.atan2. We then use Math.asin to find the angle subtended by the radius and the tangent line at the center of the circle. Finally, we use trigonometry to calculate the coordinates of the tangent points.

related categories

gistlibby LogSnag