### Start or Build Application
Source: https://github.com/alexbol99/flatten-js/blob/master/examples/create-react-app/README.md
After everything will be installed, run npm start or npm build.
```bash
npm start
```
```bash
npm build
```
--------------------------------
### Install Dependencies
Source: https://github.com/alexbol99/flatten-js/blob/master/examples/create-react-app/README.md
Clone the project and then run npm install.
```bash
npm install
```
--------------------------------
### Face Constructor Example
Source: https://github.com/alexbol99/flatten-js/blob/master/docs/Face.html
Demonstrates how to iterate over the edges of a face using either the 'next' iterator or by traversing the linked list starting from face.first.
```javascript
// Face implements "next" iterator which enables to iterate edges in for loop:
for (let edge of face) {
console.log(edge.shape.length) // do something
}
// Instead, it is possible to iterate edges as linked list, starting from face.first:
let edge = face.first;
do {
console.log(edge.shape.length); // do something
edge = edge.next;
} while (edge != face.first)
```
--------------------------------
### Installation
Source: https://github.com/alexbol99/flatten-js/blob/master/docs/index.html
Install the flatten-js core package using npm.
```bash
npm install --save @flatten-js/core
```
--------------------------------
### Example Construction
Source: https://github.com/alexbol99/flatten-js/blob/master/docs/index.html
Create geometric shapes and find their intersections.
```javascript
// extract object creators
import {point, circle, segment} from '@flatten-js/core';
// make some construction
let s1 = segment(10,10,200,200);
let s2 = segment(10,160,200,30);
let c = circle(point(200, 110), 50);
let ip = s1.intersect(s2);
```
--------------------------------
### Serialization Example
Source: https://github.com/alexbol99/flatten-js/blob/master/docs/index.html
Demonstrates how to serialize a flatten-js line object using JSON.stringify and reconstruct it using JSON.parse.
```javascript
let {lint, point} = Flatten;
let l = line(point(4, 0), point(0, 4));
// Serialize
let str = JSON.stringify(l);
// Parse and reconstruct
let l_json = JSON.parse(str);
let l_parsed = line(l_json);
```
--------------------------------
### Matrix Class Methods
Source: https://github.com/alexbol99/flatten-js/blob/master/docs/classes_matrix.js.html
Examples of scale and equalTo methods for the Matrix class.
```javascript
scale(sx, sy) {
return this.multiply(new Matrix(sx, 0, 0, sy, 0, 0));
};
equalTo(matrix) {
if (!Flatten.Utils.EQ(this.tx, matrix.tx)) return false;
if (!Flatten.Utils.EQ(this.ty, matrix.ty)) return false;
if (!Flatten.Utils.EQ(this.a, matrix.a)) return false;
if (!Flatten.Utils.EQ(this.b, matrix.b)) return false;
if (!Flatten.Utils.EQ(this.c, matrix.c)) return false;
if (!Flatten.Utils.EQ(this.d, matrix.d)) return false;
return true;
};
```
--------------------------------
### Serialization Example
Source: https://github.com/alexbol99/flatten-js/blob/master/README.md
Demonstrates how to serialize and deserialize flatten-js objects using JSON.stringify and JSON.parse.
```javascript
let {lint, point} = Flatten;
let l = line(point(4, 0), point(0, 4));
// Serialize
let str = JSON.stringify(l);
// Parse and reconstruct
let l_json = JSON.parse(str);
let l_parsed = line(l_json);
```
--------------------------------
### Example usage
Source: https://github.com/alexbol99/flatten-js/blob/master/README.md
Creating some geometric constructions using imported creators.
```javascript
// extract object creators
import {point, circle, segment} from '@flatten-js/core';
// make some construction
let s1 = segment(10,10,200,200);
let s2 = segment(10,160,200,30);
let c = circle(point(200, 110), 50);
let ip = s1.intersect(s2);
```
--------------------------------
### Browser Usage
Source: https://github.com/alexbol99/flatten-js/blob/master/examples/browser/index.html
This snippet shows how to use flatten-js in a browser to create geometric shapes and find their intersections, then render them as SVG.
```javascript
const Flatten = globalThis["@flatten-js/core"];
const {point, circle, segment} = Flatten;
// make some construction
let s1 = segment(10,10,200,200);
let s2 = segment(10,160,200,30);
let c = circle(point(200, 110), 50);
let ip = s1.intersect(s2);
document.getElementById("stage").innerHTML = s1.svg() + s2.svg() + c.svg() + ip[0].svg();
```
--------------------------------
### Tangent Vector in Start Point
Source: https://github.com/alexbol99/flatten-js/blob/master/docs/classes_arc.js.html
The `tangentInStart` method calculates and returns the unit tangent vector at the starting point of the arc, directed from start to end.
```javascript
/**
* Return tangent unit vector in the start point in the direction from start to end
* @returns {Vector}
*/
tangentInStart() {
let vec = new Flatten.Vector(this.pc, this.start);
let angle = this.counterClockwise ? Math.PI / 2. : -Math.PI / 2.;
return vec.rotate(angle).normalize();
}
```
--------------------------------
### ES Modules Usage
Source: https://github.com/alexbol99/flatten-js/blob/master/examples/es6-module/index.html
This snippet shows how to import and use flatten-js components within an ES Module.
```javascript
import {point, circle, segment} from "https://unpkg.com/@flatten-js/core?module"; // make some construction let s1 = segment(10,10,200,200); let s2 = segment(10,160,200,30); let c = circle(point(200, 110), 50); let ip = s1.intersect(s2); document.getElementById("stage").innerHTML = s1.svg() + s2.svg() + c.svg() + ip[0].svg();
```
--------------------------------
### Visualization Example
Source: https://github.com/alexbol99/flatten-js/blob/master/docs/index.html
Shows how to use the svg() method to render flatten-js shapes (segment, circle) within an SVG element.
```html
```
--------------------------------
### Arc Start Point Getter
Source: https://github.com/alexbol99/flatten-js/blob/master/docs/classes_arc.js.html
Returns the starting point of the arc as a Flatten.Point object.
```javascript
get start() {
let p0 = new Flatten.Point(this.pc.x + this.r, this.pc.y);
return p0.rotate(this.startAngle, this.pc);
}
```
--------------------------------
### getChain Method
Source: https://github.com/alexbol99/flatten-js/blob/master/docs/classes_multiline.js.html
Retrieves a sequence of edges from a starting edge up to (but not including) the next edge of the target edge.
```javascript
getChain(edgeFrom, edgeTo) {
let edges = []
for (let edge = edgeFrom; edge !== edgeTo.next; edge = edge.next) {
edges.push(edge)
}
return edges
}
```
--------------------------------
### Boolean Operations
Source: https://github.com/alexbol99/flatten-js/blob/master/docs/index.html
Example of using boolean operations like unify, subtract, and intersect.
```javascript
let {unify, subtract, intersect, innerClip, outerClip} = BooleanOperations;
```
--------------------------------
### Visualization Example
Source: https://github.com/alexbol99/flatten-js/blob/master/README.md
Shows how to use the svg() method to generate SVG strings for flatten-js objects and insert them into an HTML document.
```html
```
--------------------------------
### Box.toPoints Method
Source: https://github.com/alexbol99/flatten-js/blob/master/docs/classes_box.js.html
Converts the box into an array of four points, starting from the bottom-left corner in counterclockwise order.
```javascript
toPoints() {
return [
new Flatten.Point(this.xmin, this.ymin),
new Flatten.Point(this.xmax, this.ymin),
new Flatten.Point(this.xmax, this.ymax),
new Flatten.Point(this.xmin, this.ymax)
];
}
```
--------------------------------
### Spatial Relationship Predicates
Source: https://github.com/alexbol99/flatten-js/blob/master/README.md
Example of using spatial relationship predicates like intersect, disjoint, equal, etc.
```javascript
let {intersect, disjoint, equal, touch, inside, contain, covered, cover} = Flatten.Relations;
// define shape a and shape b
let p = intersect(a, b);
console.log(p) // true / false
```
--------------------------------
### Iterating edges in a face using linked list traversal
Source: https://github.com/alexbol99/flatten-js/blob/master/docs/classes_face.js.html
It is possible to iterate edges as a linked list, starting from face.first.
```javascript
let edge = face.first;
do {
console.log(edge.shape.length); // do something
edge = edge.next;
} while (edge != face.first)
```
--------------------------------
### Boolean Operations
Source: https://github.com/alexbol99/flatten-js/blob/master/README.md
Example of using boolean operations like unify, subtract, intersect, innerClip, and outerClip.
```javascript
let {unify, subtract, intersect, innerClip, outerClip} = BooleanOperations;
```
--------------------------------
### Face Constructor
Source: https://github.com/alexbol99/flatten-js/blob/master/docs/classes_face.js.html
Initializes a Face object. It can be initialized with a box, or with two edges representing the start and end of the face loop. The latter is used in boolean operations.
```javascript
if (args.length === 2 && args[0] instanceof Flatten.Edge && args[1] instanceof Flatten.Edge) {
this.first = args[0]; // first edge in face or undefined
this.last = args[1]; // last edge in face or undefined
this.last.next = this.first;
this.first.prev = this.last;
// set arc length
this.setArcLength();
// this.box = this.getBox();
// this.orientation = this.getOrientation(); // face direction cw or ccw
}
```
--------------------------------
### Rotate segment by 45 deg around its center
Source: https://github.com/alexbol99/flatten-js/blob/master/README.md
Example demonstrating how to rotate a segment by a specified angle around its center using the `rotate` method.
```javascript
let {point,segment,matrix} = Flatten;
let s = segment(point(20,30), point(60,70));
let center = s.box.center;
let angle = 45.*Math.PI/180.;
let rotated_segment = s.rotate(angle, center)
```
--------------------------------
### Tangent Vector Calculation
Source: https://github.com/alexbol99/flatten-js/blob/master/docs/classes_segment.js.html
Methods to get the unit tangent vector at the start and end points of the segment.
```javascript
tangentInStart() {
let vec = new Flatten.Vector(this.start, this.end);
return vec.normalize();
}
tangentInEnd() {
let vec = new Flatten.Vector(this.end, this.start);
return vec.normalize();
}
```
--------------------------------
### Point Constructor
Source: https://github.com/alexbol99/flatten-js/blob/master/docs/classes_point.js.html
Demonstrates the different ways to construct a Point object, including using two numbers, an array of two numbers, or an object with x and y properties.
```javascript
import Flatten from '../flatten';
import {convertToString} from "../utils/attributes";
import {Matrix} from "./matrix";
import {Shape} from "./shape";
import {Errors} from "../utils/errors";
/**
*
* Class representing a point
* @type {Point}
*/
export class Point extends Shape {
/**
* Point may be constructed by two numbers, or by array of two numbers
* @param {number} x - x-coordinate (float number)
* @param {number} y - y-coordinate (float number)
*/
constructor(...args) {
super()
/**
* x-coordinate (float number)
* @type {number}
*/
this.x = 0;
/**
* y-coordinate (float number)
* @type {number}
*/
this.y = 0;
if (args.length === 0) {
return;
}
if (args.length === 1 && args[0] instanceof Array && args[0].length === 2) {
let arr = args[0];
if (typeof (arr[0]) == "number" && typeof (arr[1]) == "number") {
this.x = arr[0];
this.y = arr[1];
return;
}
}
if (args.length === 1 && args[0] instanceof Object && args[0].name === "point") {
let {x, y} = args[0];
this.x = x;
this.y = y;
return;
}
if (args.length === 2) {
if (typeof (args[0]) == "number" && typeof (args[1]) == "number") {
this.x = args[0];
this.y = args[1];
return;
}
}
throw Errors.ILLEGAL_PARAMETERS;
}
/**
* Returns bounding box of a point
* @returns {Box}
*/
get box() {
return new Flatten.Box(this.x, this.y, this.x, this.y);
}
/**
* Return new cloned instance of point
* @returns {Point}
*/
clone() {
return new Flatten.Point(this.x, this.y);
}
get vertices() {
return [this.clone()];
}
/**
* Returns true if points are equal up to [Flatten.Utils.DP_TOL]{@link DP_TOL} tolerance
* @param {Point} pt Query point
* @returns {boolean}
*/
equalTo(pt) {
return Flatten.Utils.EQ(this.x, pt.x) && Flatten.Utils.EQ(this.y, pt.y);
}
/**
* Defines predicate "less than" between points. Returns true if the point is less than query points, false otherwise
* By definition point1 < point2 if {point1.y < point2.y || point1.y == point2.y && point1.x < point2.x
* Numeric values compared with [Flatten.Utils.DP_TOL]{@link DP_TOL} tolerance
* @param {Point} pt Query point
* @returns {boolean}
*/
lessThan(pt) {
if (Flatten.Utils.LT(this.y, pt.y))
return true;
if (Flatten.Utils.EQ(this.y, pt.y) && Flatten.Utils.LT(this.x, pt.x))
return true;
return false;
}
/**
* Return new point transformed by affine transformation matrix
* @param {Matrix} m - affine transformation matrix (a,b,c,d,tx,ty)
* @returns {Point}
*/
transform(m) {
return new Flatten.Point(m.transform([this.x, this.y]))
}
/**
* Returns projection point on given line
* @param {Line} line Line this point be projected on
* @returns {Point}
*/
projectionOn(line) {
if (this.equalTo(line.pt)) // this point equal to line anchor point
return this.clone();
let vec = new Flatten.Vector(this, line.pt);
if (Flatten.Utils.EQ_0(vec.cross(line.norm))) // vector to point from anchor point collinear to normal vector
return line.pt.clone();
let dist = vec.dot(line.norm); // signed distance
let proj_vec = line.norm.multiply(dist);
return this.translate(proj_vec);
}
/**
* Returns true if point belongs to the "left" semi-plane, which means, point belongs to the same semi plane where line normal vector points to
* Return false if point belongs to the "right" semi-plane or to the line itself
* @param {Line} line Query line
* @returns {boolean}
*/
leftTo(line) {
let vec = new Flatten.Vector(line.pt, this);
let onLeftSemiPlane = Flatten.Utils.GT(vec.dot(line.norm), 0);
return onLeftSemiPlane;
}
/**
```
--------------------------------
### Importing shortcuts
Source: https://github.com/alexbol99/flatten-js/blob/master/README.md
Using shortcuts to avoid the 'new' constructor for some classes.
```javascript
import {point, vector, circle, line, ray, segment, arc, polygon, matrix} from '@flatten-js/core';
```
--------------------------------
### Ray.split Method
Source: https://github.com/alexbol99/flatten-js/blob/master/docs/classes_ray.js.html
Splits the ray at a given point. If the point is on the ray, it returns an array containing a segment from the ray's start to the point, and a new ray starting from the point with the same normal vector. If the point is the ray's start point, it returns the ray itself. If the point is not on the ray, it returns an empty array.
```javascript
split(pt) {
if (!this.contains(pt))
return [];
if (this.pt.equalTo(pt)) {
return [this]
}
return [
new Flatten.Segment(this.pt, pt),
new Flatten.Ray(pt, this.norm)
]
}
```
--------------------------------
### Segment Reversal
Source: https://github.com/alexbol99/flatten-js/blob/master/docs/classes_segment.js.html
A method to create a new segment with the start and end points swapped.
```javascript
reverse() {
return new Segment(this.end, this.start);
}
```
--------------------------------
### Arc pointAtLength method
Source: https://github.com/alexbol99/flatten-js/blob/master/docs/classes_arc.js.html
Returns the point on the arc at a specified distance from the start of the arc.
```javascript
pointAtLength(length) {
if (length > this.length || length < 0) return null;
if (length === 0) return this.start;
if (length === this.length) return this.end;
let factor = length / this.length;
let endAngle = this.counterClockwise ? this.startAngle + this.sweep * factor : this.startAngle - this.sweep * factor;
let arc = new Flatten.Arc(this.pc, this.r, this.startAngle, endAngle, this.counterClockwise);
return arc.end;
}
```
--------------------------------
### Arc Vertices Getter
Source: https://github.com/alexbol99/flatten-js/blob/master/docs/classes_arc.js.html
Returns an array containing the start and end points of the arc.
```javascript
get vertices() {
return [this.start.clone(), this.end.clone()];
}
```
--------------------------------
### Point Class Methods
Source: https://github.com/alexbol99/flatten-js/blob/master/docs/classes_point.js.html
This section lists the available methods for the Point class, including clone, distanceTo, equalTo, leftTo, lessThan, on, projectionOn, and svg.
```javascript
F[clone](Point.html#clone)
F[distanceTo](Point.html#distanceTo)
F[equalTo](Point.html#equalTo)
F[leftTo](Point.html#leftTo)
F[lessThan](Point.html#lessThan)
F[on](Point.html#on)
F[projectionOn](Point.html#projectionOn)
F[svg](Point.html#svg)
```
--------------------------------
### Point at Specific Length
Source: https://github.com/alexbol99/flatten-js/blob/master/docs/classes_segment.js.html
Retrieves the point located at a specified distance along the segment from its start point.
```javascript
pointAtLength(length) {
if (length > this.length || length < 0) return null;
if (length == 0) return this.start;
if (length == this.length) return this.end;
let factor = length / this.length;
```
--------------------------------
### Clone Method
Source: https://github.com/alexbol99/flatten-js/blob/master/docs/classes_box.js.html
Returns a new cloned instance of the box.
```javascript
/**
* Return new cloned instance of box
* @returns {Box}
*/
clone() {
return new Box(this.xmin, this.ymin, this.xmax, this.ymax);
}
```
--------------------------------
### Box Constructor
Source: https://github.com/alexbol99/flatten-js/blob/master/docs/classes_box.js.html
Initializes a new Box instance with optional minimum and maximum coordinates.
```javascript
"use strict";
import Flatten from '../flatten';
import {convertToString} from "../utils/attributes";
import {Shape} from "./shape";
import {Errors} from "../utils/errors";
import {intersectSegment2Arc} from "../algorithms/intersection";
/**
* Class Box represents bounding box of the shape.
* It may also represent axis-aligned rectangle
* @type {Box}
*/
export class Box extends Shape {
/**
*
* @param {number} xmin - minimal x coordinate
* @param {number} ymin - minimal y coordinate
* @param {number} xmax - maximal x coordinate
* @param {number} ymax - maximal y coordinate
*/
constructor(xmin = undefined, ymin = undefined, xmax = undefined, ymax = undefined) {
super()
/**
* Minimal x coordinate
* @type {number}
*/
this.xmin = xmin;
/**
* Minimal y coordinate
* @type {number}
*/
this.ymin = ymin;
/**
* Maximal x coordinate
* @type {number}
*/
this.xmax = xmax;
/**
* Maximal y coordinate
* @type {number}
*/
this.ymax = ymax;
}
```
--------------------------------
### Polygon Orientation Check
Source: https://github.com/alexbol99/flatten-js/blob/master/docs/classes_polygon.js.html
Gets the orientation of the polygon based on its first face, assuming proper arrangement.
```javascript
/**
* Helper method to get orientation of the polygon as the first face orientation
* Assume that polygon is properly arranged and the first face is the outer face
* @returns {Flatten.ORIENTATION.PolygonOrientationType}
*/
orientation() {
if (this.isEmpty()) return ORIENTATION.NOT_ORIENTABLE
return [...this.faces][0].orientation();
}
```
--------------------------------
### Arc Constructor
Source: https://github.com/alexbol99/flatten-js/blob/master/docs/classes_arc.js.html
Demonstrates the different ways to instantiate an Arc object, including passing an object with arc properties or individual parameters.
```javascript
import Flatten from '../flatten';
import {Shape} from "./shape";
export class Arc extends Shape {
constructor(...args) {
super()
this.pc = new Flatten.Point();
this.r = 1;
this.startAngle = 0;
this.endAngle = 2 * Math.PI;
this.counterClockwise = true;
if (args.length === 0)
return;
if (args.length === 1 && args[0] instanceof Object && args[0].name === "arc") {
let {pc, r, startAngle, endAngle, counterClockwise} = args[0];
this.pc = new Flatten.Point(pc.x, pc.y);
this.r = r;
this.startAngle = startAngle;
this.endAngle = endAngle;
this.counterClockwise = counterClockwise;
} else {
let [pc, r, startAngle, endAngle, counterClockwise] = [...args];
if (pc && pc instanceof Flatten.Point) this.pc = pc.clone();
if (r !== undefined) this.r = r;
if (startAngle !== undefined) this.startAngle = startAngle;
if (endAngle !== undefined) this.endAngle = endAngle;
if (counterClockwise !== undefined) this.counterClockwise = counterClockwise;
}
}
}
```
--------------------------------
### Line Constructor and Export
Source: https://github.com/alexbol99/flatten-js/blob/master/docs/classes_line.js.html
This snippet shows how to create a new Line object and export a helper function for it.
```javascript
Flatten.Line = Line;
/**
* Function to create line equivalent to "new" constructor
* @param args
*/
export const line = (...args) => new Flatten.Line(...args);
Flatten.line = line;
```
--------------------------------
### Floating Point Comparison Functions
Source: https://github.com/alexbol99/flatten-js/blob/master/docs/utils_utils.js.html
This section provides utility functions for comparing floating-point numbers with a configurable tolerance.
```javascript
/**
* Floating point comparison tolerance.
* Default value is 0.000001 (10e-6)
* @type {number}
*/
let DP_TOL = 0.000001;
/**
* Set new floating point comparison tolerance
* @param {number} tolerance
*/
export function setTolerance(tolerance) {DP_TOL = tolerance;}
/**
* Get floating point comparison tolerance
* @returns {number}
*/
export function getTolerance() {return DP_TOL;}
export const DECIMALS = 3;
/**
* Returns *true* if value comparable to zero
* @param {number} x
* @param {number} y
* @return {boolean}
*/
export function EQ_0(x) {
return (x < DP_TOL && x > -DP_TOL);
}
/**
* Returns *true* if two values are equal up to DP_TOL
* @param {number} x
* @param {number} y
* @return {boolean}
*/
export function EQ(x, y) {
return (x - y < DP_TOL && x - y > -DP_TOL);
}
/**
* Returns *true* if first argument greater than second argument up to DP_TOL
* @param {number} x
* @param {number} y
* @return {boolean}
*/
export function GT(x, y) {
return (x - y > DP_TOL);
}
/**
* Returns *true* if first argument greater than or equal to second argument up to DP_TOL
* @param {number} x
* @param {number} y
* @returns {boolean}
*/
export function GE(x, y) {
return (x - y > -DP_TOL);
}
/**
* Returns *true* if first argument less than second argument up to DP_TOL
* @param {number} x
* @param {number} y
* @return {boolean}
*/
export function LT(x, y) {
return (x - y < -DP_TOL)
}
/**
* Returns *true* if first argument less than or equal to second argument up to DP_TOL
* @param {number} x
* @param {number} y
* @return {boolean}
*/
export function LE(x, y) {
return (x - y < DP_TOL);
}
```
--------------------------------
### DE-9IM Matrix Calculation
Source: https://github.com/alexbol99/flatten-js/blob/master/docs/index.html
Example of calculating the DE-9IM matrix for two shapes using the relate method.
```javascript
let {relate} = Flatten.Relations;
//
// define two shapes: polygon1, polygon2
//
let de9im = relate(polygon1, polygon2);
//
// explore 8 of 9 fields of the de9im matrix:
// de9im.I2I de9im.B2I de9im.E2I
// de9im.I2B de9im.B2B de9im.E2B
// de9im.I2E de9im.B2E N/A
```
--------------------------------
### Importing Flatten namespace
Source: https://github.com/alexbol99/flatten-js/blob/master/README.md
Importing the Flatten namespace as a default import and then destructing all classes from it.
```javascript
import Flatten from '@flatten-js/core'
const {Point, Vector, Circle, Line, Ray, Segment, Arc, Box, Polygon, Matrix, PlanarSet} = Flatten;
```
--------------------------------
### Box.toSegments Method
Source: https://github.com/alexbol99/flatten-js/blob/master/docs/classes_box.js.html
Converts the box into an array of four line segments, starting from the bottom-left corner in counterclockwise order.
```javascript
toSegments() {
let pts = this.toPoints();
return [
new Flatten.Segment(pts[0], pts[1]),
new Flatten.Segment(pts[1], pts[2]),
new Flatten.Segment(pts[2], pts[3]),
new Flatten.Segment(pts[3], pts[0])
];
}
```
--------------------------------
### Vector Constructor
Source: https://github.com/alexbol99/flatten-js/blob/master/docs/classes_vector.js.html
Demonstrates the various ways a Vector object can be constructed, including from two points, two numbers, an array of two numbers, or a segment.
```javascript
"use strict";
import Flatten from '../flatten';
import {Shape} from "./shape";
import {Matrix} from "./matrix";
import {Errors} from "../utils/errors";
/**
* Class representing a vector
* @type {Vector}
*/
export class Vector extends Shape {
/**
* Vector may be constructed by two points, or by two float numbers,
* or by array of two numbers or by segment
* @param {Point} ps - start point
* @param {Point} pe - end point
*/
constructor(...args) {
super()
/**
* x-coordinate of a vector (float number)
* @type {number}
*/
this.x = 0;
/**
* y-coordinate of a vector (float number)
* @type {number}
*/
this.y = 0;
/* return zero vector */
if (args.length === 0) {
return;
}
if (args.length === 1 && args[0] instanceof Array && args[0].length === 2) {
let arr = args[0];
if (typeof (arr[0]) == "number" && typeof (arr[1]) == "number") {
this.x = arr[0];
this.y = arr[1];
return;
}
}
if (args.length === 1 && args[0] instanceof Object && args[0].name === "vector") {
let {x, y} = args[0];
this.x = x;
this.y = y;
return;
}
if (args.length === 1 && args[0] instanceof Object && args[0].name === "segment") {
let {start, end} = args[0];
this.x = end.x - start.x;
this.y = end.y - start.y;
return;
}
if (args.length === 2) {
let a1 = args[0];
let a2 = args[1];
if (typeof (a1) == "number" && typeof (a2) == "number") {
this.x = a1;
this.y = a2;
return;
}
if (a1 instanceof Flatten.Point && a2 instanceof Flatten.Point) {
this.x = a2.x - a1.x;
this.y = a2.y - a1.y;
return;
}
}
throw Errors.ILLEGAL_PARAMETERS;
}
/**
* Method clone returns new instance of Vector
* @returns {Vector}
*/
clone() {
return new Flatten.Vector(this.x, this.y);
}
/**
* Slope of the vector in radians from 0 to 2PI
* @returns {number}
*/
get slope() {
let angle = Math.atan2(this.y, this.x);
if (angle < 0) angle = 2 * Math.PI + angle;
return angle;
}
/**
* Length of vector
* @returns {number}
*/
get length() {
return Math.sqrt(this.dot(this));
}
/**
* Returns true if the vector is zero length
* @returns {boolean}
*/
isZeroLength() {
return Flatten.Utils.EQ_0(this.length);
}
/**
* Returns true if vectors are equal up to [DP_TOL]{@link http://localhost:63342/flatten-js/docs/global.html#DP_TOL}
* tolerance
* @param {Vector} v
* @returns {boolean}
*/
equalTo(v) {
return Flatten.Utils.EQ(this.x, v.x) && Flatten.Utils.EQ(this.y, v.y);
}
/**
* Returns new vector multiplied by scalar
* @param {number} scalar
* @returns {Vector}
*/
multiply(scalar) {
return (new Flatten.Vector(scalar * this.x, scalar * this.y));
}
/**
* Returns scalar product (dot product) of two vectors
* dot_product = (this * v)
* @param {Vector} v Other vector
* @returns {number}
*/
dot(v) {
return (this.x * v.x + this.y * v.y);
}
/**
* Returns vector product (cross product) of two vectors
* cross_product = (this x v)
* @param {Vector} v Other vector
* @returns {number}
*/
cross(v) {
return (this.x * v.y - this.y * v.x);
}
/**
* Returns unit vector.
* Throw error if given vector has zero length
* @returns {Vector}
*/
normalize() {
if (this.isZeroLength()) {
throw Errors.ZERO_DIVISION;
}
return (new Flatten.Vector(this.x / this.length, this.y / this.length));
}
/**
* Returns new vector rotated by given angle,
* positive angle defines rotation in counterclockwise direction,
```
--------------------------------
### Importing classes
Source: https://github.com/alexbol99/flatten-js/blob/master/README.md
Importing all classes from the @flatten-js/core package.
```javascript
import {Point, Vector, Circle, Line, Ray, Segment, Arc, Box, Polygon, Matrix, PlanarSet} from '@flatten-js/core';
```
--------------------------------
### Matrix Constructor
Source: https://github.com/alexbol99/flatten-js/blob/master/docs/Matrix.html
Constructs a new instance of an affine transformation matrix. If parameters are omitted, it constructs an identity matrix.
```javascript
new Matrix(a, c, b, d, tx, ty)
```
--------------------------------
### Circle Constructor
Source: https://github.com/alexbol99/flatten-js/blob/master/docs/Circle.html
Initializes a new Circle object. The constructor takes a center point and a radius.
```javascript
new Circle(pc, r)
```
--------------------------------
### DE-9IM Matrix Representation
Source: https://github.com/alexbol99/flatten-js/blob/master/README.md
Example of how to retrieve and explore the DE-9IM matrix using the relate method.
```javascript
let {relate} = Flatten.Relations;
//
// define two shapes: polygon1, polygon2
//
let de9im = relate(polygon1, polygon2);
//
// explore 8 of 9 fields of the de9im matrix:
// de9im.I2I de9im.B2I de9im.E2I
// de9im.I2B de9im.B2B de9im.E2B
// de9im.I2E de9im.B2E N/A
```