Skip to content

Instantly share code, notes, and snippets.

@kolosovsky
Last active February 3, 2024 14:16
Show Gist options
  • Save kolosovsky/b56d90ad3a507876ae2da96e5bb8ff71 to your computer and use it in GitHub Desktop.
Save kolosovsky/b56d90ad3a507876ae2da96e5bb8ff71 to your computer and use it in GitHub Desktop.
The computation of the axis-aligned bounding box (AABB) in JavaScript

The computation of the axis-aligned bounding box (AABB) in JavaScript

Polygon (rectangle, triangle, etc.)

Live demo https://jsfiddle.net/Kolosovsky/tdqv6pk2/

let points = [
	{ x: 125, y: 50 },
	{ x: 250, y: 65 },
	{ x: 300, y: 125 },
	{ x: 175, y: 175 },
	{ x: 100, y: 125 },
];
let minX = Math.min(...points.map(point => point.x));
let minY = Math.min(...points.map(point => point.y));
let maxX = Math.max(...points.map(point => point.x));
let maxY = Math.max(...points.map(point => point.y));
let pivot = {
	x: maxX - ((maxX - minX) / 2),
	y: maxY - ((maxY - minY) / 2)
};
let degrees = 90;
let radians = degrees * (Math.PI / 180);
let cos = Math.cos(radians);
let sin = Math.sin(radians);

function rotatePoint(pivot, point, cos, sin) {
	return {
		x: (cos * (point.x - pivot.x)) - (sin * (point.y - pivot.y)) + pivot.x,
		y: (sin * (point.x - pivot.x)) + (cos * (point.y - pivot.y)) + pivot.y
	};
}

let boundingBox = {
	x1: Number.POSITIVE_INFINITY,
	y1: Number.POSITIVE_INFINITY,
	x2: Number.NEGATIVE_INFINITY,
	y2: Number.NEGATIVE_INFINITY,
};

points.forEach((point) => {
	let rotatedPoint = rotatePoint(pivot, point, cos, sin);

	boundingBox.x1 = Math.min(boundingBox.x1, rotatedPoint.x);
	boundingBox.y1 = Math.min(boundingBox.y1, rotatedPoint.y);
	boundingBox.x2 = Math.max(boundingBox.x2, rotatedPoint.x);
	boundingBox.y2 = Math.max(boundingBox.y2, rotatedPoint.y);
});

Ellipse

Live demo https://jsfiddle.net/Kolosovsky/sLc7ynd1/

let centerX = 350;
let centerY = 100;
let radiusX = 100;
let radiusY = 50;
let degrees = 200;

let radians = degrees * (Math.PI / 180);
let radians90 = radians + Math.PI / 2;
let ux = radiusX * Math.cos(radians);
let uy = radiusX * Math.sin(radians);
let vx = radiusY * Math.cos(radians90);
let vy = radiusY * Math.sin(radians90);

let width = Math.sqrt(ux * ux + vx * vx) * 2;
let height = Math.sqrt(uy * uy + vy * vy) * 2;
let x = centerX - (width / 2);
let y = centerY - (height / 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment