Skip to content

fit

Places content in a box like CSS object-fit and object-position, e.g. to show a design frame in a viewport of another size.

The result is the matrix from content coordinates to box coordinates: its a and d are the scales, e and f the position of the content’s top-left corner. Combine it with multiply, map points with applyToPoint, or write it with matrixToCss. Sizes are expected to be positive.

Available since v3.1.5

import { fit } from '@helpers4/geometry';
// or, from the all-in-one package (same code, one install):
import { fit } from 'helpers4/geometry';
fit(content: Size, box: Size, options: FitOptions): Matrix
ParameterTypeDescription
contentSizeThe size of the content
boxSizeThe size of the box
optionsFitOptionsMode and alignment — see FitOptions

Matrix — The content-to-box matrix

contain (the default) keeps the whole frame visible, centered.

fit({ width: 200, height: 100 }, { width: 100, height: 100 })
// => { a: 0.5, b: 0, c: 0, d: 0.5, e: 0, f: 25 }

Like object-fit: cover; object-position: left.

fit({ width: 200, height: 100 }, { width: 100, height: 100 }, { mode: 'cover', align: { x: 0 } })
// => { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 }

Where fit places content in the space left over (or overflowing), as CSS object-position: 0 is left / top, 0.5 centered, 1 right / bottom.

interface FitAlign {
  x?: number;
  y?: number;
}

Options for fit.

interface FitOptions {
  align?: FitAlign;
  mode?: FitMode;
}

A 2D affine transformation, in the layout of CSS and SVG matrix(a, b, c, d, e, f):

x' = a·x + c·y + e
y' = b·x + d·y + f
interface Matrix {
  a: number;
  b: number;
  c: number;
  d: number;
  e: number;
  f: number;
}

A width and a height.

interface Size {
  height: number;
  width: number;
}

How fit sizes content in a box, as CSS object-fit:

  • 'contain': as large as possible while staying entirely inside (bands remain on two sides);
  • 'cover': as small as possible while covering the whole box (it overflows on two sides);
  • 'fill': stretched to the box on each axis, proportions not kept;
  • 'none': not scaled;
  • 'scale-down': like 'contain', but never enlarged.
type FitMode = 'contain' | 'cover' | 'fill' | 'none' | 'scale-down'

View source on GitHub