create a bounding ball in javascript

To create a bounding ball in Javascript, you need to calculate the center and radius of the ball. The center is the average position of a collection of points, and the radius is the maximum distance from the center to any of those points.

Assuming you have an array of points with x and y coordinates, you could calculate the center and radius like this:

index.tsx
function getBoundingBall(points) {
  // Calculate the center
  let centerX = 0;
  let centerY = 0;
  for (let i = 0; i < points.length; i++) {
    centerX += points[i].x;
    centerY += points[i].y;
  }
  centerX /= points.length;
  centerY /= points.length;

  // Calculate the radius
  let radius = 0;
  for (let i = 0; i < points.length; i++) {
    let dx = points[i].x - centerX;
    let dy = points[i].y - centerY;
    let distance = Math.sqrt(dx*dx + dy*dy);
    if (distance > radius) {
      radius = distance;
    }
  }

  return {centerX: centerX, centerY: centerY, radius: radius};
}
595 chars
25 lines

Once you have the center and radius, you can draw the bounding ball on a canvas element like this:

index.tsx
let canvas = document.getElementById("myCanvas");
let ctx = canvas.getContext("2d");

ctx.beginPath();
ctx.arc(boundingBall.centerX, boundingBall.centerY, boundingBall.radius, 0, 2*Math.PI);
ctx.stroke();
205 chars
7 lines

This will create a circle with the center and radius of the bounding ball.

gistlibby LogSnag