Skip to content

largestRect

Finds the largest rectangle that fits inside a given polygon, optimizing for area across configurable rotations and aspect ratios.

An angle of zero means that the longer side of the polygon (the width) will be aligned with the x axis. An angle of 90 and/or -90 means that the longer side of the polygon (the width) will be aligned with the y axis. The value can be a number between -90 and 90 specifying the angle of rotation of the polygon, a string which is parsed to a number, or an array of numbers specifying the possible rotations of the polygon.

Searches for the largest rectangle that fits inside a polygon, trying a range of angles and aspect ratios from several starting points. The result carries the rectangle’s points, center, angle, and area. Treemap and Geomap use it to find room for a label inside an irregular shape. The search starts from random origins, so repeated runs can land on slightly different rectangles.

import {largestRect} from "@d3plus/math";

const poly = [
  [30, 60],
  [120, 15],
  [230, 40],
  [245, 150],
  [150, 190],
  [40, 165],
];
largestRect(poly);

angle restricts the candidate orientations, here to horizontal only, which is what text labels need. It accepts a single angle in degrees or an array of them.

import {largestRect} from "@d3plus/math";

const poly = [
  [30, 60],
  [120, 15],
  [230, 40],
  [245, 150],
  [150, 190],
  [40, 165],
];
largestRect(poly, {angle: 0});

origin makes the rectangle grow from a specific point instead of random starting points, which makes the result deterministic and lets a label be centered on a chosen spot.

import {largestRect} from "@d3plus/math";

const poly = [
  [30, 60],
  [120, 15],
  [230, 40],
  [245, 150],
  [150, 190],
  [40, 165],
];
largestRect(poly, {origin: [140, 100], angle: 0});

aspectRatio fixes width over height, so the search returns the largest square instead of the largest rectangle. minAspectRatio and maxAspectRatio bound the search instead of pinning it.

import {largestRect} from "@d3plus/math";

const poly = [
  [30, 60],
  [120, 15],
  [230, 40],
  [245, 150],
  [150, 190],
  [40, 165],
];
largestRect(poly, {aspectRatio: 1});

Parameters

import {largestRect} from "@d3plus/math";
polyrequiredArray.<Point>

An Array of points that represent a polygon.

optionsLargestRectOptionsDefault {}

An Object that allows for overriding various parameters of the algorithm.