javascriptgeometrybounding-box

Calculate bounding box width and height from given coordinates(x,y)


I have a list of coordinates

const coords = [{x:10, y:20}, {x:5, y:6}, {x:1, y:25}, {x:11, y:2}];

And I am wondering is there a way to calculate bounding box width and height having only these coordinates?


Solution

  • Using the map() function transform the input array into array of x or y values. You can then feed these transformed arrays to Math.min() and Math.max() to get left, right, bottom and top to compute the bounding box. When you have the bounding box, the width and height calculation is straight forward (subtract min from max). See code snippet below.

    const coords = [{x:10, y:20}, {x:5, y:6}, {x:1, y:25}, {x:11, y:2}];
    const xArr = coords.map(c => c.x);
    const yArr = coords.map(c => c.y);
    
    const l = Math.min(...xArr);
    const r = Math.max(...xArr);
    const b = Math.min(...yArr);
    const t = Math.max(...yArr);
    
    const width  = r - l;
    const height = t - b;
    console.log(width, height);