General purpose, parallelogram style rectangle library.
A way to describe and manipulate any 2D (also rotated) rectangle.
- Every rectangle can be fully described by only 3 points - which i call here origin (top-left), right (top-right), bottom (bottom-left). Everything else is based and calculated using those points.
- Rectangles have it's initial (here called stashed) dimensions and then can be transformed by applying matrix. You can apply transforms only to initial values. But any transformed state can be stashed (made a new initial state). In other words transforms are just a projections. Note however that all rectangle's properties are always "real", so if rectangle with width of 100 is scaled by factor 2, then the width becomes 200.
- The main purpose (or need why i wrote this) is to build virtual layout library. One can add rectangles onto virtual pasteboard and then translate and scale (also rotate) that inside a viewport.
$ npm install @atirip/rectangle
Or clone this repo.
It has @atirip/matrix as submodule
import {Rectangle} from './rectangle.js';
Creates new rectangle. Initial values are stashed automatically.
Parameters can be:
- x, y, width, height
- Numbers
- width, height
-
Numbers, x and y are set to
0
- origin, right, bottom
-
Points
{x:, y:}
- rectangle, toClone
-
Instance of a Rectangle, Boolean. If
toClone
is true, then exact clone is created - stashed values are copied over, not created from initial values.
- x, y, width, height
- Numbers. The obvious ones. Setter and getter.
- cx, cy
-
Numbers. Center of the rectangle in absolute coordinates -
10,10,100,100
rectangle's center is45,45
. Only getter. - matrix
- Instance of Matrix (https://github.com/atirip/matrix). Only getter.
- sx, sy, angle
- Numbers. Scale and angle of currently applied matrix. Only getter.
- bounds
-
Special instance of Rectangle. Bounding box of a rectangle, immutable, has only getters for
x, y, width, height, cx, cy
.
returns Boolean.
- rectangle
- Instance of a Rectangle to compare with
- precision
- Float. If omitted, 1E-6 is used. Difference less or equal to precision is considered equal.
Matrix transform results suffer often from rounding and comparing floats is not exact.
Save current dimensions as initial ones.
- x, y, width, height
- Numbers. Apply all new dimensions to the Rectangle
- matrix
- Instance of Matrix (https://github.com/atirip/matrix). Apply that matrix to rectangle.
Transform to explicit values given.
- originX, originY, x, y, sx, angle, sy
-
Numbers. Scale, rotate rectangle over specified origin, then translate. The most usual case is uniform scaling, therefore
sy
is the last parameter and if omittedsx
is used forsy
.
Apply values passe to existing ones. For example if angle is 45 and 2 is passed, new angle will be 47. Scaling values are multiplied, if sx is 2 and 0.8 is passed, new sx will be 1.6. Otherwise same as absTransform
.
$ npm test
Copyright © 2015 Priit Pirita, released under the MIT license.