Core utilities

All of these are re-exported from svelte-advanced-cropper, except getMimeType.

import { approximateSize, getCoefficient, loadImage } from 'svelte-advanced-cropper';

Fitting state parts

fitCoordinates

function fitCoordinates(state: CropperState, settings: CoreSettings): CropperState;

Moves and shrinks the crop until it satisfies the size, aspect ratio and position restrictions and lies inside the visible area.

fitVisibleArea

function fitVisibleArea(state: CropperState, settings: CoreSettings): CropperState;

Gives the visible area the boundary’s aspect ratio, then fits it to the area size and area position restrictions.

getRoundedCoordinates

function getRoundedCoordinates(state: CropperState, settings: CoreSettings): Coordinates | null;

Rounds the crop to whole pixels while keeping it inside the restrictions. cropper.getCoordinates() returns this by default.

Algorithms

The geometry behind the modifiers, working on plain coordinates rather than on a state.

moveCoordinatesAlgorithm

function moveCoordinatesAlgorithm(
	coordinates: Coordinates,
	directions: MoveDirections,
	positionRestrictions: PositionRestrictions
): Coordinates;

Moves the coordinates, then pushes them back inside the position restrictions.

resizeCoordinatesAlgorithm

function resizeCoordinatesAlgorithm(
	coordinates: Coordinates,
	directions: ResizeDirections,
	options: {
		compensate?: boolean;
		preserveAspectRatio?: boolean;
		allowedDirections?: { left?: boolean; right?: boolean; top?: boolean; bottom?: boolean };
		respectDirection?: 'width' | 'height';
	},
	limitations: ResizeLimitations
): Coordinates;

interface ResizeDirections {
	left: number;
	right: number;
	top: number;
	bottom: number;
}

interface ResizeLimitations {
	aspectRatio: AspectRatio;
	sizeRestrictions: SizeRestrictions;
	positionRestrictions: PositionRestrictions;
}

Moves each side of the coordinates outward by the matching amount in directions (negative values move it inward) while respecting the limitations.

anchoredResizeCoordinatesAlgorithm

function anchoredResizeCoordinatesAlgorithm(
	coordinates: Coordinates,
	anchor: ResizeAnchor,
	directions: MoveDirections,
	options: ResizeOptions,
	limitations: ResizeLimitations
): Coordinates;

The handle-based version: converts the drag of the anchor handle into side directions, calls resizeCoordinatesAlgorithm, and keeps the opposite handle where it was in options.reference. Try it on the Resize Algorithm page.

Gestures

touchesToImageTransform

function touchesToImageTransform(
	touches: SimpleTouch[],
	previousTouches: SimpleTouch[],
	container: HTMLElement,
	options?: { rotate?: boolean; move?: boolean; scale?: boolean }
): ImageTransform;

interface SimpleTouch {
	clientX: number;
	clientY: number;
}

Compares two sets of touches and returns the move, scale and rotation between them, relative to container. One finger only moves. Several fingers also scale, and exactly two can rotate. Only the kinds enabled in options are returned.

wheelEventToImageTransform

function wheelEventToImageTransform(
	event: WheelEvent,
	container: HTMLElement,
	ratio?: number
): ImageTransform;

Turns a wheel event into a scale around the pointer. ratio (default 0.1) is the zoom step per wheel tick.

Canvas

drawCroppedArea

function drawCroppedArea(
	state: CropperState,
	image: HTMLImageElement | HTMLCanvasElement,
	resultCanvas: HTMLCanvasElement,
	spareCanvas: HTMLCanvasElement,
	options: DrawOptions
): HTMLCanvasElement | null;

interface DrawOptions {
	width?: number;
	height?: number;
	minWidth?: number;
	maxWidth?: number;
	minHeight?: number;
	maxHeight?: number;
	maxArea?: number;
	imageSmoothingQuality?: 'low' | 'medium' | 'high';
	imageSmoothingEnabled?: boolean;
	fillColor?: string;
}

Draws the crop into resultCanvas. spareCanvas is used to pre-render the rotated or flipped image. The output keeps the crop’s aspect ratio: width and height set an exact size, the min*/max* options bound it, and maxArea caps the pixel count. cropper.getCanvas(options) calls this with the same options.

Normalization

The cropper’s gestures arrive in screen pixels, while the state is in image pixels. These convert one to the other by multiplying by the coefficient.

normalizeMoveDirections

function normalizeMoveDirections(
	state: CropperState,
	directions: Partial<MoveDirections>
): MoveDirections;

normalizeResizeDirections

