@core-graphics/rect
Version:
JS utilities for managing rects
69 lines (63 loc) • 1.69 kB
JavaScript
import { Point } from '@core-graphics/point';
import { intersects } from '../../intersection/dist/core-graphics-rect-intersection.esm.js';
import { R as Rect } from '../../dist/lite-3fdd983e.esm.js';
import '@core-graphics/size';
/* -----------------------------------------------------------------------------
* Distance methods
* -----------------------------------------------------------------------------*/
/**
* Returns the distance of a rect from a point
*/
function distanceFromPoint(r, p) {
var x = 0;
var y = 0;
if (p.x < r.x) x = r.x - p.x;else if (p.x > r.maxX) x = p.x - r.maxX;
if (p.y < r.y) y = r.y - p.y;else if (p.y > r.maxY) y = p.y - r.maxY;
return {
x: x,
y: y,
value: Point.distance({
x: x,
y: y
})
};
}
/**
* Returns the distance of a rect from another rect
*/
function distanceFromRect(rA, v) {
var rB = Rect.cast(v);
if (intersects(rA, rB)) return {
x: 0,
y: 0,
value: 0
};
var left = rA.x < rB.x ? rA : rB;
var right = rB.x < rA.x ? rA : rB;
var x = left.x === right.x ? 0 : right.x - left.maxX;
x = Math.max(0, x);
var upper = rA.y < rB.y ? rA : rB;
var lower = rB.y < rA.y ? rA : rB;
var y = upper.y === lower.y ? 0 : lower.y - upper.maxY;
y = Math.max(0, y);
return {
x: x,
y: y,
value: Point.distance({
x: x,
y: y
})
};
}
/**
* Returns the inner distance between an outer rect and an inner rect
*/
function edgeDistance(outer, inner) {
return {
left: inner.x - outer.x,
top: inner.y - outer.y,
right: outer.maxX - inner.maxX,
bottom: outer.maxY - inner.maxY
};
}
export { distanceFromPoint, distanceFromRect, edgeDistance };