given a point and a circle get point on edge if circle in typescript

To find a point on the edge of a circle given a point and the circle's properties in TypeScript, you can use simple trigonometry calculations.

Assuming you have the following inputs:

  • circleCenter: The coordinates of the center of the circle (e.g., { x: 0, y: 0 })
  • circleRadius: The radius of the circle
  • point: The coordinates of the point (e.g., { x: 3, y: 4 })

You can calculate the point on the edge of the circle as follows:

index.ts
function getPointOnCircle(circleCenter: { x: number, y: number }, circleRadius: number, point: { x: number, y: number }): { x: number, y: number } {
  // Calculate the vector between the circle center and the point
  const vectorX = point.x - circleCenter.x;
  const vectorY = point.y - circleCenter.y;

  // Calculate the magnitude of the vector
  const vectorMagnitude = Math.sqrt(vectorX * vectorX + vectorY * vectorY);

  // Calculate the unit vector (direction) of the vector
  const unitVectorX = vectorX / vectorMagnitude;
  const unitVectorY = vectorY / vectorMagnitude;

  // Calculate the point on the edge of the circle
  const edgePointX = circleCenter.x + unitVectorX * circleRadius;
  const edgePointY = circleCenter.y + unitVectorY * circleRadius;

  return { x: edgePointX, y: edgePointY };
}

// Usage example
const circleCenter = { x: 0, y: 0 };
const circleRadius = 5;
const point = { x: 3, y: 4 };

const edgePoint = getPointOnCircle(circleCenter, circleRadius, point);
console.log(edgePoint); // Outputs: { x: 2.4, y: 3.2 }
1045 chars
27 lines

The getPointOnCircle function calculates the vector between the circle center and the given point, normalizes it to get the unit vector, and then scales it by the circle radius to get the point on the edge of the circle.

gistlibby LogSnag