function normalizeResizeDirections(
	state: CropperState,
	directions: Partial<ResizeDirections>
): ResizeDirections;

normalizeImageTransform

function normalizeImageTransform(state: CropperState, transform: ImageTransform): ImageTransform;

Converts the move and the scale and rotation centres of an image transform. Note that it changes the object you pass in.

normalizeCenter

function normalizeCenter(state: CropperState, center: Point): Point;

Converts a point in the boundary to a point in the image.

normalizeFlip

function normalizeFlip(state: CropperState, flip: Flip): Flip;

Swaps a horizontal and a vertical flip when the image is rotated by about 90°, so that “horizontal” always means horizontal on screen.

Getters

The settings fields can be values or functions. These resolve them for a given state.

getSizeRestrictions

function getSizeRestrictions(state: CropperState, settings: CoreSettings): SizeRestrictions;

Missing values are filled with 0 and Infinity, and the maximums are capped by the position restrictions.

getPositionRestrictions

function getPositionRestrictions(state: CropperState, settings: CoreSettings): PositionRestrictions;

getAreaSizeRestrictions

function getAreaSizeRestrictions(state: CropperState, settings: CoreSettings): AreaSizeRestrictions;

getAreaPositionRestrictions

function getAreaPositionRestrictions(
	state: CropperState,
	settings: CoreSettings
): AreaPositionRestrictions;

getAspectRatio

function getAspectRatio(state: CropperState, settings: CoreSettings): AspectRatio;

Always returns { minimum, maximum }, with 0 and Infinity for missing bounds.

getDefaultCoordinates

function getDefaultCoordinates(
	state: CropperState,
	settings: CoreSettings & InitializeSettings
): CoordinatesTransform | CoordinatesTransform[];

getDefaultVisibleArea

function getDefaultVisibleArea(
	state: CropperState,
	settings: CoreSettings & InitializeSettings
): VisibleArea;

getCoefficient

function getCoefficient(state: CropperState): number;

How many image pixels one screen pixel covers: visibleArea.width / boundary.width.

getStencilCoordinates

function getStencilCoordinates(state: CropperState | null): Coordinates;

The crop in boundary pixels, which is where the stencil is drawn. All zeros when the state isn’t initialized.

getTransformedImageSize

function getTransformedImageSize(state: CropperState): Size;

The bounding size of the rotated image. Restrictions are expressed in this frame.

getMinimumSize

function getMinimumSize(state: CropperState): number;

The smallest size, in image pixels, that a resize may produce: about 20 screen pixels, so the handles stay usable.

isConsistentState

function isConsistentState(state: CropperState, settings: CoreSettings): boolean;

Whether the state already satisfies the settings, which means reconcileState would leave it unchanged.

Image

loadImage

function loadImage(
	src: string,
	settings?: { crossOrigin?: string | boolean; checkOrientation?: boolean; parse?: boolean }
): Promise<CropperImage>;

Loads an image and resolves with a CropperImage. With checkOrientation, it reads the JPEG’s EXIF orientation, returns it as transforms, and serves a copy of the image with the orientation tag cleared. crossOrigin is set on the image element (true means 'anonymous'). The promise rejects if the image fails to load. The cropper manages loading state and object-URL cleanup for its own loads.

getBackgroundStyle

function getBackgroundStyle(
	image: CropperImage,
	state: CropperState,
	transitions?: CropperTransitions | null
): Record<string, string>;

The inline style that positions the image inside the boundary for the current visible area, including the CSS transition when transitions.active is set. CropperBackgroundImage uses it.

getPreviewStyle

function getPreviewStyle(
	image: CropperImage,
	state: CropperState,
	size: Size,
	transitions?: CropperTransitions | null
): Record<string, string>;

The same for a preview of size that shows only the crop. CropperPreview uses it.

getImageStyle

function getImageStyle(
	image: CropperImage,
	state: CropperState,
	area: Coordinates,
	coefficient: number,
	transitions?: CropperTransitions | null
): Record<string, string>;

The general form of the two above: the style that shows area of the image at the given scale.

These styles are objects with camelCase keys such as willChange. In Svelte, convert them to a style string before using them.

getMimeType

import { getMimeType } from 'advanced-cropper/extensions/mimes';
function getMimeType(
	data: ArrayBuffer | string | null | undefined,
	fallback?: string | null
): string | undefined;

Detects an image’s MIME type from its first bytes, for example from CropperImage.arrayBuffer. This one lives in a separate core entry point and is not re-exported, so install advanced-cropper as a direct dependency to import it.

Size

approximateSize

function approximateSize(params: {
	width: number;
	height: number;
	sizeRestrictions?: SizeRestrictions;
	aspectRatio?: RawAspectRatio;
}): Size;

Finds the size closest to width × height that satisfies both the size restrictions and the aspect ratio.

State

isEqualState

function isEqualState(a: CropperState | null, b: CropperState | null): boolean;

Compares two states deeply, treating numbers that differ by less than 0.001 as equal. See the FAQ for an example.

copyState

function copyState<T extends CropperState | null>(state: T): T;

A deep copy.

Restrictions

getBrokenRatio

function getBrokenRatio(currentAspectRatio: number, aspectRatio: AspectRatio): number | undefined;

If currentAspectRatio is outside the allowed range, returns the bound it broke. Otherwise returns undefined.

fitToSizeRestrictions

function fitToSizeRestrictions(size: Size, sizeRestrictions: SizeRestrictions): number;

The scale factor that brings size within the restrictions while keeping its ratio (1 if it already fits).

resizeToSizeRestrictions

function resizeToSizeRestrictions(
	coordinates: Coordinates,
	sizeRestrictions: SizeRestrictions
): Coordinates;

Applies that scale factor.

mergeSizeRestrictions

function mergeSizeRestrictions(a: SizeRestrictions, b: Partial<SizeRestrictions>): SizeRestrictions;

The intersection of two size restrictions.

positionToSizeRestrictions

function positionToSizeRestrictions(positionRestrictions: PositionRestrictions): SizeRestrictions;

The largest size that fits between the position restrictions.

mergePositionRestrictions

function mergePositionRestrictions(
	a: PositionRestrictions,
	b: PositionRestrictions
): PositionRestrictions;

The intersection of two position restrictions: the tighter value for each side.

fitToPositionRestrictions

function fitToPositionRestrictions(
	coordinates: Coordinates,
	positionRestrictions: PositionRestrictions
): MoveDirections;

The move that brings the coordinates inside the restrictions.

moveToPositionRestrictions

function moveToPositionRestrictions(
	coordinates: Coordinates,
	positionRestrictions: PositionRestrictions
): Coordinates;

Applies that move.

coordinatesToPositionRestrictions

function coordinatesToPositionRestrictions(coordinates: Coordinates): PositionRestrictions;

Position restrictions that keep something inside the given rectangle.

Geometry

rotateSize

function rotateSize(size: Size, angle: number): Size;

The bounding size of size rotated by angle degrees.

rotatePoint

function rotatePoint(point: Point, angle: number, anchor?: Point): Point;

Rotates a point by angle degrees around anchor, or around the origin.

diff

function diff(firstObject: Point, secondObject: Point): Diff;

firstObject - secondObject, per axis.

sizeDistance

function sizeDistance(a: Size, b: Size): number;

How different two sizes are, used to choose the closest candidate.

getCenter

function getCenter(object: Coordinates): Point;

getIntersections

function getIntersections(
	object: Coordinates,
	positionRestrictions: PositionRestrictions
): Intersections;

How far each side of object crosses the restrictions (0 when it doesn’t).

applyDirections

function applyDirections(coordinates: Coordinates, directions: ResizeDirections): Coordinates;

Moves each side outward by the matching direction.

applyMove

function applyMove(object: Coordinates, move: MoveDirections): Coordinates;

inverseMove

function inverseMove(directions: MoveDirections): MoveDirections;

applyScale

function applyScale(
	object: Coordinates,
	factor: number,
	center?: Point,
	progress?: number
): Coordinates;

Scales a rectangle by factor around center (its own centre by default).

ratio

function ratio(object: Size): number;

width / height.

maxScale

function maxScale(size: Size, restrictions: SizeRestrictions): number;

The largest factor size can be scaled by without breaking the maximums.

minScale

function minScale(size: Size, restrictions: SizeRestrictions): number;

The smallest factor size can be scaled by without breaking the minimums.

Math

isRoughlyEqual

function isRoughlyEqual(a: number, b: number, tolerance?: number): boolean;

true when the numbers differ by less than tolerance (default 1e-3).

isGreater

function isGreater(a: number, b: number, tolerance?: number): boolean;

a > b, ignoring differences within the tolerance.

isLower

function isLower(a: number, b: number, tolerance?: number): boolean;

a < b, ignoring differences within the tolerance.

getCloserAngle

function getCloserAngle(reference: number, angle: number): number;

The angle equivalent to angle (plus or minus whole turns) that is closest to reference. See the FAQ for why this is useful.