<!-- Generated by scripts/generate-markdown-docs.mjs. Do not edit directly. -->
# Pts API Reference

Complete API reference for [Pts 1.0.2](https://ptsjs.org), generated from the same TypeDoc data used by the documentation website. Members are documented in full where they are declared and linked from subclasses that inherit them. For tutorials and runnable examples, see the [Pts guides and demos](https://ptsjs.org/guide.md).

## Contents

- [`Canvas`](#module-canvas)
  - [`CanvasForm`](#canvas-canvasform)
  - [`CanvasSpace`](#canvas-canvasspace)

- [`Color`](#module-color)
  - [`Color`](#color-color)

- [`Create`](#module-create)
  - [`Boid`](#create-boid)
  - [`Create`](#create-create)
  - [`Delaunay`](#create-delaunay)
  - [`Flock`](#create-flock)
  - [`Noise`](#create-noise)
  - [`PoissonDisk`](#create-poissondisk)

- [`Dom`](#module-dom)
  - [`DOMSpace`](#dom-domspace)
  - [`HTMLForm`](#dom-htmlform)
  - [`HTMLSpace`](#dom-htmlspace)

- [`Form`](#module-form)
  - [`Font`](#form-font)
  - [`Form`](#form-form)
  - [`VisualForm`](#form-visualform)

- [`Image`](#module-image)
  - [`Img`](#image-img)
  - [`ImgOptions`](#image-imgoptions)

- [`LinearAlgebra`](#module-linear-algebra)
  - [`Mat`](#linearalgebra-mat)
  - [`Vec`](#linearalgebra-vec)

- [`Num`](#module-num)
  - [`Geom`](#num-geom)
  - [`Num`](#num-num)
  - [`Range`](#num-range)
  - [`Shaping`](#num-shaping)

- [`Op`](#module-op)
  - [`Circle`](#op-circle)
  - [`Curve`](#op-curve)
  - [`Line`](#op-line)
  - [`Path`](#op-path)
  - [`Polygon`](#op-polygon)
  - [`Rectangle`](#op-rectangle)
  - [`Triangle`](#op-triangle)

- [`Physics`](#module-physics)
  - [`Body`](#physics-body)
  - [`Particle`](#physics-particle)
  - [`World`](#physics-world)

- [`Play`](#module-play)
  - [`Sound`](#play-sound)
  - [`Tempo`](#play-tempo)

- [`Pt`](#module-pt)
  - [`Bound`](#pt-bound)
  - [`Group`](#pt-group)
  - [`Pt`](#pt-pt)

- [`Space`](#module-space)
  - [`MultiTouchSpace`](#space-multitouchspace)
  - [`Space`](#space-space)

- [`Svg`](#module-svg)
  - [`SVGContext2D`](#svg-svgcontext2d)
  - [`SVGForm`](#svg-svgform)
  - [`SVGSpace`](#svg-svgspace)

- [`Typography`](#module-typography)
  - [`Typography`](#typography-typography)

- [`UI`](#module-ui)
  - [`UI`](#ui-ui)
  - [`UIButton`](#ui-uibutton)
  - [`UIDragger`](#ui-uidragger)
  - [`UIPointerAction`](#ui-uipointeraction)
  - [`UIShapeTest`](#ui-uishapetest)
  - [`UIPointerActions`](#ui-uipointeractions)
  - [`UIShape`](#ui-uishape)

- [`Util`](#module-util)
  - [`Util`](#util-util)
  - [`Const`](#util-const)

- [`uheprng`](#module-uheprng)
  - [`default`](#uheprng-default)

- [`Types`](#module-types)
  - [`IPlayer`](#types-iplayer)
  - [`IPt`](#types-ipt)
  - [`ISpacePlayers`](#types-ispaceplayers)
  - [`ITimer`](#types-itimer)
  - [`MultiTouchElement`](#types-multitouchelement)
  - [`AnimateCallbackFn`](#types-animatecallbackfn)
  - [`CanvasPatternRepetition`](#types-canvaspatternrepetition)
  - [`CanvasSpaceOptions`](#types-canvasspaceoptions)
  - [`ColorType`](#types-colortype)
  - [`DefaultFormStyle`](#types-defaultformstyle)
  - [`DelaunayMesh`](#types-delaunaymesh)
  - [`DelaunayShape`](#types-delaunayshape)
  - [`DOMFormContext`](#types-domformcontext)
  - [`FlockBoundary`](#types-flockboundary)
  - [`FlockOptions`](#types-flockoptions)
  - [`GroupLike`](#types-grouplike)
  - [`IntersectContext`](#types-intersectcontext)
  - [`ISoundAnalyzer`](#types-isoundanalyzer)
  - [`ITempoListener`](#types-itempolistener)
  - [`ITempoProgressFn`](#types-itempoprogressfn)
  - [`ITempoResponses`](#types-itemporesponses)
  - [`ITempoStartFn`](#types-itempostartfn)
  - [`PoissonDiskOptions`](#types-poissondiskoptions)
  - [`PolygonLike`](#types-polygonlike)
  - [`PtIterable`](#types-ptiterable)
  - [`PtLike`](#types-ptlike)
  - [`PtLikeIterable`](#types-ptlikeiterable)
  - [`RenderingContext2D`](#types-renderingcontext2d)
  - [`SoundType`](#types-soundtype)
  - [`TextMeasure`](#types-textmeasure)
  - [`TextVerticalAlign`](#types-textverticalalign)
  - [`TouchPointsKey`](#types-touchpointskey)
  - [`UIActionEvent`](#types-uiactionevent)
  - [`UIHandler`](#types-uihandler)
  - [`WarningType`](#types-warningtype)

<a id="module-canvas"></a>
## Module: `Canvas`

<a id="canvas-canvasform"></a>
### `CanvasForm`

**Kind:** Class · **Source:** [`src/Canvas.ts:555`](https://github.com/williamngan/pts/blob/master/src/Canvas.ts#L555)

**Extends:** `VisualForm`

VisualForm is an abstract class that represents a form that can be used to express Pts visually.
For example, [`CanvasForm`](#canvas-canvasform) is an implementation of VisualForm that draws on [`CanvasSpace`](#canvas-canvasspace) which represents a html canvas. Learn more about Space and Form in [this guide](https://ptsjs.org/guide/Space-0500.html).

#### Constructors

<a id="canvas-canvasform-constructor"></a>
##### Constructor

```ts
new CanvasForm(space: RenderingContext2D | CanvasSpace): CanvasForm
```

Create a new CanvasForm. You may also use [`CanvasSpace.getForm()`](#canvas-canvasspace-get-form) to get the default form.

**Parameters**

- `space` (`RenderingContext2D | CanvasSpace`) — an instance of CanvasSpace, or a rendering context. Passing a context is the renderer extension point: any object implementing the context surface documented in [`SVGContext2D`](#svg-svgcontext2d) (the reference implementation) receives this form's full drawing API — this is how SVG output works, and how custom renderers can be built.

#### Accessors

<a id="canvas-canvasform-ctx"></a>
##### `ctx`

```ts
get ctx(): RenderingContext2D
```

Get the rendering context of canvas to perform other canvas functions.

<a id="canvas-canvasform-space"></a>
##### `space`

```ts
get space(): S
```

get the CanvasSpace instance that this form is associated with

#### Methods

<a id="canvas-canvasform-align-text"></a>
##### `alignText`

```ts
alignText(alignment: CanvasTextAlign = "left", baseline: CanvasTextBaseline = "alphabetic"): CanvasForm
```

Set text alignment and baseline (eg, vertical-align).

**Parameters**

- `alignment` (`CanvasTextAlign`; default `"left"`) — HTML canvas' textAlign option: "left", "right", "center", "start", or "end"
- `baseline` (`CanvasTextBaseline`; default `"alphabetic"`) — HTML canvas' textBaseline option: "top", "hanging", "middle", "alphabetic", "ideographic", "bottom". For convenience, you can also use "center" (same as "middle"), and "baseline" (same as "alphabetic")

<a id="canvas-canvasform-alpha"></a>
##### `alpha`

*overrides `VisualForm.alpha`*

```ts
alpha(a: number): this
```

Set current alpha value.

**Parameters**

- `a` (`number`) — alpha value between 0 and 1

**Example**

```ts
form.alpha(0.6)
```

<a id="canvas-canvasform-apply-fill-stroke"></a>
##### `applyFillStroke`

```ts
applyFillStroke(filled: string | boolean = true, stroked: string | boolean = true, strokeWidth: number = 1): CanvasForm
```

A convenient function to apply fill and/or stroke after custom drawings using canvas context (eg, `form.ctx.ellipse(...)`).
You don't need to call this function if you're using Pts' drawing functions like `form.point` or `form.rect`

**Parameters**

- `filled` (`string | boolean`; default `true`) — apply fill when set to `true`
- `stroked` (`string | boolean`; default `true`) — apply stroke when set to `true`
- `strokeWidth` (`number`; default `1`) — optionally set a stroke width

**Example**

```ts
form.ctx.beginPath(); form.ctx.ellipse(...); form.applyFillStroke();
```

<a id="canvas-canvasform-arc"></a>
##### `arc`

*overrides `VisualForm.arc`*

```ts
arc(pt: PtLike, radius: number, startAngle: number, endAngle: number, cc: boolean): this
```

Draw an arc.

**Parameters**

- `pt` (`PtLike`) — center position
- `radius` (`number`) — radius of the arc circle
- `startAngle` (`number`) — start angle of the arc
- `endAngle` (`number`) — end angle of the arc
- `cc` (`boolean`) — an optional boolean value to specify if it should be drawn clockwise (`false`) or counter-clockwise (`true`). Default is clockwise.

<a id="canvas-canvasform-bezier"></a>
##### `bezier`

```ts
bezier(pts: PtLikeIterable): this
```

Draw a chain of cubic Bezier curves as one native path. Unlike a polyline from [`Curve.bezier`](#op-curve-static-bezier),
the path stays smooth at any zoom and exports as compact SVG. Use [`Curve.cardinalToBezier`](#op-curve-static-cardinal-to-bezier) or
[`Curve.bsplineToBezier`](#op-curve-static-bspline-to-bezier) to draw those curves this way.

**Parameters**

- `pts` (`PtLikeIterable`) — a Group or an Iterable<PtLike> in the layout of [`Curve.bezier`](#op-curve-static-bezier): an anchor followed by 2 control points and an anchor per segment

**Example**

```ts
form.bezier( Curve.cardinalToBezier( pts ) )
```

<a id="canvas-canvasform-circle"></a>
##### `circle`

*overrides `VisualForm.circle`*

```ts
circle(pts: PtLikeIterable): this
```

Draw a circle. See also [`Circle.fromCenter`](#op-circle-static-from-center)

**Parameters**

- `pts` (`PtLikeIterable`) — usually a Group or an Iterable<PtLike> with 2 Pt, but it can also take an array of two numeric arrays [ [position], [size] ]

<a id="canvas-canvasform-clip"></a>
##### `clip`

```ts
clip(): this
```

Create a clipping mask from the current path. See [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/clip) for details.

<a id="canvas-canvasform-composite"></a>
##### `composite`

```ts
composite(mode: GlobalCompositeOperation = "source-over"): this
```

Set composite operation (also known as blend mode). You can also call this function without parameters to get back to default 'source-over' mode. See [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation) for the full list of operations you can use.

**Parameters**

- `mode` (`GlobalCompositeOperation`; default `"source-over"`) — a composite operation such as 'lighten', 'multiply', 'overlay', and 'color-burn'.

<a id="canvas-canvasform-compound"></a>
##### `compound`

```ts
compound(rings: Iterable): this
```

Draw a compound polygon: several rings as one path, so that a ring inside another with the opposite orientation becomes a hole
(the nonzero winding rule). This is how a [`Path`](#op-path) result is drawn; [`CanvasForm.polygons`](#form-visualform-polygons) would fill the holes.

**Parameters**

- `rings` (`Iterable`) — an Array/Iterable of rings, each a Group or an Iterable<PtLike>; rings with fewer than 2 points are skipped, and nothing is drawn if no ring remains

**Example**

```ts
form.fillOnly("#f03").compound( Path.minusFront( [disc, hole] ) )
```

<a id="canvas-canvasform-dash"></a>
##### `dash`

```ts
dash(segments: boolean | PtLike = true, offset: number = 0): this
```

Activate dashed stroke and set dash style. You can customize the segments and offset.

**Parameters**

- `segments` (`boolean | PtLike`; default `true`) — Dash segments. Defaults to `true` which corresponds to `[5, 5]`. Pass `false` to deactivate dashes. (See [canvas documentation](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setLineDash))
- `offset` (`number`; default `0`) — Dash offset. Defaults to 0. (See [canvas documentation](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset)

**Example**

```ts
form.dash()`, `form.dash([5, 10])`, `form.dash([5, 5], 5)`, `form.dash(false)
```

<a id="canvas-canvasform-ellipse"></a>
##### `ellipse`

```ts
ellipse(pt: PtLike, radius: PtLike, rotation: number = 0, startAngle: number = 0, endAngle: number = Const.two_pi, cc: boolean = false): CanvasForm
```

Draw an ellipse.

**Parameters**

- `pt` (`PtLike`) — center position
- `radius` (`PtLike`) — radius [x, y] of the ellipse
- `rotation` (`number`; default `0`) — rotation of the ellipse in radian. Default is 0.
- `startAngle` (`number`; default `0`) — start angle of the ellipse. Default is 0.
- `endAngle` (`number`; default `Const.two_pi`) — end angle of the ellipse. Default is 2 PI.
- `cc` (`boolean`; default `false`) — an optional boolean value to specify if it should be drawn clockwise (`false`) or counter-clockwise (`true`). Default is clockwise.

<a id="canvas-canvasform-fill"></a>
##### `fill`

*overrides `VisualForm.fill`*

```ts
fill(c: string | boolean | CanvasGradient | CanvasPattern): this
```

Set current fill style. Provide a valid color string such as `"#FFF"` or `"rgba(255,0,100,0.5)"` or `false` to specify no fill color.

**Parameters**

- `c` (`string | boolean | CanvasGradient | CanvasPattern`) — fill color which can be as color, gradient, or pattern. (See [canvas documentation](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle))

**Example**

```ts
form.fill("#F90")`, `form.fill("rgba(0,0,0,.5")`, `form.fill(false)
```

<a id="canvas-canvasform-fill-only"></a>
##### `fillOnly`

*overrides `VisualForm.fillOnly`*

```ts
fillOnly(c: string | boolean | CanvasGradient | CanvasPattern): this
```

Set current fill style and remove stroke style.

**Parameters**

- `c` (`string | boolean | CanvasGradient | CanvasPattern`) — fill color which can be as color, gradient, or pattern. (See [canvas documentation](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle))

<a id="canvas-canvasform-font"></a>
##### `font`

*overrides `VisualForm.font`*

```ts
font(sizeOrFont: number | Font, weight: string, style: string, lineHeight: number, family: string): this
```

Set the current font.

**Parameters**

- `sizeOrFont` (`number | Font`) — either a number to specify font-size, or a `Font` object to specify all font properties
- `weight` (`string`) — Optional font-weight string such as "bold"
- `style` (`string`) — Optional font-style string such as "italic"
- `lineHeight` (`number`) — Optional line-height number suchas 1.5
- `family` (`string`) — Optional font-family such as "Helvetica, sans-serif"

**Example**

```ts
form.font( myFont )`, `form.font(14, "bold")
```

<a id="canvas-canvasform-font-width-estimate"></a>
##### `fontWidthEstimate`

```ts
fontWidthEstimate(estimate: boolean | sample | char = true): this
```

Set whether to use html canvas' [`measureText`](#svg-svgcontext2d-measure-text) function, or a faster but less accurate estimate.

**Parameters**

- `estimate` (`boolean | sample | char`; default `true`) — `false` to use ctx.measureText; `true` or `"sample"` to use a sampled-average estimator (fastest); `"char"` to use a per-character width cache (nearly as accurate as measureText for most texts, and much faster after warmup)

<a id="canvas-canvasform-get-text-width"></a>
##### `getTextWidth`

```ts
getTextWidth(c: string): number
```

Get the width of this text. It will return an actual measurement or an estimate based on [`fontWidthEstimate`](#canvas-canvasform-font-width-estimate) setting. Default is an actual measurement using canvas context's measureText.

**Parameters**

- `c` (`string`) — a string of text contents

<a id="canvas-canvasform-gradient"></a>
##### `gradient`

```ts
gradient(stops: string[] | number,string[]):  Fn(area1:GroupLike, area2:GroupLike)
```

This function takes an array of gradient colors, and returns a function to define the areas of the gradient fill. See demo code in [CanvasForm.gradient](https://ptsjs.org/demo/?name=canvasform.textBox).

**Parameters**

- `stops` (`string[] | number,string[]`) — an array of gradient stops. This can be an array of colors `["#f00", "#0f0", ...]` for evenly distributed gradient, or an array of [stop, color] like `[[0.1, "#f00"], [0.7, "#0f0"]]`

**Returns:** a function that takes 1 or 2 `Group` as parameters. Use a single `Group` to specify a rectangular area for linear gradient, or use 2 `Groups` to specify 2 `Circles` for radial gradient.

**Example**

```ts
c1 = Circle.fromCenter(...); grad = form.gradient(["#f00", "#00f"]); form.fill( grad( c1, c2 ) ).circle( c1 )
```

<a id="canvas-canvasform-image"></a>
##### `image`

```ts
image(ptOrRect: PtLikeIterable | PtLike, img: Img | CanvasImageSource, orig: PtLikeIterable): CanvasForm
```

Draw an image.

**Parameters**

- `ptOrRect` (`PtLikeIterable | PtLike`) — a target area to place the image. Either a PtLike specifying a position, or a Group or an Iterable<PtLike> with 2 Pt (top-left position, bottom-right position) that specifies a bounding box. Default is (0,0) at top-left.
- `img` (`Img | CanvasImageSource`) — either an [Img](#image-img) instance or an [`CanvasImageSource`](https://developer.mozilla.org/en-US/docs/Web/API/CanvasImageSource) instance (eg the image from `<img>`, `<video>` or `<canvas>`)
- `orig` (`PtLikeIterable`) — optionally a Group or an Iterable<PtLike> with 2 Pt (top-left position, bottom-right position) that specifies a cropping box  in the original target.

<a id="canvas-canvasform-image-data"></a>
##### `imageData`

```ts
imageData(ptOrRect: PtLikeIterable | PtLike, img: ImageData): CanvasForm
```

Draw ImageData on canvas using ImageData

**Parameters**

- `ptOrRect` (`PtLikeIterable | PtLike`) — a target area to place the image. Either a Pt or numeric array specifying a position, or a Group or an Iterable<PtLike> with 2 Pt (top-left, bottom-right) that specifies a bounding box for resizing. Default is (0,0) at top-left.
- `img` (`ImageData`) — an ImageData object

<a id="canvas-canvasform-line"></a>
##### `line`

*overrides `VisualForm.line`*

```ts
line(pts: PtLikeIterable): this
```

Draw a line or polyline.

**Parameters**

- `pts` (`PtLikeIterable`) — a Group or an Iterable<PtLike> representing a line

<a id="canvas-canvasform-log"></a>
##### `log`

```ts
log(txt: any): this
```

A convenient way to draw some text on canvas for logging or debugging. It'll be draw on the top-left of the canvas as an overlay.

**Parameters**

- `txt` (`any`) — text

<a id="canvas-canvasform-paragraph-box"></a>
##### `paragraphBox`

```ts
paragraphBox(box: PtLikeIterable, txt: string, lineHeight: number = 1.2, verticalAlign: TextVerticalAlign = "top", crop: boolean = true): this
```

Fit multi-line text in a rectangular box. Note that this will also set canvas context's textBaseline to "top".

**Parameters**

- `box` (`PtLikeIterable`) — a Group or an Iterable<PtLike> with 2 Pt that represents a bounding box
- `txt` (`string`) — string of text
- `lineHeight` (`number`; default `1.2`) — line height as a ratio of font size. Default is 1.2.
- `verticalAlign` (`TextVerticalAlign`; default `"top"`) — "top", "middle", or "bottom" to specify vertical alignment inside the box
- `crop` (`boolean`; default `true`) — a boolean to specify whether to crop text when overflowing

<a id="canvas-canvasform-point"></a>
##### `point`

*overrides `VisualForm.point`*

```ts
point(p: PtLike, radius: number = 5, shape: string = "square"): this
```

Draws a point.

**Parameters**

- `p` (`PtLike`) — a Pt object
- `radius` (`number`; default `5`) — radius of the point. Default is 5.
- `shape` (`string`; default `"square"`) — The shape of the point. Defaults to "square", but it can be "circle" or a custom shape function in your own implementation.

**Example**

```ts
form.point( p )`, `form.point( p, 10, "circle" )
```

<a id="canvas-canvasform-polygon"></a>
##### `polygon`

*overrides `VisualForm.polygon`*

```ts
polygon(pts: PtLikeIterable): this
```

Draw a polygon.

**Parameters**

- `pts` (`PtLikeIterable`) — a Group or an Iterable<PtLike> representingg a polygon

<a id="canvas-canvasform-rect"></a>
##### `rect`

*overrides `VisualForm.rect`*

```ts
rect(pts: PtLikeIterable): this
```

Draw a rectangle.

**Parameters**

- `pts` (`PtLikeIterable`) — a Group or an Iterable<PtLike> with 2 Pt specifying the top-left and bottom-right positions.

<a id="canvas-canvasform-render-offscreen"></a>
##### `renderOffscreen`

```ts
renderOffscreen(offset: PtLike = ...): void
```

Render the offscreen canvas's content on the visible canvas

**Parameters**

- `offset` (`PtLike`; default `...`) — Optional offset on the top-left position when drawing on the visible canvas

<a id="canvas-canvasform-reset"></a>
##### `reset`

*overrides `VisualForm.reset`*

```ts
reset(): this
```

Reset the rendering context's common styles to this form's styles. This supports using multiple forms on the same canvas context.

<a id="canvas-canvasform-square"></a>
##### `square`

```ts
square(pt: PtLike, halfsize: number): CanvasForm
```

Draw a square, given a center and its half-size.

**Parameters**

- `pt` (`PtLike`) — center Pt
- `halfsize` (`number`) — half-size

<a id="canvas-canvasform-stroke"></a>
##### `stroke`

*overrides `VisualForm.stroke`*

```ts
stroke(c: string | boolean | CanvasGradient | CanvasPattern, width: number, linejoin: CanvasLineJoin, linecap: CanvasLineCap): this
```

Set current stroke style. Provide a valid color string or `false` to specify no stroke color.

**Parameters**

- `c` (`string | boolean | CanvasGradient | CanvasPattern`) — stroke color which can be as color, gradient, or pattern. (See [canvas documentation](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/strokeStyle))
- `width` (`number`) — Optional value (can be floating point) to set line width
- `linejoin` (`CanvasLineJoin`) — Optional string to set line joint style. Can be "miter", "bevel", or "round".
- `linecap` (`CanvasLineCap`) — Optional string to set line cap style. Can be "butt", "round", or "square".

**Example**

```ts
form.stroke("#F90")`, `form.stroke("rgba(0,0,0,.5")`, `form.stroke(false)`, `form.stroke("#000", 0.5, 'round', 'square')
```

<a id="canvas-canvasform-stroke-only"></a>
##### `strokeOnly`

*overrides `VisualForm.strokeOnly`*

```ts
strokeOnly(c: string | boolean | CanvasGradient | CanvasPattern, width: number, linejoin: CanvasLineJoin, linecap: CanvasLineCap): this
```

Set stroke style and remove fill style.

**Parameters**

- `c` (`string | boolean | CanvasGradient | CanvasPattern`) — stroke color which can be as color, gradient, or pattern. (See [canvas documentation](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/strokeStyle))
- `width` (`number`) — Optional value (can be floating point) to set line width
- `linejoin` (`CanvasLineJoin`) — Optional string to set line joint style. Can be "miter", "bevel", or "round".
- `linecap` (`CanvasLineCap`) — Optional string to set line cap style. Can be "butt", "round", or "square".

<a id="canvas-canvasform-text"></a>
##### `text`

*overrides `VisualForm.text`*

```ts
text(pt: PtLike, txt: string, maxWidth: number): this
```

Draw text on canvas.

**Parameters**

- `pt` (`PtLike`) — a Pt or numeric array to specify the anchor point
- `txt` (`string`) — text
- `maxWidth` (`number`) — specify a maximum width per line

<a id="canvas-canvasform-text-box"></a>
##### `textBox`

```ts
textBox(box: PtIterable, txt: string, verticalAlign: TextVerticalAlign = "middle", tail: string = "", overrideBaseline: boolean = true): this
```

Fit a single-line text in a rectangular box.

**Parameters**

- `box` (`PtIterable`) — a rectangle box defined by a Group or an Iterable<Pt>
- `txt` (`string`) — string of text
- `verticalAlign` (`TextVerticalAlign`; default `"middle"`) — "top", "middle", or "bottom" to specify vertical alignment inside the box
- `tail` (`string`; default `""`) — text to indicate overflow such as "...". Default is empty "".
- `overrideBaseline` (`boolean`; default `true`) — If `true`, use the corresponding baseline as verticalAlign. If `false`, use the current canvas context's textBaseline setting. Default is `true`.

<a id="canvas-canvasform-use-offscreen"></a>
##### `useOffscreen`

```ts
useOffscreen(off: boolean = true, clear: string | boolean = false): CanvasForm
```

Toggle whether to draw on offscreen canvas (if offscreen is set in CanvasSpace)

**Parameters**

- `off` (`boolean`; default `true`) — if `true`, draw on offscreen canvas instead of the visible canvas. Default is `true`
- `clear` (`string | boolean`; default `false`) — optionally provide a valid color string to fill a bg color. see CanvasSpace's `clearOffscreen` function.

<a id="canvas-canvasform-static-arc"></a>
##### `arc`

*static*

```ts
static arc(ctx: RenderingContext2D, pt: PtLike, radius: number, startAngle: number, endAngle: number, cc: boolean): void
```

A static function to draw an arc.

**Parameters**

- `ctx` (`RenderingContext2D`) — canvas rendering context
- `pt` (`PtLike`) — center position
- `radius` (`number`) — radius of the arc circle
- `startAngle` (`number`) — start angle of the arc
- `endAngle` (`number`) — end angle of the arc
- `cc` (`boolean`) — an optional boolean value to specify if it should be drawn clockwise (`false`) or counter-clockwise (`true`). Default is clockwise.

<a id="canvas-canvasform-static-bezier"></a>
##### `bezier`

*static*

```ts
static bezier(ctx: RenderingContext2D, pts: PtLikeIterable): void
```

A static function to draw a chain of cubic Bezier curves as one native path.

**Parameters**

- `ctx` (`RenderingContext2D`) — canvas rendering context
- `pts` (`PtLikeIterable`) — a Group or an Iterable<PtLike> in the layout of [`Curve.bezier`](#op-curve-static-bezier): an anchor followed by 2 control points and an anchor per segment

<a id="canvas-canvasform-static-circle"></a>
##### `circle`

*static*

```ts
static circle(ctx: RenderingContext2D, pt: PtLike, radius: number = 10): void
```

A static function to draw a circle.

**Parameters**

- `ctx` (`RenderingContext2D`) — canvas rendering context
- `pt` (`PtLike`) — center position of the circle
- `radius` (`number`; default `10`) — radius of the circle

<a id="canvas-canvasform-static-compound"></a>
##### `compound`

*static*

```ts
static compound(ctx: RenderingContext2D, rings: Iterable): void
```

A static function to draw a compound polygon: several rings as one path, so that a ring inside another with the opposite orientation becomes a hole (the nonzero winding rule).

**Parameters**

- `ctx` (`RenderingContext2D`) — canvas rendering context
- `rings` (`Iterable`) — an Array/Iterable of rings, each a Group or an Iterable<PtLike>; rings with fewer than 2 points are skipped

<a id="canvas-canvasform-static-ellipse"></a>
##### `ellipse`

*static*

```ts
static ellipse(ctx: RenderingContext2D, pt: PtLike, radius: PtLike, rotation: number = 0, startAngle: number = 0, endAngle: number = Const.two_pi, cc: boolean = false): void
```

A static function to draw an ellipse.

**Parameters**

- `ctx` (`RenderingContext2D`) — canvas rendering context
- `pt` (`PtLike`) — center position
- `radius` (`PtLike`) — radius [x, y] of the ellipse
- `rotation` (`number`; default `0`) — rotation of the ellipse in radian. Default is 0.
- `startAngle` (`number`; default `0`) — start angle of the ellipse. Default is 0.
- `endAngle` (`number`; default `Const.two_pi`) — end angle of the ellipse. Default is 2 PI.
- `cc` (`boolean`; default `false`) — an optional boolean value to specify if it should be drawn clockwise (`false`) or counter-clockwise (`true`). Default is clockwise.

<a id="canvas-canvasform-static-image"></a>
##### `image`

*static*

```ts
static image(ctx: RenderingContext2D, ptOrRect: PtLikeIterable | PtLike, img: Img | CanvasImageSource, orig: PtLikeIterable): void
```

A static function to draw an image.

**Parameters**

- `ctx` (`RenderingContext2D`) — canvas rendering context
- `ptOrRect` (`PtLikeIterable | PtLike`) — a target area to place the image. Either a Pt or numeric array specifying a position, or a Group or an Iterable<PtLike> with 2 Pt (top-left, bottom-right) that specifies a bounding box for resizing. Default is (0,0) at top-left.
- `img` (`Img | CanvasImageSource`) — either an [Img](#image-img) instance or an [`CanvasImageSource`](https://developer.mozilla.org/en-US/docs/Web/API/CanvasImageSource) instance (eg the image from `<img>`, `<video>` or `<canvas>`)
- `orig` (`PtLikeIterable`) — optionally a Group or an Iterable<PtLike> with 2 Pt (top-left, bottom-right) that specifies a cropping box in the original target.

<a id="canvas-canvasform-static-image-data"></a>
##### `imageData`

*static*

```ts
static imageData(ctx: RenderingContext2D, ptOrRect: PtLikeIterable | PtLike, img: ImageData): void
```

A static function to draw ImageData on canvas

**Parameters**

- `ctx` (`RenderingContext2D`) — canvas rendering context
- `ptOrRect` (`PtLikeIterable | PtLike`) — a target area to place the image. Either a Pt or numeric array specifying a position, or a Group or an Iterable<PtLike> with 2 Pt (top-left, bottom-right) that places a region of the image data of that size at that position. Note that `putImageData` cannot resize: the rect clips, not scales. Default is (0,0) at top-left.
- `img` (`ImageData`) — an ImageData object

<a id="canvas-canvasform-static-line"></a>
##### `line`

*static*

```ts
static line(ctx: RenderingContext2D, pts: PtLikeIterable): void
```

A static function to draw a line or polyline.

**Parameters**

- `ctx` (`RenderingContext2D`) — canvas rendering context
- `pts` (`PtLikeIterable`) — a Group or an Iterable<PtLike> representing a line

<a id="canvas-canvasform-static-point"></a>
##### `point`

*static*

```ts
static point(ctx: RenderingContext2D, p: PtLike, radius: number = 5, shape: string = "square"): void
```

A static function to draw a point.

**Parameters**

- `ctx` (`RenderingContext2D`) — canvas rendering context
- `p` (`PtLike`) — a Pt object
- `radius` (`number`; default `5`) — radius of the point. Default is 5.
- `shape` (`string`; default `"square"`) — The shape of the point. Defaults to "square", but it can be "circle" or a custom shape function in your own implementation.

**Example**

```ts
form.point( p )`, `form.point( p, 10, "circle" )
```

<a id="canvas-canvasform-static-polygon"></a>
##### `polygon`

*static*

```ts
static polygon(ctx: RenderingContext2D, pts: PtLikeIterable): void
```

A static function to draw a polygon.

**Parameters**

- `ctx` (`RenderingContext2D`) — canvas rendering context
- `pts` (`PtLikeIterable`) — a Group or an Iterable<PtLike> representing a polygon

<a id="canvas-canvasform-static-rect"></a>
##### `rect`

*static*

```ts
static rect(ctx: RenderingContext2D, pts: PtLikeIterable): void
```

A static function to draw a rectangle.

**Parameters**

- `ctx` (`RenderingContext2D`) — canvas rendering context
- `pts` (`PtLikeIterable`) — a Group or an Iterable<PtLike> with 2 Pt specifying the top-left and bottom-right positions.

<a id="canvas-canvasform-static-reset-style-cache"></a>
##### `resetStyleCache`

*static*

```ts
static resetStyleCache(ctx: object | RenderingContext2D): void
```

Forget the cached style values for a rendering context, so every
subsequent style write applies. Call this after anything that resets or
desyncs a context's state outside a form — most commonly assigning a
canvas's `width` or `height`, which resets the context to its defaults.
(Within a form, [`CanvasForm.reset`](#canvas-canvasform-reset) is the equivalent recovery.)

**Parameters**

- `ctx` (`object | RenderingContext2D`) — the rendering context to forget

<a id="canvas-canvasform-static-square"></a>
##### `square`

*static*

```ts
static square(ctx: RenderingContext2D, pt: PtLike, halfsize: number): void
```

A static function to draw a square.

**Parameters**

- `ctx` (`RenderingContext2D`) — canvas rendering context
- `pt` (`PtLike`) — center position of the square
- `halfsize` (`number`) — half size of the square

<a id="canvas-canvasform-static-text"></a>
##### `text`

*static*

```ts
static text(ctx: RenderingContext2D, pt: PtLike, txt: string, maxWidth: number): void
```

A static function to draw text.

**Parameters**

- `ctx` (`RenderingContext2D`) — canvas rendering context
- `pt` (`PtLike`) — a Point object to specify the anchor point
- `txt` (`string`) — a string of text to draw
- `maxWidth` (`number`) — specify a maximum width per line

#### Inherited API

- From [`VisualForm`](#form-visualform): [`currentFont`](#form-visualform-current-font), [`filled`](#form-visualform-filled), [`stroked`](#form-visualform-stroked), [`circles`](#form-visualform-circles), [`lines`](#form-visualform-lines), [`points`](#form-visualform-points), [`polygons`](#form-visualform-polygons), [`rects`](#form-visualform-rects), [`squares`](#form-visualform-squares).
- From [`Form`](#form-form): [`ready`](#form-form-ready).

<a id="canvas-canvasspace"></a>
### `CanvasSpace`

**Kind:** Class · **Source:** [`src/Canvas.ts:26`](https://github.com/williamngan/pts/blob/master/src/Canvas.ts#L26)

**Extends:** `MultiTouchSpace`

CanvasSpace is an implementation of the abstract class [`Space`](#space-space). It represents a space for HTML Canvas.
Learn more about the concept of Space in [this guide](https://ptsjs.org/guide/Space-0500.html).

#### Constructors

<a id="canvas-canvasspace-constructor"></a>
##### Constructor

```ts
new CanvasSpace(elem: string | Element | null = "pt", callback:  Fn(bound:Bound, elem:EventTarget)): CanvasSpace
```

Create a CanvasSpace which represents a HTML Canvas Space

**Parameters**

- `elem` (`string | Element | null`; default `"pt"`) — Specify an element by its "id" attribute as string, or by the element object itself. An element can be an existing `<canvas>`, or a `<div>` container in which a new `<canvas>` will be created. If left empty, a `<div id="pt_container"><canvas id="pt" /></div>` will be added to DOM. Use css to customize its appearance if needed.
- `callback` (` Fn(bound:Bound, elem:EventTarget)`) — an optional callback `function(boundingBox, spaceElement)` to be called when canvas is appended and ready. Alternatively, a "ready" event will also be fired from the `<canvas>` element when it's appended, which can be traced with `spaceInstance.canvas.addEventListener("ready")`

**Example**

```ts
new CanvasSpace( "#myElementID" )
```

#### Accessors

<a id="canvas-canvasspace-auto-resize"></a>
##### `autoResize`

```ts
get autoResize(): boolean
set autoResize(auto: boolean): void
```

Set whether the canvas element should resize when its container is resized.

<a id="canvas-canvasspace-background"></a>
##### `background`

```ts
get background(): string
set background(bg: string): void
```

Set a background color for this canvas. Alternatively, you may use `clear()` function.

<a id="canvas-canvasspace-ctx"></a>
##### `ctx`

*public*

```ts
get ctx(): CanvasRenderingContext2D
```

Get the rendering context of canvas

<a id="canvas-canvasspace-element"></a>
##### `element`

```ts
get element(): HTMLCanvasElement
```

Get the html canvas element

<a id="canvas-canvasspace-has-offscreen"></a>
##### `hasOffscreen`

*public*

```ts
get hasOffscreen(): boolean
```

Check if an offscreen canvas is created

<a id="canvas-canvasspace-offscreen-canvas"></a>
##### `offscreenCanvas`

*public*

```ts
get offscreenCanvas(): HTMLCanvasElement
```

Get the offscreen canvas element

<a id="canvas-canvasspace-offscreen-ctx"></a>
##### `offscreenCtx`

*public*

```ts
get offscreenCtx(): RenderingContext2D
```

Get the rendering context of offscreen canvas (if created via `setup()`)

<a id="canvas-canvasspace-parent"></a>
##### `parent`

```ts
get parent(): Element
```

Get the parent element that contains the canvas element

<a id="canvas-canvasspace-pixel-scale"></a>
##### `pixelScale`

*public*

```ts
get pixelScale(): number
```

`pixelScale` property returns a number that let you determine if the screen is "retina" (when value >= 2)

<a id="canvas-canvasspace-ready"></a>
##### `ready`

```ts
get ready(): boolean
```

A property to indicate if the Space is ready

#### Methods

<a id="canvas-canvasspace-clear"></a>
##### `clear`

*overrides `MultiTouchSpace.clear`*

```ts
clear(bg: string): this
```

Clear the canvas with its background color. Overrides Space's `clear` function.

**Parameters**

- `bg` (`string`) — Optionally specify a custom background color in hex or rgba string, or "transparent". If not defined, it will use its `bgcolor` property as background color to clear the canvas.

<a id="canvas-canvasspace-clear-offscreen"></a>
##### `clearOffscreen`

```ts
clearOffscreen(bg: string | null): this
```

Similiar to `clear()` but clear the offscreen canvas instead

**Parameters**

- `bg` (`string | null`) — Optionally specify a custom background color in hex or rgba string, or "transparent". If not defined, it will use its `bgcolor` property as background color to clear the canvas.

<a id="canvas-canvasspace-dispose"></a>
##### `dispose`

```ts
dispose(): this
```

Dispose of browser resources held by this space and remove all players. Call this before unmounting the canvas.

<a id="canvas-canvasspace-get-form"></a>
##### `getForm`

*public · overrides `MultiTouchSpace.getForm`*

```ts
getForm(): CanvasForm
```

Get a new `CanvasForm` for drawing

**See also:** `CanvasForm`

<a id="canvas-canvasspace-play-items"></a>
##### `playItems`

*protected · overrides `MultiTouchSpace.playItems`*

```ts
playItems(time: number): void
```

Main animation function.

**Parameters**

- `time` (`number`) — current time

<a id="canvas-canvasspace-recorder"></a>
##### `recorder`

```ts
recorder(downloadOrCallback: boolean |  Fn(blobURL:string), filetype: string = "webm", bitrate: number = 15000000): MediaRecorder
```

Get a [`MediaRecorder`](https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder) to record the current CanvasSpace. You can then call its `start()` function to start recording, and `stop()` to either download the video file or handle the blob data in the callback function you provided.

**Parameters**

- `downloadOrCallback` (`boolean |  Fn(blobURL:string)`) — Either `true` to download the video, or provide a callback function to handle the Blob data, when recording is completed.
- `filetype` (`string`; default `"webm"`) — video format. Default is "webm".
- `bitrate` (`number`; default `15000000`) — bitrate per second

**Example**

```ts
let rec = space.recorder(true); rec.start(); setTimeout( () => rec.stop(), 5000); // record 5s of video and download the file
```

<a id="canvas-canvasspace-resize"></a>
##### `resize`

*overrides `MultiTouchSpace.resize`*

```ts
resize(b: Bound, evt: Event | null): this
```

This overrides Space's `resize` function. It's used as a callback function for window's resize event and not usually called directly. You can keep track of resize events with `resize: (bound ,evt)` callback in your player objects.

**Parameters**

- `b` (`Bound`) — a Bound object to resize to
- `evt` (`Event | null`) — Optionally pass a resize event

**See also:** Space.add

<a id="canvas-canvasspace-setup"></a>
##### `setup`

```ts
setup(opt: CanvasSpaceOptions): this
```

Set up various options for CanvasSpace. The `opt` parameter is an object with the following fields. This is usually set during instantiation, eg `new CanvasSpace(...).setup( { opt } )`

**Parameters**

- `opt` (`CanvasSpaceOptions`) — a [`CanvasSpaceOptions`](#types-canvasspaceoptions) object with optional settings, ie `{ bgcolor:string, resize:boolean, retina:boolean, offscreen:boolean, pixelDensity:number }`. Note that omitting `bgcolor` sets a transparent background (a long-standing behavior that differs from `DOMSpace.setup`, which keeps the current background when the option is absent).

**Example**

```ts
space.setup({ bgcolor: "#f00", retina: true, resize: true })
```

#### Inherited API

- From [`Space`](#space-space): [`center`](#space-space-center), [`customRendering`](#space-space-custom-rendering), [`height`](#space-space-height), [`innerBound`](#space-space-inner-bound), [`isPlaying`](#space-space-is-playing), [`outerBound`](#space-space-outer-bound), [`size`](#space-space-size), [`width`](#space-space-width), [`add`](#space-space-add), [`minFrameTime`](#space-space-min-frame-time), [`pause`](#space-space-pause), [`play`](#space-space-play), [`playOnce`](#space-space-play-once), [`refresh`](#space-space-refresh), [`remove`](#space-space-remove), [`render`](#space-space-render), [`replay`](#space-space-replay), [`resume`](#space-space-resume), [`stop`](#space-space-stop), [`bound`](#space-space-bound), [`id`](#space-space-id), [`playerCount`](#space-space-player-count), [`players`](#space-space-players).
- From [`MultiTouchSpace`](#space-multitouchspace): [`pointer`](#space-multitouchspace-pointer), [`bindCanvas`](#space-multitouchspace-bind-canvas), [`bindDoc`](#space-multitouchspace-bind-doc), [`bindKeyboard`](#space-multitouchspace-bind-keyboard), [`bindMouse`](#space-multitouchspace-bind-mouse), [`bindTouch`](#space-multitouchspace-bind-touch), [`removeAll`](#space-multitouchspace-remove-all), [`touchesToPoints`](#space-multitouchspace-touches-to-points), [`track`](#space-multitouchspace-track), [`unbindCanvas`](#space-multitouchspace-unbind-canvas), [`unbindDoc`](#space-multitouchspace-unbind-doc), [`untrack`](#space-multitouchspace-untrack).

<a id="module-color"></a>
## Module: `Color`

<a id="color-color"></a>
### `Color`

**Kind:** Class · **Source:** [`src/Color.ts:43`](https://github.com/williamngan/pts/blob/master/src/Color.ts#L43)

**Extends:** `Pt`

Color is a subclass of Pt. Since a color in a color space is analogous to a point or vector in a space, you can apply all Pt operations to colors too. The Color class provides support for many color spaces like HSL and LAB.
Convert non-RGB colors to RGB before using `.hex`, `.rgb`, or `.rgba` for rendering. These getters format the channels; they don't convert between color spaces.

#### Constructors

<a id="color-color-constructor"></a>
##### Constructor

*overrides `Pt.__constructor`*

```ts
new Color(args: any[]): Color
```

Create a Color. Same as creating a Pt. Optionally you may use [`Color.from`](#color-color-static-from) to create a color.

**Parameters**

- `args` (`any[]`) — Pt-like parameters which can be a list of numeric parameters, an array of numbers, or an object with {x,y,z,w} properties

#### Accessors

<a id="color-color-a"></a>
##### `a`

```ts
get a(): number
set a(n: number): void
```

the `a` value in LAB color mode. Same as `y`.

<a id="color-color-alpha"></a>
##### `alpha`

```ts
get alpha(): number
set alpha(n: number): void
```

Get alpha value

<a id="color-color-b"></a>
##### `b`

```ts
get b(): number
set b(n: number): void
```

the `b` value in RGB/LAB/HSB color mode. Same as `z`.

<a id="color-color-c"></a>
##### `c`

```ts
get c(): number
set c(n: number): void
```

the `c` value in LCH color mode. Same as `y`.

<a id="color-color-g"></a>
##### `g`

```ts
get g(): number
set g(n: number): void
```

the `g` value in RGB color mode. Same as `y`.

<a id="color-color-h"></a>
##### `h`

```ts
get h(): number
set h(n: number): void
```

the `h` value in HSL/HSB or LCH color mode. Same as either `x` or `z` depending on current color mode.

<a id="color-color-hex"></a>
##### `hex`

*public*

```ts
get hex(): string
```

Get a hex string such as "#FF0000". Same as `toString("hex")`.
For non-RGB colors, convert to RGB first.

<a id="color-color-l"></a>
##### `l`

```ts
get l(): number
set l(n: number): void
```

the `l` value in HSL or LCH/LAB color mode. Same as either `x` or `z` depending on current color mode.

<a id="color-color-mode"></a>
##### `mode`

```ts
get mode(): ColorType
```

Get this Color's mode.

<a id="color-color-normalized"></a>
##### `normalized`

```ts
get normalized(): boolean
set normalized(b: boolean): void
```

Check if color values are normalized (between 0 to 1). If conversion is needed, use [`Color.normalize`](#color-color-normalize) function.

<a id="color-color-r"></a>
##### `r`

```ts
get r(): number
set r(n: number): void
```

the `r` value in RGB color mode. Same as `x`.

<a id="color-color-rgb"></a>
##### `rgb`

*public*

```ts
get rgb(): string
```

Get a rgb string such as "rgb(255,0,0)". Same as `toString("rgb")`.
For non-RGB colors, convert to RGB first, eg `Color.HSLtoRGB(color).rgb`.

<a id="color-color-rgba"></a>
##### `rgba`

*public*

```ts
get rgba(): string
```

Get a rgba string such as "rgba(255,0,0,0.5)". Same as `toString("rgba")`.
For non-RGB colors, convert to RGB first.

<a id="color-color-s"></a>
##### `s`

```ts
get s(): number
set s(n: number): void
```

the `s` value in HSL/HSB color mode. Same as `y`.

<a id="color-color-u"></a>
##### `u`

```ts
get u(): number
set u(n: number): void
```

the `u` value in LUV color mode. Same as `y`.

<a id="color-color-v"></a>
##### `v`

```ts
get v(): number
set v(n: number): void
```

the `v` value in LUV color mode. Same as `z`.

<a id="color-color-static-ranges"></a>
##### `ranges`

*static*

```ts
get ranges():
set ranges(value: ): void
```

Value range for each color space

#### Methods

<a id="color-color-dollar-normalize"></a>
##### `$normalize`

```ts
$normalize(toNorm: boolean = true): Color
```

Like `normalize()` but returns a new Color.

**Parameters**

- `toNorm` (`boolean`; default `true`) — a boolean value specifying whether to normalize (`true`) or revert (`false`)

**Returns:** new Color

<a id="color-color-clone"></a>
##### `clone`

*overrides `Pt.clone`*

```ts
clone(): Color
```

Clone this Color.

<a id="color-color-normalize"></a>
##### `normalize`

```ts
normalize(toNorm: boolean = true): Color
```

Normalize the color values to between 0 to 1, or revert it back to the min/max values in current color mode.

**Parameters**

- `toNorm` (`boolean`; default `true`) — a boolean value specifying whether to normalize (`true`) or revert (`false`)

<a id="color-color-to-mode"></a>
##### `toMode`

```ts
toMode(mode: ColorType, convert: boolean = false): this
```

Convert this color from current color space to another color space.

**Parameters**

- `mode` (`ColorType`) — a ColorType string: "rgb" "hsl" "hsb" "lab" "lch" "luv" "xyz";
- `convert` (`boolean`; default `false`) — if `true`, convert this Color to the new color space specified in `mode`. Default is `false`, which only sets the color mode without converting color values.

<a id="color-color-to-string"></a>
##### `toString`

*overrides `Pt.toString`*

```ts
toString(format: rgb | rgba | hex | mode = "mode"): string
```

Convert this Color to a string. It can be used to get a hex or rgb string for use in rendering.
This formats the current channels without converting color spaces. Convert to RGB before requesting "hex", "rgb", or "rgba". The default "mode" format is for inspecting values, not for CSS rendering.

**Parameters**

- `format` (`rgb | rgba | hex | mode`; default `"mode"`) — "hex", "rgb", "rgba", or "mode" which means using current color mode label. Default is "mode".

<a id="color-color-static-from"></a>
##### `from`

*static · overrides `Pt.from`*

```ts
static from(args: any[]): Color
```

Create a Color object with 4 default dimensional values (1,1,1,1).

**Parameters**

- `args` (`any[]`) — Pt-like parameters which can be a list of numeric parameters, an array of numbers, or an object with {x,y,z,w} properties

<a id="color-color-static-from-hex"></a>
##### `fromHex`

*static*

```ts
static fromHex(hex: string): Color
```

Convert a rgb hex string like `"#FF0000"` or `"#F00"` to a Color object.

**Parameters**

- `hex` (`string`) — a hex string, with optional '#' prefix

<a id="color-color-static-hsb"></a>
##### `hsb`

*static*

```ts
static hsb(args: any[]): Color
```

Create HSB Color. HSB color ranges are (0...360, 0...1, 0...1) respectively. You may use [`Color.normalize`](#color-color-normalize) to convert the ranges to 0...1.

**Parameters**

- `args` (`any[]`) — Pt-like parameters which can be a list of numeric parameters, an array of numbers, or an object with {x,y,z,w} properties.

<a id="color-color-static-hsbto-rgb"></a>
##### `HSBtoRGB`

*static*

```ts
static HSBtoRGB(hsb: Color, normalizedInput: boolean = false, normalizedOutput: boolean = false): Color
```

A static function to convert HSB to RGB.

**Parameters**

- `hsb` (`Color`) — a HSB Color
- `normalizedInput` (`boolean`; default `false`) — a boolean specifying whether input color is normalized. Default is not normalized: `false`.
- `normalizedOutput` (`boolean`; default `false`) — a boolean specifying whether output color shoud be normalized. Default is not normalized: `false`.

**Returns:** a new RGB Color

<a id="color-color-static-hsl"></a>
##### `hsl`

*static*

```ts
static hsl(args: any[]): Color
```

Create HSL Color. HSL color ranges are (0...360, 0...1, 0...1) respectively. You may use [`Color.normalize`](#color-color-normalize) to convert the ranges to 0...1.

**Parameters**

- `args` (`any[]`) — Pt-like parameters which can be a list of numeric parameters, an array of numbers, or an object with {x,y,z,w} properties.

<a id="color-color-static-hslto-rgb"></a>
##### `HSLtoRGB`

*static*

```ts
static HSLtoRGB(hsl: Color, normalizedInput: boolean = false, normalizedOutput: boolean = false): Color
```

A static function to convert HSL to RGB.

**Parameters**

- `hsl` (`Color`) — a HSL Color
- `normalizedInput` (`boolean`; default `false`) — a boolean specifying whether input color is normalized. Default is not normalized: `false`.
- `normalizedOutput` (`boolean`; default `false`) — a boolean specifying whether output color shoud be normalized. Default is not normalized: `false`.

**Returns:** a new RGB Color

<a id="color-color-static-lab"></a>
##### `lab`

*static*

```ts
static lab(args: any[]): Color
```

Create LAB Color. LAB color ranges are (0...100, -128...127, -128...127) respectively. You may use [`Color.normalize`](#color-color-normalize) to convert the ranges to 0...1.

**Parameters**

- `args` (`any[]`) — Pt-like parameters which can be a list of numeric parameters, an array of numbers, or an object with {x,y,z,w} properties.

<a id="color-color-static-labto-lch"></a>
##### `LABtoLCH`

*static*

```ts
static LABtoLCH(lab: Color, normalizedInput: boolean = false, normalizedOutput: boolean = false): Color
```

A static function to convert LAB to LCH.

**Parameters**

- `lab` (`Color`) — a LAB Color
- `normalizedInput` (`boolean`; default `false`) — a boolean specifying whether input color is normalized. Default is not normalized: `false`.
- `normalizedOutput` (`boolean`; default `false`) — a boolean specifying whether output color shoud be normalized. Default is not normalized: `false`.

**Returns:** a new LCH Color

<a id="color-color-static-labto-rgb"></a>
##### `LABtoRGB`

*static*

```ts
static LABtoRGB(lab: Color, normalizedInput: boolean = false, normalizedOutput: boolean = false): Color
```

A static function to convert LAB to RGB.

**Parameters**

- `lab` (`Color`) — a LAB Color
- `normalizedInput` (`boolean`; default `false`) — a boolean specifying whether input color is normalized. Default is not normalized: `false`.
- `normalizedOutput` (`boolean`; default `false`) — a boolean specifying whether output color shoud be normalized. Default is not normalized: `false`.

**Returns:** a new RGB Color

<a id="color-color-static-labto-xyz"></a>
##### `LABtoXYZ`

*static*

```ts
static LABtoXYZ(lab: Color, normalizedInput: boolean = false, normalizedOutput: boolean = false): Color
```

A static function to convert LAB to XYZ.

**Parameters**

- `lab` (`Color`) — a LAB Color
- `normalizedInput` (`boolean`; default `false`) — a boolean specifying whether input color is normalized. Default is not normalized: `false`.
- `normalizedOutput` (`boolean`; default `false`) — a boolean specifying whether output color shoud be normalized. Default is not normalized: `false`.

**Returns:** a new XYZ Color

<a id="color-color-static-lch"></a>
##### `lch`

*static*

```ts
static lch(args: any[]): Color
```

Create LCH Color. LCH color ranges are (0...100, 0...100, 0...360) respectively. You may use [`Color.normalize`](#color-color-normalize) to convert the ranges to 0...1.

**Parameters**

- `args` (`any[]`) — Pt-like parameters which can be a list of numeric parameters, an array of numbers, or an object with {x,y,z,w} properties.

<a id="color-color-static-lchto-lab"></a>
##### `LCHtoLAB`

*static*

```ts
static LCHtoLAB(lch: Color, normalizedInput: boolean = false, normalizedOutput: boolean = false): Color
```

A static function to convert LCH to LAB.

**Parameters**

- `lch` (`Color`) — a LCH Color
- `normalizedInput` (`boolean`; default `false`) — a boolean specifying whether input color is normalized. Default is not normalized: `false`.
- `normalizedOutput` (`boolean`; default `false`) — a boolean specifying whether output color shoud be normalized. Default is not normalized: `false`.

**Returns:** a new LAB Color

<a id="color-color-static-lchto-rgb"></a>
##### `LCHtoRGB`

*static*

```ts
static LCHtoRGB(lch: Color, normalizedInput: boolean = false, normalizedOutput: boolean = false): Color
```

A static function to convert LCH to RGB.

**Parameters**

- `lch` (`Color`) — a LCH Color
- `normalizedInput` (`boolean`; default `false`) — a boolean specifying whether input color is normalized. Default is not normalized: `false`.
- `normalizedOutput` (`boolean`; default `false`) — a boolean specifying whether output color shoud be normalized. Default is not normalized: `false`.

**Returns:** a new RGB Color

<a id="color-color-static-luv"></a>
##### `luv`

*static*

```ts
static luv(args: any[]): Color
```

Create LUV Color. LUV color ranges are (0...100, -134...220, -140...122) respectively. You may use [`Color.normalize`](#color-color-normalize) to convert the ranges to 0...1.

**Parameters**

- `args` (`any[]`) — Pt-like parameters which can be a list of numeric parameters, an array of numbers, or an object with {x,y,z,w} properties.

<a id="color-color-static-luvto-rgb"></a>
##### `LUVtoRGB`

*static*

```ts
static LUVtoRGB(luv: Color, normalizedInput: boolean = false, normalizedOutput: boolean = false): Color
```

A static function to convert LUV to RGB.

**Parameters**

- `luv` (`Color`) — a LUV Color
- `normalizedInput` (`boolean`; default `false`) — a boolean specifying whether input color is normalized. Default is not normalized: `false`.
- `normalizedOutput` (`boolean`; default `false`) — a boolean specifying whether output color shoud be normalized. Default is not normalized: `false`.

**Returns:** a new RGB Color

<a id="color-color-static-luvto-xyz"></a>
##### `LUVtoXYZ`

*static*

```ts
static LUVtoXYZ(luv: Color, normalizedInput: boolean = false, normalizedOutput: boolean = false): Color
```

A static function to convert LUV to XYZ.

**Parameters**

- `luv` (`Color`) — a LUV Color
- `normalizedInput` (`boolean`; default `false`) — a boolean specifying whether input color is normalized. Default is not normalized: `false`.
- `normalizedOutput` (`boolean`; default `false`) — a boolean specifying whether output color shoud be normalized. Default is not normalized: `false`.

**Returns:** a new XYZ Color

<a id="color-color-static-max-values"></a>
##### `maxValues`

*static*

```ts
static maxValues(mode: string): Pt
```

Get a Color object whose values are the maximum of its mode.

**Parameters**

- `mode` (`string`) — a mode string such as "rgb" or "lab"

**Example**

```ts
Color.maxValue("rgb") will return a rgb Color object with values (255,255,255)
```

<a id="color-color-static-oklab"></a>
##### `oklab`

*static*

```ts
static oklab(args: any[]): Color
```

Create OKLAB Color. OKLAB color ranges are (0...1, -0.4...0.4, -0.4...0.4) respectively. You may use [`Color.normalize`](#color-color-normalize) to convert the ranges to 0...1.

**Parameters**

- `args` (`any[]`) — Pt-like parameters which can be a list of numeric parameters, an array of numbers, or an object with {x,y,z,w} properties.

<a id="color-color-static-oklabto-oklch"></a>
##### `OKLABtoOKLCH`

*static*

```ts
static OKLABtoOKLCH(oklab: Color, normalizedInput: boolean = false, normalizedOutput: boolean = false): Color
```

A static function to convert OKLAB to OKLCH.

**Parameters**

- `oklab` (`Color`) — an OKLAB Color
- `normalizedInput` (`boolean`; default `false`) — a boolean specifying whether input color is normalized. Default is not normalized: `false`.
- `normalizedOutput` (`boolean`; default `false`) — a boolean specifying whether output color shoud be normalized. Default is not normalized: `false`.

**Returns:** a new OKLCH Color

<a id="color-color-static-oklabto-rgb"></a>
##### `OKLABtoRGB`

*static*

```ts
static OKLABtoRGB(oklab: Color, normalizedInput: boolean = false, normalizedOutput: boolean = false): Color
```

A static function to convert OKLAB to RGB. Out-of-gamut results are clamped to the sRGB range.

**Parameters**

- `oklab` (`Color`) — an OKLAB Color
- `normalizedInput` (`boolean`; default `false`) — a boolean specifying whether input color is normalized. Default is not normalized: `false`.
- `normalizedOutput` (`boolean`; default `false`) — a boolean specifying whether output color shoud be normalized. Default is not normalized: `false`.

**Returns:** a new RGB Color

<a id="color-color-static-oklch"></a>
##### `oklch`

*static*

```ts
static oklch(args: any[]): Color
```

Create OKLCH Color. OKLCH color ranges are (0...1, 0...0.4, 0...360) respectively. You may use [`Color.normalize`](#color-color-normalize) to convert the ranges to 0...1.

**Parameters**

- `args` (`any[]`) — Pt-like parameters which can be a list of numeric parameters, an array of numbers, or an object with {x,y,z,w} properties.

<a id="color-color-static-oklchto-oklab"></a>
##### `OKLCHtoOKLAB`

*static*

```ts
static OKLCHtoOKLAB(oklch: Color, normalizedInput: boolean = false, normalizedOutput: boolean = false): Color
```

A static function to convert OKLCH to OKLAB.

**Parameters**

- `oklch` (`Color`) — an OKLCH Color
- `normalizedInput` (`boolean`; default `false`) — a boolean specifying whether input color is normalized. Default is not normalized: `false`.
- `normalizedOutput` (`boolean`; default `false`) — a boolean specifying whether output color shoud be normalized. Default is not normalized: `false`.

**Returns:** a new OKLAB Color

<a id="color-color-static-oklchto-rgb"></a>
##### `OKLCHtoRGB`

*static*

```ts
static OKLCHtoRGB(oklch: Color, normalizedInput: boolean = false, normalizedOutput: boolean = false): Color
```

A static function to convert OKLCH to RGB. Out-of-gamut results are clamped to the sRGB range.

**Parameters**

- `oklch` (`Color`) — an OKLCH Color
- `normalizedInput` (`boolean`; default `false`) — a boolean specifying whether input color is normalized. Default is not normalized: `false`.
- `normalizedOutput` (`boolean`; default `false`) — a boolean specifying whether output color shoud be normalized. Default is not normalized: `false`.

**Returns:** a new RGB Color

<a id="color-color-static-rgb"></a>
##### `rgb`

*static*

```ts
static rgb(args: any[]): Color
```

Create RGB Color. RGB color ranges are (0...255, 0...255, 0...255) respectively. You may use [`Color.normalize`](#color-color-normalize) to convert the ranges to 0...1.

**Parameters**

- `args` (`any[]`) — Pt-like parameters which can be a list of numeric parameters, an array of numbers, or an object with {x,y,z,w} properties.

<a id="color-color-static-rgbto-hsb"></a>
##### `RGBtoHSB`

*static*

```ts
static RGBtoHSB(rgb: Color, normalizedInput: boolean = false, normalizedOutput: boolean = false): Color
```

A static function to convert RGB to HSB.

**Parameters**

- `rgb` (`Color`) — a RGB Color
- `normalizedInput` (`boolean`; default `false`) — a boolean specifying whether input color is normalized. Default is not normalized: `false`.
- `normalizedOutput` (`boolean`; default `false`) — a boolean specifying whether output color shoud be normalized. Default is not normalized: `false`.

**Returns:** a new HSB Color

<a id="color-color-static-rgbto-hsl"></a>
##### `RGBtoHSL`

*static*

```ts
static RGBtoHSL(rgb: Color, normalizedInput: boolean = false, normalizedOutput: boolean = false): Color
```

A static function to convert RGB to HSL.

**Parameters**

- `rgb` (`Color`) — a RGB Color
- `normalizedInput` (`boolean`; default `false`) — a boolean specifying whether input color is normalized. Default is not normalized: `false`.
- `normalizedOutput` (`boolean`; default `false`) — a boolean specifying whether output color shoud be normalized. Default is not normalized: `false`.

**Returns:** a new HSL Color

<a id="color-color-static-rgbto-lab"></a>
##### `RGBtoLAB`

*static*

```ts
static RGBtoLAB(rgb: Color, normalizedInput: boolean = false, normalizedOutput: boolean = false): Color
```

A static function to convert RGB to LAB.

**Parameters**

- `rgb` (`Color`) — a RGB Color
- `normalizedInput` (`boolean`; default `false`) — a boolean specifying whether input color is normalized. Default is not normalized: `false`.
- `normalizedOutput` (`boolean`; default `false`) — a boolean specifying whether output color shoud be normalized. Default is not normalized: `false`.

**Returns:** a new LAB Color

<a id="color-color-static-rgbto-lch"></a>
##### `RGBtoLCH`

*static*

```ts
static RGBtoLCH(rgb: Color, normalizedInput: boolean = false, normalizedOutput: boolean = false): Color
```

A static function to convert RGB to LCH.

**Parameters**

- `rgb` (`Color`) — a RGB Color
- `normalizedInput` (`boolean`; default `false`) — a boolean specifying whether input color is normalized. Default is not normalized: `false`.
- `normalizedOutput` (`boolean`; default `false`) — a boolean specifying whether output color shoud be normalized. Default is not normalized: `false`.

**Returns:** a new LCH Color

<a id="color-color-static-rgbto-luv"></a>
##### `RGBtoLUV`

*static*

```ts
static RGBtoLUV(rgb: Color, normalizedInput: boolean = false, normalizedOutput: boolean = false): Color
```

A static function to convert RGB to LUV.

**Parameters**

- `rgb` (`Color`) — a RGB Color
- `normalizedInput` (`boolean`; default `false`) — a boolean specifying whether input color is normalized. Default is not normalized: `false`.
- `normalizedOutput` (`boolean`; default `false`) — a boolean specifying whether output color shoud be normalized. Default is not normalized: `false`.

**Returns:** a new LUV Color

<a id="color-color-static-rgbto-oklab"></a>
##### `RGBtoOKLAB`

*static*

```ts
static RGBtoOKLAB(rgb: Color, normalizedInput: boolean = false, normalizedOutput: boolean = false): Color
```

A static function to convert RGB to OKLAB (Ottosson 2020, as specified in CSS Color 4). OKLAB improves on LAB's perceptual uniformity, especially hue stability in blues.

**Parameters**

- `rgb` (`Color`) — a RGB Color
- `normalizedInput` (`boolean`; default `false`) — a boolean specifying whether input color is normalized. Default is not normalized: `false`.
- `normalizedOutput` (`boolean`; default `false`) — a boolean specifying whether output color shoud be normalized. Default is not normalized: `false`.

**Returns:** a new OKLAB Color

<a id="color-color-static-rgbto-oklch"></a>
##### `RGBtoOKLCH`

*static*

```ts
static RGBtoOKLCH(rgb: Color, normalizedInput: boolean = false, normalizedOutput: boolean = false): Color
```

A static function to convert RGB to OKLCH, the cylindrical form of OKLAB as specified in CSS Color 4.

**Parameters**

- `rgb` (`Color`) — a RGB Color
- `normalizedInput` (`boolean`; default `false`) — a boolean specifying whether input color is normalized. Default is not normalized: `false`.
- `normalizedOutput` (`boolean`; default `false`) — a boolean specifying whether output color shoud be normalized. Default is not normalized: `false`.

**Returns:** a new OKLCH Color

<a id="color-color-static-rgbto-xyz"></a>
##### `RGBtoXYZ`

*static*

```ts
static RGBtoXYZ(rgb: Color, normalizedInput: boolean = false, normalizedOutput: boolean = false): Color
```

A static function to convert RGB to XYZ.

**Parameters**

- `rgb` (`Color`) — a RGB Color
- `normalizedInput` (`boolean`; default `false`) — a boolean specifying whether input color is normalized. Default is not normalized: `false`.
- `normalizedOutput` (`boolean`; default `false`) — a boolean specifying whether output color shoud be normalized. Default is not normalized: `false`.

**Returns:** a new XYZ Color

<a id="color-color-static-xyz"></a>
##### `xyz`

*static*

```ts
static xyz(args: any[]): Color
```

Create XYZ Color. XYZ color ranges are (0...100, 0...100, 0...100) respectively. You may use [`Color.normalize`](#color-color-normalize) to convert the ranges to 0...1.

**Parameters**

- `args` (`any[]`) — Pt-like parameters which can be a list of numeric parameters, an array of numbers, or an object with {x,y,z,w} properties.

<a id="color-color-static-xyzto-lab"></a>
##### `XYZtoLAB`

*static*

```ts
static XYZtoLAB(xyz: Color, normalizedInput: boolean = false, normalizedOutput: boolean = false): Color
```

A static function to convert XYZ to LAB.

**Parameters**

- `xyz` (`Color`) — a XYZ Color
- `normalizedInput` (`boolean`; default `false`) — a boolean specifying whether input color is normalized. Default is not normalized: `false`.
- `normalizedOutput` (`boolean`; default `false`) — a boolean specifying whether output color shoud be normalized. Default is not normalized: `false`.

**Returns:** a new LAB Color

<a id="color-color-static-xyzto-luv"></a>
##### `XYZtoLUV`

*static*

```ts
static XYZtoLUV(xyz: Color, normalizedInput: boolean = false, normalizedOutput: boolean = false): Color
```

A static function to convert XYZ to LUV.

**Parameters**

- `xyz` (`Color`) — a XYZ Color
- `normalizedInput` (`boolean`; default `false`) — a boolean specifying whether input color is normalized. Default is not normalized: `false`.
- `normalizedOutput` (`boolean`; default `false`) — a boolean specifying whether output color shoud be normalized. Default is not normalized: `false`.

**Returns:** a new LUV Color

<a id="color-color-static-xyzto-rgb"></a>
##### `XYZtoRGB`

*static*

```ts
static XYZtoRGB(xyz: Color, normalizedInput: boolean = false, normalizedOutput: boolean = false): Color
```

A static function to convert XYZ to RGB.

**Parameters**

- `xyz` (`Color`) — a XYZ Color
- `normalizedInput` (`boolean`; default `false`) — a boolean specifying whether input color is normalized. Default is not normalized: `false`.
- `normalizedOutput` (`boolean`; default `false`) — a boolean specifying whether output color shoud be normalized. Default is not normalized: `false`.

**Returns:** a new RGB Color

#### Inherited API

- From [`Pt`](#pt-pt): [`id`](#pt-pt-id), [`w`](#pt-pt-w), [`x`](#pt-pt-x), [`y`](#pt-pt-y), [`z`](#pt-pt-z), [`$abs`](#pt-pt-dollar-abs), [`$add`](#pt-pt-dollar-add), [`$ceil`](#pt-pt-dollar-ceil), [`$concat`](#pt-pt-dollar-concat), [`$cross`](#pt-pt-dollar-cross), [`$cross2D`](#pt-pt-dollar-cross2-d), [`$divide`](#pt-pt-dollar-divide), [`$floor`](#pt-pt-dollar-floor), [`$max`](#pt-pt-dollar-max), [`$min`](#pt-pt-dollar-min), [`$multiply`](#pt-pt-dollar-multiply), [`$project`](#pt-pt-dollar-project), [`$round`](#pt-pt-dollar-round), [`$subtract`](#pt-pt-dollar-subtract), [`$take`](#pt-pt-dollar-take), [`$to`](#pt-pt-dollar-to), [`$unit`](#pt-pt-dollar-unit), [`abs`](#pt-pt-abs), [`add`](#pt-pt-add), [`angle`](#pt-pt-angle), [`angleBetween`](#pt-pt-angle-between), [`ceil`](#pt-pt-ceil), [`divide`](#pt-pt-divide), [`dot`](#pt-pt-dot), [`equals`](#pt-pt-equals), [`floor`](#pt-pt-floor), [`magnitude`](#pt-pt-magnitude), [`magnitudeSq`](#pt-pt-magnitude-sq), [`maxValue`](#pt-pt-max-value), [`minValue`](#pt-pt-min-value), [`multiply`](#pt-pt-multiply), [`op`](#pt-pt-op), [`ops`](#pt-pt-ops), [`projectScalar`](#pt-pt-project-scalar), [`reflect2D`](#pt-pt-reflect2-d), [`rotate2D`](#pt-pt-rotate2-d), [`round`](#pt-pt-round), [`scale`](#pt-pt-scale), [`shear2D`](#pt-pt-shear2-d), [`subtract`](#pt-pt-subtract), [`to`](#pt-pt-to), [`toAngle`](#pt-pt-to-angle), [`toArray`](#pt-pt-to-array), [`toBound`](#pt-pt-to-bound), [`toGroup`](#pt-pt-to-group), [`unit`](#pt-pt-unit), [`make`](#pt-pt-static-make).
- From [`Float32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array): 26 standard properties and methods (not repeated here).

<a id="module-create"></a>
## Module: `Create`

<a id="create-boid"></a>
### `Boid`

**Kind:** Class · **Source:** [`src/Create.ts:906`](https://github.com/williamngan/pts/blob/master/src/Create.ts#L906)

**Extends:** `Pt`

Boid is a subclass of [`Pt`](#pt-pt) that represents a single agent in a [`Flock`](#create-flock).
Its own values are the agent's position, and it carries a `velocity` that [`Flock.step`](#create-flock-step)
integrates. Create them through [`Create.flock`](#create-create-static-flock) or [`Flock.addBoid`](#create-flock-add-boid).
See [a demo here](https://ptsjs.org/demo/?name=create.flock).

#### Accessors

<a id="create-boid-heading"></a>
##### `heading`

```ts
get heading(): number
```

The angle this agent is heading toward, in radians. Note that a stationary agent has no
heading and reports 0 (pointing along +x) rather than NaN. Set a [`Flock`](#create-flock)'s
`minSpeed` if you are drawing headings and want to avoid that.

<a id="create-boid-speed"></a>
##### `speed`

```ts
get speed(): number
```

This agent's speed, in units per second.

<a id="create-boid-velocity"></a>
##### `velocity`

```ts
get velocity(): Pt
set velocity(v: Pt): void
```

This agent's velocity, in units per second.

#### Inherited API

- From [`Pt`](#pt-pt): [`constructor`](#pt-pt-constructor), [`id`](#pt-pt-id), [`w`](#pt-pt-w), [`x`](#pt-pt-x), [`y`](#pt-pt-y), [`z`](#pt-pt-z), [`$abs`](#pt-pt-dollar-abs), [`$add`](#pt-pt-dollar-add), [`$ceil`](#pt-pt-dollar-ceil), [`$concat`](#pt-pt-dollar-concat), [`$cross`](#pt-pt-dollar-cross), [`$cross2D`](#pt-pt-dollar-cross2-d), [`$divide`](#pt-pt-dollar-divide), [`$floor`](#pt-pt-dollar-floor), [`$max`](#pt-pt-dollar-max), [`$min`](#pt-pt-dollar-min), [`$multiply`](#pt-pt-dollar-multiply), [`$project`](#pt-pt-dollar-project), [`$round`](#pt-pt-dollar-round), [`$subtract`](#pt-pt-dollar-subtract), [`$take`](#pt-pt-dollar-take), [`$to`](#pt-pt-dollar-to), [`$unit`](#pt-pt-dollar-unit), [`abs`](#pt-pt-abs), [`add`](#pt-pt-add), [`angle`](#pt-pt-angle), [`angleBetween`](#pt-pt-angle-between), [`ceil`](#pt-pt-ceil), [`clone`](#pt-pt-clone), [`divide`](#pt-pt-divide), [`dot`](#pt-pt-dot), [`equals`](#pt-pt-equals), [`floor`](#pt-pt-floor), [`magnitude`](#pt-pt-magnitude), [`magnitudeSq`](#pt-pt-magnitude-sq), [`maxValue`](#pt-pt-max-value), [`minValue`](#pt-pt-min-value), [`multiply`](#pt-pt-multiply), [`op`](#pt-pt-op), [`ops`](#pt-pt-ops), [`projectScalar`](#pt-pt-project-scalar), [`reflect2D`](#pt-pt-reflect2-d), [`rotate2D`](#pt-pt-rotate2-d), [`round`](#pt-pt-round), [`scale`](#pt-pt-scale), [`shear2D`](#pt-pt-shear2-d), [`subtract`](#pt-pt-subtract), [`to`](#pt-pt-to), [`toAngle`](#pt-pt-to-angle), [`toArray`](#pt-pt-to-array), [`toBound`](#pt-pt-to-bound), [`toGroup`](#pt-pt-to-group), [`toString`](#pt-pt-to-string), [`unit`](#pt-pt-unit), [`make`](#pt-pt-static-make).
- From [`Float32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array): 26 standard properties and methods (not repeated here).

<a id="create-create"></a>
### `Create`

**Kind:** Class · **Source:** [`src/Create.ts:23`](https://github.com/williamngan/pts/blob/master/src/Create.ts#L23)

The `Create` class helps you create structures from sets of points.

#### Methods

<a id="create-create-static-delaunay"></a>
##### `delaunay`

*static*

```ts
static delaunay(pts: GroupLike): Delaunay
```

Create a Delaunay Group. Use the [`Delaunay.delaunay()`](#create-delaunay-delaunay) and [`Delaunay.voronoi()`](#create-delaunay-voronoi) functions in the returned group to generate tessellations.

**Parameters**

- `pts` (`GroupLike`) — a Group or an array of Pts

**Returns:** an instance of the Delaunay class

<a id="create-create-static-distribute-linear"></a>
##### `distributeLinear`

*static*

```ts
static distributeLinear(line: PtIterable, count: number): Group
```

Create a set of points that distribute evenly on a line. Similar to [`Line.subpoints`](#op-line-static-subpoints) but includes the end points.

**Parameters**

- `line` (`PtIterable`) — a Group or an Iterable<Pt> representing a line
- `count` (`number`) — number of points to create

<a id="create-create-static-distribute-random"></a>
##### `distributeRandom`

*static*

```ts
static distributeRandom(bound: Bound, count: number, dimensions: number = 2): Group
```

Create a set of random points inside a bounday.

**Parameters**

- `bound` (`Bound`) — the rectangular boundary
- `count` (`number`) — number of random points to create
- `dimensions` (`number`; default `2`) — number of dimensions in each point

<a id="create-create-static-flock"></a>
##### `flock`

*static*

```ts
static flock(pts: PtLikeIterable, options: FlockOptions = {}): Flock
```

Create a [`Flock`](#create-flock) of [`Boid`](#create-boid) agents that simulate flocking (also known as "boids"),
where each agent steers by three local rules: separation, alignment, and cohesion.
Advance the simulation by calling [`Flock.step`](#create-flock-step) with the elapsed time.
See a [flocking demo here](https://ptsjs.org/demo/?name=create.flock).

Each agent starts with a random heading, drawn from [`Num.random`](#num-num-static-random), so seeding with
[`Num.seed`](#num-num-static-seed) makes a flock reproducible.

**Parameters**

- `pts` (`PtLikeIterable`) — a Group or an Iterable<Pt> of starting positions
- `options` (`FlockOptions`; default `{}`) — optional [`FlockOptions`](#types-flockoptions) to tune the behavior

**Returns:** an instance of the Flock class, which is a Group of Boids

**Example**

```ts
Create.flock( Create.distributeRandom( space.innerBound, 200 ), { bound: space.innerBound } )
```

<a id="create-create-static-grid-cells"></a>
##### `gridCells`

*static*

```ts
static gridCells(bound: Bound, columns: number, rows: number): Group[]
```

Create a grid of cells inside a boundary, where each cell is defined by a group of 2 Pt.

**Parameters**

- `bound` (`Bound`) — the rectangular boundary
- `columns` (`number`) — number of columns
- `rows` (`number`) — number of rows

**Returns:** an array of Groups, where each group represents a rectangular cell

<a id="create-create-static-grid-pts"></a>
##### `gridPts`

*static*

```ts
static gridPts(bound: Bound, columns: number, rows: number, orientation: PtLike = ...): Group
```

Create an evenly distributed set of points (like a grid of points) inside a boundary.

**Parameters**

- `bound` (`Bound`) — the rectangular boundary
- `columns` (`number`) — number of columns
- `rows` (`number`) — number of rows
- `orientation` (`PtLike`; default `...`) — a Pt or number array to specify where the point should be inside a cell. Default is [0.5, 0.5] which places the point in the middle.

**Returns:** a Group of Pts

<a id="create-create-static-noise-pts"></a>
##### `noisePts`

*static*

```ts
static noisePts(pts: PtIterable, dx: number = 0.01, dy: number = 0.01, rows: number = 0, columns: number = 0): Group
```

Given a group of Pts, return a new group of `Noise` Pts.

**Parameters**

- `pts` (`PtIterable`) — a Group or an Iterable<Pt>, in row-major order when treated as a grid
- `dx` (`number`; default `0.01`) — small increment value in x dimension
- `dy` (`number`; default `0.01`) — small increment value in y dimension
- `rows` (`number`; default `0`) — Optional row count to generate 2D noise
- `columns` (`number`; default `0`) — Optional column count (points per row) to generate 2D noise. When provided, each point's noise offset is (dx·column, dy·row) with row = floor(i/columns); when only `rows` is provided it is used as the points-per-row divisor instead.

<a id="create-create-static-radial-pts"></a>
##### `radialPts`

*static*

```ts
static radialPts(center: PtLike, radius: number, count: number, angleOffset: number = -Const.half_pi): Group
```

Create a set of Pts around a circular path.

**Parameters**

- `center` (`PtLike`) — circle center
- `radius` (`number`) — circle radius
- `count` (`number`) — number of Pts to create
- `angleOffset` (`number`; default `-Const.half_pi`) — offset starting angle

<a id="create-create-static-sampling"></a>
##### `sampling`

*static*

```ts
static sampling(bound: Bound, radius: number, options: PoissonDiskOptions = {}): PoissonDisk
```

Create a set of Pts that are randomly placed but never closer than `radius` to each other,
using Poisson-disk sampling (also called blue noise).
Compared with [`Create.distributeRandom`](#create-create-static-distribute-random), the points avoid clumping.
Sampling uses a finite candidate budget, so gaps can remain when it finishes.
The returned [`PoissonDisk`](#create-poissondisk) is a complete Group; to grow a set gradually instead,
construct a `PoissonDisk` and call its [`PoissonDisk.step`](#create-poissondisk-step) or [`PoissonDisk.sample`](#create-poissondisk-sample).
See a [demo here](https://ptsjs.org/demo/?name=create.sampling).

Randomness comes from [`Num.random`](#num-num-static-random), so seeding with [`Num.seed`](#num-num-static-seed) makes the set reproducible.

**Parameters**

- `bound` (`Bound`) — the rectangular boundary
- `radius` (`number`) — minimum distance between any two points
- `options` (`PoissonDiskOptions`; default `{}`) — optional [`PoissonDiskOptions`](#types-poissondiskoptions)

**Returns:** an instance of the PoissonDisk class, which is a Group of Pts

**Example**

```ts
Create.sampling( space.innerBound, 10 )
```

<a id="create-delaunay"></a>
### `Delaunay`

**Kind:** Class · **Source:** [`src/Create.ts:529`](https://github.com/williamngan/pts/blob/master/src/Create.ts#L529)

**Extends:** `Group`

Delaunay is a [`Group`](#pt-group) of Pts that generates Delaunay and Voronoi tessellations.
Points are triangulated by incremental insertion in Hilbert-curve order with exact
orientation and in-circle tests, so grids, collinear runs, points on edges, and duplicate
points are handled without degenerate triangles.

#### Methods

<a id="create-delaunay-delaunay"></a>
##### `delaunay`

```ts
delaunay(triangleOnly: boolean = true): GroupLike[] | DelaunayShape[]
```

Generate Delaunay triangles. This function also caches the mesh that is used to generate Voronoi tessellation in `voronoi()`. See a [Delaunay demo here](https://ptsjs.org/demo/?name=create.delaunay).

**Parameters**

- `triangleOnly` (`boolean`; default `true`) — if true, returns an array of triangles in Groups, otherwise return the whole DelaunayShape

**Returns:** an array of Groups or an array of DelaunayShapes `{i, j, k, triangle, circle}` which records the indices of the vertices, and the calculated triangles and circumcircles

<a id="create-delaunay-mesh"></a>
##### `mesh`

```ts
mesh(): DelaunayMesh
```

Get the cached mesh. The mesh is an array of objects, each of which representing the enclosing triangles around a Pt in this Delaunay group.

**Returns:** an array of objects that store a series of DelaunayShapes

<a id="create-delaunay-neighbor-pts"></a>
##### `neighborPts`

```ts
neighborPts(i: number, sort: boolean = false): GroupLike
```

Given an index of a Pt in this Delaunay Group, returns its neighboring Pts in the network.

**Parameters**

- `i` (`number`) — index of a Pt
- `sort` (`boolean`; default `false`) — if true, sort the neighbors so that their edges will form a polygon

**Returns:** an array of Pts

<a id="create-delaunay-neighbors"></a>
##### `neighbors`

```ts
neighbors(i: number): DelaunayShape[]
```

Given an index of a Pt in this Delaunay Group, returns its neighboring DelaunayShapes.

**Parameters**

- `i` (`number`) — index of a Pt

**Returns:** an array of DelaunayShapes `{i, j, k, triangle, circle}`

<a id="create-delaunay-voronoi"></a>
##### `voronoi`

```ts
voronoi(bound: PtIterable): Group[]
```

Generate Voronoi cells. `delaunay()` must be called before calling this function. See a [Voronoi demo here](https://ptsjs.org/demo/?name=create.delaunay).

**Parameters**

- `bound` (`PtIterable`) — Optionally provide a rectangular bound (eg, `space.innerBound`) to clip the cells against, including the unbounded cells on the convex hull. Without a bound, cells around sliver triangles can extend to enormous coordinates (circumcenters of nearly-collinear points), which is technically correct but extremely slow to draw.

**Returns:** an array of Groups, each of which represents a Voronoi cell. Unclipped cells share their vertex Pts with the cached mesh (see [`Delaunay.mesh`](#create-delaunay-mesh)), so treat them as read-only or clone before mutating.

#### Inherited API

- From [`Group`](#pt-group): [`constructor`](#pt-group-constructor), [`id`](#pt-group-id), [`p1`](#pt-group-p1), [`p2`](#pt-group-p2), [`p3`](#pt-group-p3), [`p4`](#pt-group-p4), [`q1`](#pt-group-q1), [`q2`](#pt-group-q2), [`q3`](#pt-group-q3), [`q4`](#pt-group-q4), [`$matrixAdd`](#pt-group-dollar-matrix-add), [`$matrixMultiply`](#pt-group-dollar-matrix-multiply), [`$zip`](#pt-group-dollar-zip), [`add`](#pt-group-add), [`anchorFrom`](#pt-group-anchor-from), [`anchorTo`](#pt-group-anchor-to), [`boundingBox`](#pt-group-bounding-box), [`centroid`](#pt-group-centroid), [`clone`](#pt-group-clone), [`divide`](#pt-group-divide), [`forEachPt`](#pt-group-for-each-pt), [`insert`](#pt-group-insert), [`interpolate`](#pt-group-interpolate), [`lines`](#pt-group-lines), [`moveBy`](#pt-group-move-by), [`moveTo`](#pt-group-move-to), [`multiply`](#pt-group-multiply), [`op`](#pt-group-op), [`ops`](#pt-group-ops), [`reflect2D`](#pt-group-reflect2-d), [`remove`](#pt-group-remove), [`rotate2D`](#pt-group-rotate2-d), [`scale`](#pt-group-scale), [`segments`](#pt-group-segments), [`shear2D`](#pt-group-shear2-d), [`sortByDimension`](#pt-group-sort-by-dimension), [`split`](#pt-group-split), [`subtract`](#pt-group-subtract), [`toBound`](#pt-group-to-bound), [`toString`](#pt-group-to-string), [`zipSlice`](#pt-group-zip-slice), [`fromArray`](#pt-group-static-from-array), [`fromPtArray`](#pt-group-static-from-pt-array).
- From [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array): 21 standard properties and methods (not repeated here).

<a id="create-flock"></a>
### `Flock`

**Kind:** Class · **Source:** [`src/Create.ts:948`](https://github.com/williamngan/pts/blob/master/src/Create.ts#L948)

**Extends:** `Group`

Flock is a subclass of [`Group`](#pt-group) that holds [`Boid`](#create-boid) agents and simulates
flocking behavior (also known as "boids", after Craig Reynolds). Each agent steers by three
local rules — separation, alignment, and cohesion — evaluated over the neighbors within its
`perception` radius. Create one with [`Create.flock`](#create-create-static-flock) and advance it with
[`Flock.step`](#create-flock-step). Since a Flock is a Group of Pts, it draws directly:
`form.points( flock, 2, "circle" )`.

Neighbors are found through a uniform spatial hash rather than by testing every pair, so the
cost scales with the number of agents rather than with its square.
See [a demo here](https://ptsjs.org/demo/?name=create.flock).

#### Accessors

<a id="create-flock-align-weight"></a>
##### `alignWeight`

```ts
get alignWeight(): number
set alignWeight(w: number): void
```

Weight of the alignment behavior, which matches an agent's heading to its neighbors'.

<a id="create-flock-bound"></a>
##### `bound`

```ts
get bound(): GroupLike | null
set bound(b: GroupLike | null): void
```

Boundary that keeps the flock in view, as a [`Bound`](#pt-bound) or a Group of 2 Pts.
When this is null, no boundary behavior is applied regardless of `boundary`.

<a id="create-flock-boundary"></a>
##### `boundary`

```ts
get boundary(): FlockBoundary
set boundary(b: FlockBoundary): void
```

How the boundary is treated: `"steer"`, `"wrap"`, `"bounce"`, or `"none"`.

Note that `"wrap"` teleports agents across the bound while the neighborhood search is not
toroidal, so a flock loses sight of itself at the seam. Prefer `"steer"` when that matters.

<a id="create-flock-cohesion-weight"></a>
##### `cohesionWeight`

```ts
get cohesionWeight(): number
set cohesionWeight(w: number): void
```

Weight of the cohesion behavior, which steers an agent toward its neighbors' center.

<a id="create-flock-initial-speed"></a>
##### `initialSpeed`

```ts
get initialSpeed(): number
set initialSpeed(s: number): void
```

Speed given to an agent added without an explicit velocity. Defaults to half of `maxSpeed`.

<a id="create-flock-margin"></a>
##### `margin`

```ts
get margin(): number
set margin(m: number): void
```

Distance from an edge at which `"steer"` starts turning agents back.

<a id="create-flock-max-force"></a>
##### `maxForce`

```ts
get maxForce(): number
set maxForce(f: number): void
```

Maximum steering force, in units per second squared. This caps how sharply an agent can
turn toward the direction its three behaviors blend to. A boundary turn is added on top,
so an agent near an edge can accelerate up to twice this.

<a id="create-flock-max-speed"></a>
##### `maxSpeed`

```ts
get maxSpeed(): number
set maxSpeed(s: number): void
```

Maximum speed, in units per second.

<a id="create-flock-max-time-step"></a>
##### `maxTimeStep`

```ts
get maxTimeStep(): number
set maxTimeStep(ms: number): void
```

Maximum simulated time in milliseconds per [`Flock.step`](#create-flock-step) call. Longer elapsed times
are clamped to this, which keeps a stalled frame from teleporting the flock. Default is 50.

<a id="create-flock-min-speed"></a>
##### `minSpeed`

```ts
get minSpeed(): number
set minSpeed(s: number): void
```

Minimum speed, in units per second, so agents never stall. Default is 0.

<a id="create-flock-perception"></a>
##### `perception`

```ts
get perception(): number
set perception(r: number): void
```

Radius within which an agent sees its neighbors. This is also the spatial hash's cell size.

<a id="create-flock-separate-weight"></a>
##### `separateWeight`

```ts
get separateWeight(): number
set separateWeight(w: number): void
```

Weight of the separation behavior, which steers an agent away from close neighbors.

<a id="create-flock-separation"></a>
##### `separation`

```ts
get separation(): number
set separation(r: number): void
```

Radius within which an agent steers away from its neighbors. Values above `perception`
have no additional effect, since an agent only considers neighbors it can see.

#### Methods

<a id="create-flock-add-boid"></a>
##### `addBoid`

```ts
addBoid(pt: PtLike | Boid, velocity: PtLike): this
```

Add an agent to this flock. Named `addBoid` rather than `add` because [`Group.add`](#pt-group-add)
already means "translate every Pt in this group", and [`Group.moveBy`](#pt-group-move-by) delegates to it.

**Parameters**

- `pt` (`PtLike | Boid`) — a Pt, a Boid, or an array of numbers for the starting position
- `velocity` (`PtLike`) — optional starting velocity. When omitted, a new agent gets a random heading at [`Flock.initialSpeed`](#create-flock-initial-speed), drawn from [`Num.random`](#num-num-static-random).

<a id="create-flock-setup"></a>
##### `setup`

```ts
setup(options: FlockOptions): this
```

Set any number of options at once. Unspecified options keep their current value.

**Parameters**

- `options` (`FlockOptions`) — a [`FlockOptions`](#types-flockoptions) object

<a id="create-flock-step"></a>
##### `step`

```ts
step(ms: number): this
```

Advance the simulation. Call this once per frame with the frame time, eg
`space.add( (time, ftime) => flock.step( ftime ) )`.

Elapsed times longer than [`Flock.maxTimeStep`](#create-flock-max-time-step) are clamped, so a slow frame slows
the flock down instead of teleporting it. A non-positive or NaN time is a no-op.

**Parameters**

- `ms` (`number`) — elapsed time in milliseconds

#### Inherited API

- From [`Group`](#pt-group): [`constructor`](#pt-group-constructor), [`id`](#pt-group-id), [`p1`](#pt-group-p1), [`p2`](#pt-group-p2), [`p3`](#pt-group-p3), [`p4`](#pt-group-p4), [`q1`](#pt-group-q1), [`q2`](#pt-group-q2), [`q3`](#pt-group-q3), [`q4`](#pt-group-q4), [`$matrixAdd`](#pt-group-dollar-matrix-add), [`$matrixMultiply`](#pt-group-dollar-matrix-multiply), [`$zip`](#pt-group-dollar-zip), [`add`](#pt-group-add), [`anchorFrom`](#pt-group-anchor-from), [`anchorTo`](#pt-group-anchor-to), [`boundingBox`](#pt-group-bounding-box), [`centroid`](#pt-group-centroid), [`clone`](#pt-group-clone), [`divide`](#pt-group-divide), [`forEachPt`](#pt-group-for-each-pt), [`insert`](#pt-group-insert), [`interpolate`](#pt-group-interpolate), [`lines`](#pt-group-lines), [`moveBy`](#pt-group-move-by), [`moveTo`](#pt-group-move-to), [`multiply`](#pt-group-multiply), [`op`](#pt-group-op), [`ops`](#pt-group-ops), [`reflect2D`](#pt-group-reflect2-d), [`remove`](#pt-group-remove), [`rotate2D`](#pt-group-rotate2-d), [`scale`](#pt-group-scale), [`segments`](#pt-group-segments), [`shear2D`](#pt-group-shear2-d), [`sortByDimension`](#pt-group-sort-by-dimension), [`split`](#pt-group-split), [`subtract`](#pt-group-subtract), [`toBound`](#pt-group-to-bound), [`toString`](#pt-group-to-string), [`zipSlice`](#pt-group-zip-slice), [`fromArray`](#pt-group-static-from-array), [`fromPtArray`](#pt-group-static-from-pt-array).
- From [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array): 21 standard properties and methods (not repeated here).

<a id="create-noise"></a>
### `Noise`

**Kind:** Class · **Source:** [`src/Create.ts:298`](https://github.com/williamngan/pts/blob/master/src/Create.ts#L298)

**Extends:** `Pt`

Noise is a subclass of Pt that generates Perlin noise. Current implementation supports basic 2D noise.
This implementation is based on this [gist](https://gist.github.com/banksean/304522).

#### Constructors

<a id="create-noise-constructor"></a>
##### Constructor

*overrides `Pt.__constructor`*

```ts
new Noise(args: any[]): Noise
```

Create a Noise Pt that can generate noise continuously. See a [Noise demo here](https://ptsjs.org/demo/?name=create.noisePts).

**Parameters**

- `args` (`any[]`) — a list of numeric parameters, an array of numbers, or an object with {x,y,z,w} properties

#### Methods

<a id="create-noise-init-noise"></a>
##### `initNoise`

```ts
initNoise(args: any[]): Noise
```

Set the initial dimensional values of the noise.

**Parameters**

- `args` (`any[]`) — a list of numeric parameters, an array of numbers, or an object with {x,y,z,w} properties

**Example**

```ts
noise.initNoise( 0.01, 0.1 )
```

<a id="create-noise-noise2-d"></a>
##### `noise2D`

```ts
noise2D(): number
```

Generate a 2D Perlin noise value.

<a id="create-noise-seed"></a>
##### `seed`

```ts
seed(s: number): Noise
```

Specify a seed for this Noise.

**Parameters**

- `s` (`number`) — seed value

<a id="create-noise-step"></a>
##### `step`

```ts
step(x: number = 0, y: number = 0): Noise
```

Add a small increment to the noise values.

**Parameters**

- `x` (`number`; default `0`) — step in x dimension
- `y` (`number`; default `0`) — step in y dimension

#### Properties

<a id="create-noise-perm"></a>
##### `perm`

*protected*

```ts
perm: number[]
```

#### Inherited API

- From [`Pt`](#pt-pt): [`id`](#pt-pt-id), [`w`](#pt-pt-w), [`x`](#pt-pt-x), [`y`](#pt-pt-y), [`z`](#pt-pt-z), [`$abs`](#pt-pt-dollar-abs), [`$add`](#pt-pt-dollar-add), [`$ceil`](#pt-pt-dollar-ceil), [`$concat`](#pt-pt-dollar-concat), [`$cross`](#pt-pt-dollar-cross), [`$cross2D`](#pt-pt-dollar-cross2-d), [`$divide`](#pt-pt-dollar-divide), [`$floor`](#pt-pt-dollar-floor), [`$max`](#pt-pt-dollar-max), [`$min`](#pt-pt-dollar-min), [`$multiply`](#pt-pt-dollar-multiply), [`$project`](#pt-pt-dollar-project), [`$round`](#pt-pt-dollar-round), [`$subtract`](#pt-pt-dollar-subtract), [`$take`](#pt-pt-dollar-take), [`$to`](#pt-pt-dollar-to), [`$unit`](#pt-pt-dollar-unit), [`abs`](#pt-pt-abs), [`add`](#pt-pt-add), [`angle`](#pt-pt-angle), [`angleBetween`](#pt-pt-angle-between), [`ceil`](#pt-pt-ceil), [`clone`](#pt-pt-clone), [`divide`](#pt-pt-divide), [`dot`](#pt-pt-dot), [`equals`](#pt-pt-equals), [`floor`](#pt-pt-floor), [`magnitude`](#pt-pt-magnitude), [`magnitudeSq`](#pt-pt-magnitude-sq), [`maxValue`](#pt-pt-max-value), [`minValue`](#pt-pt-min-value), [`multiply`](#pt-pt-multiply), [`op`](#pt-pt-op), [`ops`](#pt-pt-ops), [`projectScalar`](#pt-pt-project-scalar), [`reflect2D`](#pt-pt-reflect2-d), [`rotate2D`](#pt-pt-rotate2-d), [`round`](#pt-pt-round), [`scale`](#pt-pt-scale), [`shear2D`](#pt-pt-shear2-d), [`subtract`](#pt-pt-subtract), [`to`](#pt-pt-to), [`toAngle`](#pt-pt-to-angle), [`toArray`](#pt-pt-to-array), [`toBound`](#pt-pt-to-bound), [`toGroup`](#pt-pt-to-group), [`toString`](#pt-pt-to-string), [`unit`](#pt-pt-unit), [`make`](#pt-pt-static-make).
- From [`Float32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array): 26 standard properties and methods (not repeated here).

<a id="create-poissondisk"></a>
### `PoissonDisk`

**Kind:** Class · **Source:** [`src/Create.ts:1603`](https://github.com/williamngan/pts/blob/master/src/Create.ts#L1603)

**Extends:** `Group`

PoissonDisk is a Group of Pts produced by Poisson-disk sampling: every point is at least
[`PoissonDisk.radius`](#create-poissondisk-radius) away from every other. Create a finished set with
[`Create.sampling`](#create-create-static-sampling), or construct one directly and grow it with [`PoissonDisk.step`](#create-poissondisk-step)
(one point at a time) or [`PoissonDisk.sample`](#create-poissondisk-sample) (a batch at a time), which is how the
[demo](https://ptsjs.org/demo/?name=create.sampling) shows the packing as it forms.

The sampler is Bridson's grid-accelerated algorithm with Roberts' candidate placement: each
visit to an active point tries up to [`PoissonDisk.candidates`](#create-poissondisk-candidates) candidates on the circle
just outside `radius` around it, at evenly spaced angles from a random offset, and accepts the
first one with no existing point within `radius`. It runs in linear time on one small integer
grid. In a bound thinner than the radius, candidates take random positions across the thin
axis and alternate along the long one, since a circle of candidates would miss the strip.

Three traits to know: most points sit just beyond `radius` from the point that spawned them,
which packs tighter than candidates at random distances; the candidate budget is finite, so
a finished set can still have gaps; and coordinates are compared as float32 (the precision of
a Pt), exact at pixel scales but rejecting some candidates when coordinates exceed roughly
8000 times the radius.

Treat the Group as read-only while sampling: pushing or moving its Pts by hand would
desynchronize the grid that enforces the spacing. A PoissonDisk produced by `map`, `filter`
or `slice` is a plain copy that reports radius 0 and `done`, and needs `setup` before sampling.

#### Accessors

<a id="create-poissondisk-bound"></a>
##### `bound`

```ts
get bound(): Bound
```

The rectangular boundary that the samples fill.

<a id="create-poissondisk-candidates"></a>
##### `candidates`

```ts
get candidates(): number
```

Maximum candidates tried per visit to an active sample before retiring it if none succeed.

<a id="create-poissondisk-done"></a>
##### `done`

```ts
get done(): boolean
```

Whether no active samples remain. Gaps may still fit further points, but sampling has stopped.

<a id="create-poissondisk-radius"></a>
##### `radius`

```ts
get radius(): number
```

Minimum distance between any two points in this set.

#### Methods

<a id="create-poissondisk-sample"></a>
##### `sample`

```ts
sample(count: number = Infinity): this
```

Add up to `count` more samples, or every remaining sample by default.

**Parameters**

- `count` (`number`; default `Infinity`) — maximum number of samples to add, rounded down; nonpositive values and NaN add none

**Example**

```ts
pd.sample( 20 )` adds twenty points per frame; `pd.sample()` completes the set
```

<a id="create-poissondisk-setup"></a>
##### `setup`

```ts
setup(bound: Bound, radius: number, options: PoissonDiskOptions = {}): this
```

Reset this sampler and place its first sample. Calling `setup` again empties the group and
starts over, which is how a sketch restarts sampling after a resize.

**Parameters**

- `bound` (`Bound`) — the rectangular boundary
- `radius` (`number`) — minimum distance between any two points
- `options` (`PoissonDiskOptions`; default `{}`) — optional [`PoissonDiskOptions`](#types-poissondiskoptions)

**Returns:** this

**Example**

```ts
new PoissonDisk().setup( space.innerBound, 12 ).sample( 40 )
```

<a id="create-poissondisk-step"></a>
##### `step`

```ts
step(): Pt | undefined
```

Add the next sample and return it, or return `undefined` once no active samples remain.
The new Pt is also the last element of this group.

**Example**

```ts
let p = pd.step(); if (p) form.point( p, 2 );
```

#### Inherited API

- From [`Group`](#pt-group): [`constructor`](#pt-group-constructor), [`id`](#pt-group-id), [`p1`](#pt-group-p1), [`p2`](#pt-group-p2), [`p3`](#pt-group-p3), [`p4`](#pt-group-p4), [`q1`](#pt-group-q1), [`q2`](#pt-group-q2), [`q3`](#pt-group-q3), [`q4`](#pt-group-q4), [`$matrixAdd`](#pt-group-dollar-matrix-add), [`$matrixMultiply`](#pt-group-dollar-matrix-multiply), [`$zip`](#pt-group-dollar-zip), [`add`](#pt-group-add), [`anchorFrom`](#pt-group-anchor-from), [`anchorTo`](#pt-group-anchor-to), [`boundingBox`](#pt-group-bounding-box), [`centroid`](#pt-group-centroid), [`clone`](#pt-group-clone), [`divide`](#pt-group-divide), [`forEachPt`](#pt-group-for-each-pt), [`insert`](#pt-group-insert), [`interpolate`](#pt-group-interpolate), [`lines`](#pt-group-lines), [`moveBy`](#pt-group-move-by), [`moveTo`](#pt-group-move-to), [`multiply`](#pt-group-multiply), [`op`](#pt-group-op), [`ops`](#pt-group-ops), [`reflect2D`](#pt-group-reflect2-d), [`remove`](#pt-group-remove), [`rotate2D`](#pt-group-rotate2-d), [`scale`](#pt-group-scale), [`segments`](#pt-group-segments), [`shear2D`](#pt-group-shear2-d), [`sortByDimension`](#pt-group-sort-by-dimension), [`split`](#pt-group-split), [`subtract`](#pt-group-subtract), [`toBound`](#pt-group-to-bound), [`toString`](#pt-group-to-string), [`zipSlice`](#pt-group-zip-slice), [`fromArray`](#pt-group-static-from-array), [`fromPtArray`](#pt-group-static-from-pt-array).
- From [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array): 21 standard properties and methods (not repeated here).

<a id="module-dom"></a>
## Module: `Dom`

<a id="dom-domspace"></a>
### `DOMSpace`

**Kind:** Class · **Source:** [`src/Dom.ts:33`](https://github.com/williamngan/pts/blob/master/src/Dom.ts#L33)

**Extends:** `MultiTouchSpace`

DOMSpace hosts a Space in a DOM element. It is the subclassing entry point for building
custom element-based spaces; usually its subclass [`SVGSpace`](#svg-svgspace) should be used instead.
Learn more about spaces in [this guide](https://ptsjs.org/guide/Space-0500.html).

When using a Space inside a component framework, create it on mount and call
[`DOMSpace.dispose`](#dom-domspace-dispose) on unmount so listeners and the animation loop are released.
For example, in React:
```
useEffect(() => {
  const space = new SVGSpace(ref.current).setup({ resize: true });
  space.add(...).play();
  return () => { space.dispose(); };
}, []);
```
Dispose is idempotent, and a new Space can be mounted on the same element afterwards
(as happens under React's StrictMode).

#### Constructors

<a id="dom-domspace-constructor"></a>
##### Constructor

```ts
new DOMSpace(elem: string | Element | null = "pt", callback:  Fn(bound:Bound, elem:Element)): DOMSpace
```

Create a DOMSpace for HTML DOM elements

**Parameters**

- `elem` (`string | Element | null`; default `"pt"`) — Specify an element by its "id" attribute as string, or by the element object itself. If left empty, a `<div id="pt_container"><div id="pt" /></div>` will be added to DOM; a missing id is created the same way. Use css to customize its appearance if needed.
- `callback` (` Fn(bound:Bound, elem:Element)`) — an optional callback `function(boundingBox, spaceElement)` to be called when element is appended and ready. Alternatively, a "ready" event will also be fired from the element when it's appended, which can be traced with `spaceInstance.element.addEventListener("ready")`

**Example**

```ts
new DOMSpace( "#myElementID" )
```

#### Accessors

<a id="dom-domspace-auto-resize"></a>
##### `autoResize`

```ts
get autoResize(): boolean
set autoResize(auto: boolean): void
```

Set whether the canvas element should resize when its container is resized.

<a id="dom-domspace-background"></a>
##### `background`

```ts
get background(): string
set background(bg: string): void
```

Set a background color on the container element.

<a id="dom-domspace-element"></a>
##### `element`

```ts
get element(): Element
```

Get this DOM element.

<a id="dom-domspace-parent"></a>
##### `parent`

```ts
get parent(): Element
```

Get the parent DOM element that contains this DOM element.

<a id="dom-domspace-ready"></a>
##### `ready`

```ts
get ready(): boolean
```

A property to indicate if the Space is ready.

#### Methods

<a id="dom-domspace-clear"></a>
##### `clear`

*overrides `MultiTouchSpace.clear`*

```ts
clear(bg: string): this
```

Clear the element's contents, and optionally set a new background color. This overrides Space's `clear` function.

**Parameters**

- `bg` (`string`) — Optionally specify a custom background color in hex or rgba string, or "transparent". If not defined, it will use its `bgcolor` property as background color to clear the canvas.

<a id="dom-domspace-dispose"></a>
##### `dispose`

```ts
dispose(): this
```

Dispose of browser resources held by this space and remove all players. Call this before
unmounting the DOM, eg in a framework component's unmount/cleanup callback. Dispose is
idempotent, and a new Space can be created on the same element afterwards.

<a id="dom-domspace-get-form"></a>
##### `getForm`

*overrides `MultiTouchSpace.getForm`*

```ts
getForm(): Form
```

Not implemented. See SVGSpace and HTMLSpace for implementation.

<a id="dom-domspace-resize"></a>
##### `resize`

*overrides `MultiTouchSpace.resize`*

```ts
resize(b: Bound, evt: Event | null): this
```

This overrides Space's `resize` function. It's used as a callback function for window's resize event and not usually called directly. You can keep track of resize events with `resize: (bound, evt)` callback in your player objects (See [`Space.add`](#space-space-add) function).

**Parameters**

- `b` (`Bound`) — a Bound object to resize to
- `evt` (`Event | null`) — Optionally pass a resize event

<a id="dom-domspace-setup"></a>
##### `setup`

```ts
setup(opt: { bgcolor:string, resize:boolean }): this
```

Set up various options for DOMSpace. This is usually set during instantiation, eg `new DOMSpace(...).setup( {opt} )`.

**Parameters**

- `opt` (`{ bgcolor:string, resize:boolean }`) — an object with these optional properties: **bgcolor** is a hex or rgba string to set initial background color of the canvas, or use `false` or "transparent" to set a transparent background; **resize** a boolean to set whether `<canvas>` size should auto resize to match its container's size, which can also be set using `autoSize()`.

**Example**

```ts
space.setup({ bgcolor: "#f00", resize: true })
```

<a id="dom-domspace-style"></a>
##### `style`

```ts
style(key: string, val: string, update: boolean = false): this
```

Add or update a style definition, and optionally update that style in the Element.

**Parameters**

- `key` (`string`) — style name
- `val` (`string`) — style value
- `update` (`boolean`; default `false`) — a boolean to update the element's style immediately if set to `true`. Default is `false`.

<a id="dom-domspace-styles"></a>
##### `styles`

```ts
styles(styles: Record, update: boolean = false): this
```

Add of update a list of style definitions, and optionally update those styles in the Element.

**Parameters**

- `styles` (`Record`) — a key-value objects of style definitions
- `update` (`boolean`; default `false`) — a boolean to update the element's style immediately if set to `true`. Default is `false`.

**Returns:** this

<a id="dom-domspace-static-create-element"></a>
##### `createElement`

*static*

```ts
static createElement(elem: string = "div", id: string, appendTo: Element): Element
```

Helper function to create a DOM element.

**Parameters**

- `elem` (`string`; default `"div"`) — element tag name
- `id` (`string`) — element id attribute
- `appendTo` (`Element`) — Optional, if specified, the created element will be appended to this element

<a id="dom-domspace-static-get-inline-styles"></a>
##### `getInlineStyles`

*static*

```ts
static getInlineStyles(data: Record): string
```

A static helper function to compose an inline style string from a object of styles.

**Parameters**

- `data` (`Record`) — an object with key-value pairs

**Example**

```ts
DOMSpace.getInlineStyles( {width: "100px", "font-size": "10px"} )
```

<a id="dom-domspace-static-set-attr"></a>
##### `setAttr`

*static*

```ts
static setAttr(elem: Element, data: Record): Element
```

A static helper function to add or update Element attributes.

**Parameters**

- `elem` (`Element`) — Element to update
- `data` (`Record`) — an object with key-value pairs

**Returns:** this DOM element

#### Properties

<a id="dom-domspace-id"></a>
##### `id`

*overrides `MultiTouchSpace.id`*

```ts
id: string
```

#### Inherited API

- From [`Space`](#space-space): [`center`](#space-space-center), [`customRendering`](#space-space-custom-rendering), [`height`](#space-space-height), [`innerBound`](#space-space-inner-bound), [`isPlaying`](#space-space-is-playing), [`outerBound`](#space-space-outer-bound), [`size`](#space-space-size), [`width`](#space-space-width), [`add`](#space-space-add), [`minFrameTime`](#space-space-min-frame-time), [`pause`](#space-space-pause), [`play`](#space-space-play), [`playItems`](#space-space-play-items), [`playOnce`](#space-space-play-once), [`refresh`](#space-space-refresh), [`remove`](#space-space-remove), [`render`](#space-space-render), [`replay`](#space-space-replay), [`resume`](#space-space-resume), [`stop`](#space-space-stop), [`bound`](#space-space-bound), [`playerCount`](#space-space-player-count), [`players`](#space-space-players).
- From [`MultiTouchSpace`](#space-multitouchspace): [`pointer`](#space-multitouchspace-pointer), [`bindCanvas`](#space-multitouchspace-bind-canvas), [`bindDoc`](#space-multitouchspace-bind-doc), [`bindKeyboard`](#space-multitouchspace-bind-keyboard), [`bindMouse`](#space-multitouchspace-bind-mouse), [`bindTouch`](#space-multitouchspace-bind-touch), [`removeAll`](#space-multitouchspace-remove-all), [`touchesToPoints`](#space-multitouchspace-touches-to-points), [`track`](#space-multitouchspace-track), [`unbindCanvas`](#space-multitouchspace-unbind-canvas), [`unbindDoc`](#space-multitouchspace-unbind-doc), [`untrack`](#space-multitouchspace-untrack).

<a id="dom-htmlform"></a>
### `HTMLForm`

**Kind:** Class · **Source:** [`src/Dom.ts:423`](https://github.com/williamngan/pts/blob/master/src/Dom.ts#L423)

**Extends:** `VisualForm`

#### Constructors

<a id="dom-htmlform-constructor"></a>
##### Constructor

```ts
new HTMLForm(space: HTMLSpace): HTMLForm
```

Create a new `HTMLForm`. Alternatively, you can use [`HTMLSpace.getForm`](#dom-htmlspace-get-form) function to get an instance of HTMLForm.

**Parameters**

- `space` (`HTMLSpace`) — the space to use

#### Accessors

<a id="dom-htmlform-space"></a>
##### `space`

```ts
get space(): HTMLSpace
```

Get the corresponding space for this form

<a id="dom-htmlform-static-dom-id"></a>
##### `domID`

*static*

```ts
get domID(): number
set domID(n: number): void
```

<a id="dom-htmlform-static-group-id"></a>
##### `groupID`

*static*

```ts
get groupID(): number
set groupID(n: number): void
```

#### Methods

<a id="dom-htmlform-alpha"></a>
##### `alpha`

*overrides `VisualForm.alpha`*

```ts
alpha(a: number): this
```

Set current alpha value.

**Parameters**

- `a` (`number`) — alpha value between 0 and 1

**Example**

```ts
form.alpha(0.6)
```

<a id="dom-htmlform-arc"></a>
##### `arc`

*overrides `VisualForm.arc`*

```ts
arc(pt: PtLike, radius: number, startAngle: number, endAngle: number, cc: boolean): this
```

Arc is not implemented in HTMLForm.

**Parameters**

- `pt` (`PtLike`)
- `radius` (`number`)
- `startAngle` (`number`)
- `endAngle` (`number`)
- `cc` (`boolean`)

<a id="dom-htmlform-circle"></a>
##### `circle`

*overrides `VisualForm.circle`*

```ts
circle(pts: GroupLike | number[][]): this
```

Draw a circle.

**Parameters**

- `pts` (`GroupLike | number[][]`) — usually a Group of 2 Pts, but it can also take an array of two numeric arrays [ [position], [size] ]

**See also:** [`Circle.fromCenter`](#op-circle-static-from-center)

<a id="dom-htmlform-cls"></a>
##### `cls`

```ts
cls(c: string | boolean): HTMLForm
```

Add custom class to the created element.

**Parameters**

- `c` (`string | boolean`) — custom class name or `false` to reset it

**Example**

```ts
form.fill("#f00").cls("myClass").rects(r)` `form.cls(false).circles(c)
```

<a id="dom-htmlform-fill"></a>
##### `fill`

*overrides `VisualForm.fill`*

```ts
fill(c: string | boolean): this
```

Set current fill style. Provide a valid color string or `false` to specify no fill color.

**Parameters**

- `c` (`string | boolean`) — fill color

**Example**

```ts
form.fill("#F90")`, `form.fill("rgba(0,0,0,.5")`, `form.fill(false)
```

<a id="dom-htmlform-fill-text"></a>
##### `fillText`

```ts
fillText(c: string): this
```

Set current text color style. Provide a valid color string.

**Parameters**

- `c` (`string`) — fill color

**Example**

```ts
form.fill("#F90")`, `form.fill("rgba(0,0,0,.5")`, `form.fill(false)
```

<a id="dom-htmlform-font"></a>
##### `font`

*overrides `VisualForm.font`*

```ts
font(sizeOrFont: number | Font, weight: string, style: string, lineHeight: number, family: string): this
```

Set the current font.

**Parameters**

- `sizeOrFont` (`number | Font`) — either a number to specify font-size, or a `Font` object to specify all font properties
- `weight` (`string`) — Optional font-weight string such as "bold"
- `style` (`string`) — Optional font-style string such as "italic"
- `lineHeight` (`number`) — Optional line-height number suchas 1.5
- `family` (`string`) — Optional font-family such as "Helvetica, sans-serif"

**Example**

```ts
form.font( myFont )`, `form.font(14, "bold")
```

<a id="dom-htmlform-line"></a>
##### `line`

*overrides `VisualForm.line`*

```ts
line(pts: GroupLike | number[][]): this
```

Line is not implemented in HTMLForm.

**Parameters**

- `pts` (`GroupLike | number[][]`)

<a id="dom-htmlform-log"></a>
##### `log`

```ts
log(txt: any): this
```

A convenient way to draw some text on canvas for logging or debugging. It'll be draw on the top-left of the canvas as an overlay.

**Parameters**

- `txt` (`any`) — text

<a id="dom-htmlform-next-id"></a>
##### `nextID`

```ts
nextID(): string
```

Get next available id in the current group.

**Returns:** an id string

<a id="dom-htmlform-point"></a>
##### `point`

*overrides `VisualForm.point`*

```ts
point(pt: PtLike, radius: number = 5, shape: string = "square"): this
```

Draws a point.

**Parameters**

- `pt` (`PtLike`) — a Pt object
- `radius` (`number`; default `5`) — radius of the point. Default is 5.
- `shape` (`string`; default `"square"`) — The shape of the point. Defaults to "square", but it can be "circle" or a custom shape function in your own implementation.

**Example**

```ts
form.point( p )`, `form.point( p, 10, "circle" )
```

<a id="dom-htmlform-polygon"></a>
##### `polygon`

*overrides `VisualForm.polygon`*

```ts
polygon(pts: GroupLike | number[][]): this
```

Polygon is not implemented in HTMLForm.

**Parameters**

- `pts` (`GroupLike | number[][]`)

<a id="dom-htmlform-rect"></a>
##### `rect`

*overrides `VisualForm.rect`*

```ts
rect(pts: PtLikeIterable): this
```

Draw a rectangle.

**Parameters**

- `pts` (`PtLikeIterable`) — a Group or an Iterable<PtLike> with 2 Pt specifying the top-left and bottom-right positions.

<a id="dom-htmlform-reset"></a>
##### `reset`

*overrides `VisualForm.reset`*

```ts
reset(): this
```

Reset the context's common styles to this form's styles. This supports using multiple forms on the same canvas context.

<a id="dom-htmlform-scope"></a>
##### `scope`

```ts
scope(item: IPlayer): DOMFormContext
```

Set the current group scope to an item added into space, in order to keep track of any point, circle, etc created within it. The item must have an `animateID` property, so that elements created within the item will have generated IDs like "item-{animateID}-{count}".

**Parameters**

- `item` (`IPlayer`) — a "player" item that's added to space (see `space.add(...)`) and has an `animateID` property

**Returns:** this form's context

<a id="dom-htmlform-square"></a>
##### `square`

```ts
square(pt: PtLike, halfsize: number): this
```

Draw a square, given a center and its half-size.

**Parameters**

- `pt` (`PtLike`) — center Pt
- `halfsize` (`number`) — half-size

<a id="dom-htmlform-stroke"></a>
##### `stroke`

*overrides `VisualForm.stroke`*

```ts
stroke(c: string | boolean, width: number, linejoin: string, linecap: string): this
```

Set current stroke style. Provide a valid color string or `false` to specify no stroke color.

**Parameters**

- `c` (`string | boolean`) — stroke color which can be as color, gradient, or pattern. (See [canvas documentation](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/strokeStyle))
- `width` (`number`) — Optional value (can be floating point) to set line width
- `linejoin` (`string`) — not implemented in HTMLForm
- `linecap` (`string`) — not implemented in HTMLForm

**Example**

```ts
form.stroke("#F90")`, `form.stroke("rgba(0,0,0,.5")`, `form.stroke(false)`, `form.stroke("#000", 0.5, 'round', 'square')
```

<a id="dom-htmlform-style-to"></a>
##### `styleTo`

*protected*

```ts
styleTo(k: string, v: any, unit: string = ""): void
```

Usually not used directly. This updates a style in `_ctx` context or throw an Error if the style doesn't exist.

**Parameters**

- `k` (`string`) — style key
- `v` (`any`) — style value
- `unit` (`string`; default `""`) — Optional unit like 'px' to append to value

<a id="dom-htmlform-text"></a>
##### `text`

*overrides `VisualForm.text`*

```ts
text(pt: PtLike, txt: string): this
```

Draw text in a DOM element.

**Parameters**

- `pt` (`PtLike`) — a Pt or numeric array to specify the anchor point
- `txt` (`string`) — text

<a id="dom-htmlform-update-scope"></a>
##### `updateScope`

```ts
updateScope(group_id: string, group: Element): DOMFormContext
```

Set this form's group scope by an ID, and optionally define the group's parent element. A group scope keeps track of elements by their generated IDs, and updates their properties as needed. See also `scope()`.

**Parameters**

- `group_id` (`string`) — a string to use as prefix for the group's id. For example, group_id "hello" will create elements with id like "hello-1", "hello-2", etc
- `group` (`Element`) — Optional DOM element to define this group's parent element

**Returns:** this form's context

<a id="dom-htmlform-static-circle"></a>
##### `circle`

*static*

```ts
static circle(ctx: DOMFormContext, pt: PtLike, radius: number = 10): Element
```

A static function to draw a circle.

**Parameters**

- `ctx` (`DOMFormContext`) — a context object of HTMLForm
- `pt` (`PtLike`) — center position of the circle
- `radius` (`number`; default `10`) — radius of the circle

<a id="dom-htmlform-static-get-id"></a>
##### `getID`

*static*

```ts
static getID(ctx: DOMFormContext): string
```

A static function to generate an ID string based on a context object.

**Parameters**

- `ctx` (`DOMFormContext`) — a context object for an HTMLForm

<a id="dom-htmlform-static-point"></a>
##### `point`

*static*

```ts
static point(ctx: DOMFormContext, pt: PtLike, radius: number = 5, shape: string = "square"): Element
```

A static function to draws a point.

**Parameters**

- `ctx` (`DOMFormContext`) — a context object of HTMLForm
- `pt` (`PtLike`) — a Pt object or numeric array
- `radius` (`number`; default `5`) — radius of the point. Default is 5.
- `shape` (`string`; default `"square"`) — The shape of the point. Defaults to "square", but it can be "circle" or a custom shape function in your own implementation.

**Example**

```ts
HTMLForm.point( p )`, `HTMLForm.point( p, 10, "circle" )
```

<a id="dom-htmlform-static-rect"></a>
##### `rect`

*static*

```ts
static rect(ctx: DOMFormContext, pts: PtLikeIterable): Element | undefined
```

A static function to draw a rectangle.

**Parameters**

- `ctx` (`DOMFormContext`) — a context object of HTMLForm
- `pts` (`PtLikeIterable`) — a Group or an Iterable<PtLike> with 2 Pt specifying the top-left and bottom-right positions.

<a id="dom-htmlform-static-rect-style"></a>
##### `rectStyle`

*static*

```ts
static rectStyle(ctx: DOMFormContext, pt: PtLike, size: PtLike): DOMFormContext
```

A helper function to set top, left, width, height of DOM element.

**Parameters**

- `ctx` (`DOMFormContext`) — the HTMLForm context whose style is updated
- `pt` (`PtLike`) — left and top position
- `size` (`PtLike`) — width and height

<a id="dom-htmlform-static-scope-id"></a>
##### `scopeID`

*static*

```ts
static scopeID(item: IPlayer): string
```

A static function to generate an ID string for a scope, based on a "player" item in the Space.

**Parameters**

- `item` (`IPlayer`) — a "player" item that's added to space (see `space.add(...)`) and has an `animateID` property

<a id="dom-htmlform-static-square"></a>
##### `square`

*static*

```ts
static square(ctx: DOMFormContext, pt: PtLike, halfsize: number): HTMLElement
```

A static function to draw a square.

**Parameters**

- `ctx` (`DOMFormContext`) — a context object of HTMLForm
- `pt` (`PtLike`) — center position of the square
- `halfsize` (`number`) — half size of the square

<a id="dom-htmlform-static-style"></a>
##### `style`

*static*

```ts
static style(elem: Element, styles: Record): Element
```

A static function to help adding style object to an element. This put all styles into `style` attribute instead of individual attributes, so that the styles can be parsed by Adobe Illustrator.

**Parameters**

- `elem` (`Element`) — A DOM element to add to
- `styles` (`Record`) — an object of style properties

**Returns:** DOM element

**Example**

```ts
HTMLForm.style(elem, {fill: "#f90", stroke: false})
```

<a id="dom-htmlform-static-text"></a>
##### `text`

*static*

```ts
static text(ctx: DOMFormContext, pt: PtLike, txt: string): Element
```

A static function to draw text.

**Parameters**

- `ctx` (`DOMFormContext`) — a context object of HTMLForm
- `pt` (`PtLike`) — a Point object to specify the anchor point
- `txt` (`string`) — a string of text to draw

<a id="dom-htmlform-static-text-style"></a>
##### `textStyle`

*static*

```ts
static textStyle(ctx: DOMFormContext, pt: PtLike): DOMFormContext
```

A helper function to set the top and left position styling of text DOM context.

**Parameters**

- `ctx` (`DOMFormContext`) — context to add style to
- `pt` (`PtLike`) — a Pt object or numeric array determining the top-left position of the text

#### Inherited API

- From [`VisualForm`](#form-visualform): [`currentFont`](#form-visualform-current-font), [`filled`](#form-visualform-filled), [`stroked`](#form-visualform-stroked), [`circles`](#form-visualform-circles), [`fillOnly`](#form-visualform-fill-only), [`lines`](#form-visualform-lines), [`points`](#form-visualform-points), [`polygons`](#form-visualform-polygons), [`rects`](#form-visualform-rects), [`squares`](#form-visualform-squares), [`strokeOnly`](#form-visualform-stroke-only).
- From [`Form`](#form-form): [`ready`](#form-form-ready).

<a id="dom-htmlspace"></a>
### `HTMLSpace`

**Kind:** Class · **Source:** [`src/Dom.ts:352`](https://github.com/williamngan/pts/blob/master/src/Dom.ts#L352)

**Extends:** `DOMSpace`

#### Methods

<a id="dom-htmlspace-get-form"></a>
##### `getForm`

*overrides `DOMSpace.getForm`*

```ts
getForm(): Form
```

Get a new `HTMLForm` which provides visualization functions in html elements.

**See also:** `HTMLForm`

<a id="dom-htmlspace-remove"></a>
##### `remove`

*overrides `DOMSpace.remove`*

```ts
remove(player: IPlayer): this
```

Remove an item from this space.

**Parameters**

- `player` (`IPlayer`) — a player item with an auto-assigned `animateID` property

<a id="dom-htmlspace-remove-all"></a>
##### `removeAll`

*overrides `DOMSpace.removeAll`*

```ts
removeAll(): this
```

Remove all items from this space. This clears the contents of the space's
element but never touches its container.

<a id="dom-htmlspace-static-html-element"></a>
##### `htmlElement`

*static*

```ts
static htmlElement(parent: Element | null | undefined, name: string, id: string, autoClass: boolean = true): HTMLElement
```

A static function to add a DOM element inside a node. Usually you don't need to use this directly. See methods in [`HTMLForm`](#dom-htmlform) instead.

**Parameters**

- `parent` (`Element | null | undefined`) — the parent element, or `null` to use current `<svg>` as parent.
- `name` (`string`) — a string of element name,  such as `rect` or `circle`
- `id` (`string`) — id attribute of the new element
- `autoClass` (`boolean`; default `true`) — add a class based on the id (from char 0 to index of "-"). Default is true.

#### Inherited API

- From [`DOMSpace`](#dom-domspace): [`constructor`](#dom-domspace-constructor), [`autoResize`](#dom-domspace-auto-resize), [`background`](#dom-domspace-background), [`element`](#dom-domspace-element), [`parent`](#dom-domspace-parent), [`ready`](#dom-domspace-ready), [`clear`](#dom-domspace-clear), [`dispose`](#dom-domspace-dispose), [`resize`](#dom-domspace-resize), [`setup`](#dom-domspace-setup), [`style`](#dom-domspace-style), [`styles`](#dom-domspace-styles), [`createElement`](#dom-domspace-static-create-element), [`getInlineStyles`](#dom-domspace-static-get-inline-styles), [`setAttr`](#dom-domspace-static-set-attr), [`id`](#dom-domspace-id).
- From [`Space`](#space-space): [`center`](#space-space-center), [`customRendering`](#space-space-custom-rendering), [`height`](#space-space-height), [`innerBound`](#space-space-inner-bound), [`isPlaying`](#space-space-is-playing), [`outerBound`](#space-space-outer-bound), [`size`](#space-space-size), [`width`](#space-space-width), [`add`](#space-space-add), [`minFrameTime`](#space-space-min-frame-time), [`pause`](#space-space-pause), [`play`](#space-space-play), [`playItems`](#space-space-play-items), [`playOnce`](#space-space-play-once), [`refresh`](#space-space-refresh), [`render`](#space-space-render), [`replay`](#space-space-replay), [`resume`](#space-space-resume), [`stop`](#space-space-stop), [`bound`](#space-space-bound), [`playerCount`](#space-space-player-count), [`players`](#space-space-players).
- From [`MultiTouchSpace`](#space-multitouchspace): [`pointer`](#space-multitouchspace-pointer), [`bindCanvas`](#space-multitouchspace-bind-canvas), [`bindDoc`](#space-multitouchspace-bind-doc), [`bindKeyboard`](#space-multitouchspace-bind-keyboard), [`bindMouse`](#space-multitouchspace-bind-mouse), [`bindTouch`](#space-multitouchspace-bind-touch), [`touchesToPoints`](#space-multitouchspace-touches-to-points), [`track`](#space-multitouchspace-track), [`unbindCanvas`](#space-multitouchspace-unbind-canvas), [`unbindDoc`](#space-multitouchspace-unbind-doc), [`untrack`](#space-multitouchspace-untrack).

<a id="module-form"></a>
## Module: `Form`

<a id="form-font"></a>
### `Font`

**Kind:** Class · **Source:** [`src/Form.ts:267`](https://github.com/williamngan/pts/blob/master/src/Form.ts#L267)

Font class lets you create a specific font style with properties for its size and style. A font instance can be passed as parameter to set a form's font. For example, see [`CanvasForm.font`](#canvas-canvasform-font).

#### Constructors

<a id="form-font-constructor"></a>
##### Constructor

```ts
new Font(size: number = 12, face: string = "sans-serif", weight: string = "", style: string = "", lineHeight: number = 1.5): Font
```

Create a font style.

**Parameters**

- `size` (`number`; default `12`) — font size. Defaults is 12px.
- `face` (`string`; default `"sans-serif"`) — Optional font-family, use css-like string such as "Helvetica" or "Helvetica, sans-serif". Default is "sans-serif".
- `weight` (`string`; default `""`) — Optional font weight such as "bold". Default is "" (none).
- `style` (`string`; default `""`) — Optional font style such as "italic". Default is "" (none).
- `lineHeight` (`number`; default `1.5`) — Optional line height. Default is 1.5.

**Example**

```ts
new Font(12, "Frutiger, sans-serif", "bold", "underline", 1.5)
```

#### Accessors

<a id="form-font-value"></a>
##### `value`

```ts
get value(): string
```

Get a string representing the font style, in css-like string such as "italic bold 12px/1.5 sans-serif".

#### Methods

<a id="form-font-to-string"></a>
##### `toString`

```ts
toString(): string
```

Get a string representing the font style, in css-like string such as "italic bold 12px/1.5 sans-serif".

#### Properties

<a id="form-font-face"></a>
##### `face`

*public*

```ts
face: string
```

<a id="form-font-line-height"></a>
##### `lineHeight`

*public*

```ts
lineHeight: number
```

<a id="form-font-size"></a>
##### `size`

*public*

```ts
size: number
```

<a id="form-font-style"></a>
##### `style`

*public*

```ts
style: string
```

<a id="form-font-weight"></a>
##### `weight`

*public*

```ts
weight: string
```

<a id="form-form"></a>
### `Form`

**Kind:** Class · **Source:** [`src/Form.ts:10`](https://github.com/williamngan/pts/blob/master/src/Form.ts#L10)

Form is an abstract class that represents a form that's used in a Space for expressions. Learn more about Space and Form in [this guide](https://ptsjs.org/guide/Space-0500.html).

#### Accessors

<a id="form-form-ready"></a>
##### `ready`

```ts
get ready(): boolean
```

get whether the Form has received the Space's rendering context.

<a id="form-visualform"></a>
### `VisualForm`

**Kind:** Class · **Source:** [`src/Form.ts:25`](https://github.com/williamngan/pts/blob/master/src/Form.ts#L25)

**Extends:** `Form`

VisualForm is an abstract class that represents a form that can be used to express Pts visually.
For example, [`CanvasForm`](#canvas-canvasform) is an implementation of VisualForm that draws on [`CanvasSpace`](#canvas-canvasspace) which represents a html canvas. Learn more about Space and Form in [this guide](https://ptsjs.org/guide/Space-0500.html).

#### Accessors

<a id="form-visualform-current-font"></a>
##### `currentFont`

```ts
get currentFont(): Font
```

Get the current font in use in this form.

<a id="form-visualform-filled"></a>
##### `filled`

```ts
get filled(): boolean
set filled(b: boolean): void
```

Check whether this form currently has fill style.

<a id="form-visualform-stroked"></a>
##### `stroked`

```ts
get stroked(): boolean
set stroked(b: boolean): void
```

Check whether this form currently has stroke style.

#### Methods

<a id="form-visualform-alpha"></a>
##### `alpha`

```ts
alpha(a: number): this
```

Set alpha (not implemented here  -- to be implemented in subclasses).

**Parameters**

- `a` (`number`) — alpha value between 0 and 1

<a id="form-visualform-arc"></a>
##### `arc`

*abstract*

```ts
arc(pt: PtLike, radius: number, startAngle: number, endAngle: number, cc: boolean): this
```

Draw an arc (not implemented here  -- to be implemented in subclasses).

**Parameters**

- `pt` (`PtLike`) — center position
- `radius` (`number`) — radius of the arc circle
- `startAngle` (`number`) — start angle of the arc
- `endAngle` (`number`) — end angle of the arc
- `cc` (`boolean`) — an optional boolean value to specify if it should be drawn clockwise (`false`) or counter-clockwise (`true`). Default is clockwise.

<a id="form-visualform-circle"></a>
##### `circle`

*abstract*

```ts
circle(pts: GroupLike | number[][]): this
```

Draw a circle (not implemented here  -- to be implemented in subclasses).

**Parameters**

- `pts` (`GroupLike | number[][]`) — usually a Group of 2 Pts, but it can also take an array of two numeric arrays [ [position], [size] ]

**See also:** [`Circle.fromCenter`](#op-circle-static-from-center)

<a id="form-visualform-circles"></a>
##### `circles`

```ts
circles(groups: GroupLike[]): this
```

Draw multiple circles at once.

**Parameters**

- `groups` (`GroupLike[]`) — an array of Groups that defines multiple circles

<a id="form-visualform-fill"></a>
##### `fill`

```ts
fill(c: string | boolean): this
```

Set fill color (not implemented here  -- to be implemented in subclasses).

**Parameters**

- `c` (`string | boolean`) — fill color as string or `false` to specify transparent.

<a id="form-visualform-fill-only"></a>
##### `fillOnly`

```ts
fillOnly(c: string | boolean): this
```

Set current fill style and remove stroke style. (not implemented here  -- to be implemented in subclasses).

**Parameters**

- `c` (`string | boolean`) — fill color as string or `false` to specify transparent.

<a id="form-visualform-font"></a>
##### `font`

*abstract*

```ts
font(sizeOrFont: number | Font, weight: string, style: string, lineHeight: number, family: string): this
```

Set font style (not implemented here  -- to be implemented in subclasses).

**Parameters**

- `sizeOrFont` (`number | Font`) — either a number to specify font-size, or a `Font` object to specify all font properties
- `weight` (`string`) — Optional font-weight string such as "bold"
- `style` (`string`) — Optional font-style string such as "italic"
- `lineHeight` (`number`) — Optional line-height number suchas 1.5
- `family` (`string`) — Optional font-family such as "Helvetica, sans-serif"

**See also:** `Font` class

**Example**

```ts
form.font( myFont )`, `form.font(14, "bold")
```

<a id="form-visualform-line"></a>
##### `line`

*abstract*

```ts
line(pts: GroupLike | number[][]): this
```

Draw a line or polyline (not implemented here  -- to be implemented in subclasses).

**Parameters**

- `pts` (`GroupLike | number[][]`) — a Group of multiple Pts, or an array of multiple numeric arrays

<a id="form-visualform-lines"></a>
##### `lines`

```ts
lines(groups: GroupLike[]): this
```

Draw multiple lines at once.

**Parameters**

- `groups` (`GroupLike[]`) — An array of Groups of Pts

<a id="form-visualform-point"></a>
##### `point`

*abstract*

```ts
point(p: PtLike, radius: number, shape: string): this
```

Draw a point (not implemented here  -- to be implemented in subclasses).

**Parameters**

- `p` (`PtLike`) — a Pt object
- `radius` (`number`) — radius of the point. Default is 5.
- `shape` (`string`) — The shape of the point. Defaults to "square", but it can be "circle" or a custom shape function in your own implementation.

**Example**

```ts
form.point( p )`, `form.point( p, 10, "circle" )
```

<a id="form-visualform-points"></a>
##### `points`

```ts
points(pts: GroupLike | number[][], radius: number, shape: string): this
```

Draw multiple points at once.

**Parameters**

- `pts` (`GroupLike | number[][]`) — an array of Pt or an array of number arrays
- `radius` (`number`) — radius of the point. Default is 5.
- `shape` (`string`) — The shape of the point. Defaults to "square", but it can be "circle" or a custom shape function in your own implementation.

<a id="form-visualform-polygon"></a>
##### `polygon`

*abstract*

```ts
polygon(pts: GroupLike | number[][]): this
```

Draw a polygon (not implemented here  -- to be implemented in subclasses).

**Parameters**

- `pts` (`GroupLike | number[][]`) — a Group of multiple Pts, or an array of multiple numeric arrays

<a id="form-visualform-polygons"></a>
##### `polygons`

```ts
polygons(groups: GroupLike[]): this
```

Draw multiple polygons at once.

**Parameters**

- `groups` (`GroupLike[]`) — An array of Groups of Pts

<a id="form-visualform-rect"></a>
##### `rect`

*abstract*

```ts
rect(pts: Pt[] | number[][]): this
```

Draw a rectangle (not implemented here  -- to be implemented in subclasses).

**Parameters**

- `pts` (`Pt[] | number[][]`) — usually a Group of 2 Pts specifying the top-left and bottom-right positions. Alternatively it can be an array of numeric arrays.

<a id="form-visualform-rects"></a>
##### `rects`

```ts
rects(groups: GroupLike[]): this
```

Draw multiple rectangles at once.

**Parameters**

- `groups` (`GroupLike[]`) — An array of Groups of Pts

<a id="form-visualform-reset"></a>
##### `reset`

*abstract*

```ts
reset(): this
```

Abstract reset style

<a id="form-visualform-squares"></a>
##### `squares`

```ts
squares(groups: GroupLike[]): this
```

Draw multiple squares at once.

**Parameters**

- `groups` (`GroupLike[]`) — an array of Groups that defines multiple circles

<a id="form-visualform-stroke"></a>
##### `stroke`

```ts
stroke(c: string | boolean, width: number, linejoin: string, linecap: string): this
```

Set stroke style (not implemented here  -- to be implemented in subclasses).

**Parameters**

- `c` (`string | boolean`) — stroke color as string or `false` to specify transparent.
- `width` (`number`) — Optional value (can be floating point) to set line width
- `linejoin` (`string`) — Optional string to set line joint style. Can be "miter", "bevel", or "round".
- `linecap` (`string`) — Optional string to set line cap style. Can be "butt", "round", or "square".

<a id="form-visualform-stroke-only"></a>
##### `strokeOnly`

```ts
strokeOnly(c: string | boolean, width: number, linejoin: string, linecap: string): this
```

Set stroke style and remove fill style. (not implemented here  -- to be implemented in subclasses).

**Parameters**

- `c` (`string | boolean`) — stroke color as string or `false` to specify transparent.
- `width` (`number`) — Optional value (can be floating point) to set line width
- `linejoin` (`string`) — Optional string to set line joint style. Can be "miter", "bevel", or "round".
- `linecap` (`string`) — Optional string to set line cap style. Can be "butt", "round", or "square".

<a id="form-visualform-text"></a>
##### `text`

*abstract*

```ts
text(pt: PtLike, txt: string, maxWidth: number): this
```

Draw text (not implemented here  -- to be implemented in subclasses).

**Parameters**

- `pt` (`PtLike`) — a Pt or numeric array to specify the anchor point
- `txt` (`string`) — text
- `maxWidth` (`number`) — specify a maximum width per line

#### Inherited API

- From [`Form`](#form-form): [`ready`](#form-form-ready).

<a id="module-image"></a>
## Module: `Image`

<a id="image-img"></a>
### `Img`

**Kind:** Class · **Source:** [`src/Image.ts:25`](https://github.com/williamngan/pts/blob/master/src/Image.ts#L25)

Img provides convenient functions to support image operations on HTML Canvas and [`CanvasSpace`](#canvas-canvasspace). Combine this with other Pts functions to experiment with visual forms that integrate bitmaps and vector graphics.

#### Constructors

<a id="image-img-constructor"></a>
##### Constructor

```ts
new Img(editable: boolean | ImgOptions = false, space: CanvasSpace, crossOrigin: boolean): Img
```

Create an Img

**Parameters**

- `editable` (`boolean | ImgOptions`; default `false`) — either an [`ImgOptions`](#image-imgoptions) object, or a boolean specifying if you want to manipulate pixels of this image. Default is `false`.
- `space` (`CanvasSpace`) — Set the `CanvasSpace` reference. This is optional but will make sure the image's pixelScale match the canvas and set the context for creating pattern.
- `crossOrigin` (`boolean`) — an optional parameter to enable loading cross-domain images if set to true. The image server's configuration must also be set correctly. For more, see [this documentation](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image).

**Example**

```ts
new Img(true, space)`, `new Img({ editable: true, pixelScale: 2 })
```

#### Accessors

<a id="image-img-canvas"></a>
##### `canvas`

```ts
get canvas(): HTMLCanvasElement
```

Get the internal canvas

<a id="image-img-canvas-size"></a>
##### `canvasSize`

```ts
get canvasSize(): Pt
```

Get size of the canvas

<a id="image-img-ctx"></a>
##### `ctx`

```ts
get ctx(): RenderingContext2D
```

Get the internal canvas' context. You can use this to draw directly on canvas, or create a new [CanvasForm](#canvas-canvasform) instance with it.

<a id="image-img-current"></a>
##### `current`

```ts
get current(): CanvasImageSource
```

Get current image source. If editable, this will return the canvas, otherwise it will return the original image.

<a id="image-img-data"></a>
##### `data`

```ts
get data(): ImageData
```

Get the internal canvas' ImageData

<a id="image-img-image"></a>
##### `image`

```ts
get image(): HTMLImageElement
```

Get the original image

<a id="image-img-image-size"></a>
##### `imageSize`

```ts
get imageSize(): Pt
```

Get size of the original image

<a id="image-img-loaded"></a>
##### `loaded`

```ts
get loaded(): boolean
```

Get whether the image is loaded

<a id="image-img-pixel-scale"></a>
##### `pixelScale`

```ts
get pixelScale(): number
```

Get pixel density scale

<a id="image-img-scaled-matrix"></a>
##### `scaledMatrix`

```ts
get scaledMatrix(): Mat
```

Get a Mat instance with a scale transform based on current `pixelScale`.
This can be useful for generating a domMatrix for transforming patterns consistently across different pixel-density screens.

#### Methods

<a id="image-img-bitmap"></a>
##### `bitmap`

```ts
bitmap(size: PtLike): Promise
```

Get an efficient, readonly bitmap of the current canvas.

**Parameters**

- `size` (`PtLike`) — Optional size to crop

**Returns:** a Promise that resolves to an ImageBitmap

<a id="image-img-cleanup"></a>
##### `cleanup`

```ts
cleanup(): void
```

Remove the elements and data associated with this Img.

**deprecated:** Use [`Img.dispose`](#image-img-dispose).

<a id="image-img-crop"></a>
##### `crop`

```ts
crop(box: Bound): ImageData
```

Crop an area of the image.

**Parameters**

- `box` (`Bound`) — bounding box

<a id="image-img-dispose"></a>
##### `dispose`

```ts
dispose(): this
```

Dispose of the elements, data, and any object URL associated with this Img. Pending loads reject; the instance should not be reused.

<a id="image-img-filter"></a>
##### `filter`

```ts
filter(css: string): this
```

Apply filters such as blur and grayscale to the canvas image. The original image is unchanged until `sync()`.

**Parameters**

- `css` (`string`) — a css filter string such as "blur(10px) contrast(200%)". See [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/filter#browser_compatibility) for a list of filter functions.

<a id="image-img-get-form"></a>
##### `getForm`

```ts
getForm(): CanvasForm | undefined
```

Get a CanvasForm for drawing on the internal canvas if this Img is editable

<a id="image-img-init-canvas"></a>
##### `initCanvas`

```ts
initCanvas(width: number, height: number, canvasScale: number | PtLike = 1): void
```

Initiate an editable canvas

**Parameters**

- `width` (`number`) — width of canvas
- `height` (`number`) — height of canvas
- `canvasScale` (`number | PtLike`; default `1`) — pixel scale

<a id="image-img-load"></a>
##### `load`

```ts
load(src: string): Promise
```

Load an image.

**Parameters**

- `src` (`string`) — an url of the image in same domain. Alternatively you can use a base64 string. To load from Blob, use `Img.fromBlob`.

**Returns:** a Promise that resolves to an Img

<a id="image-img-load-pixels"></a>
##### `loadPixels`

```ts
loadPixels(): this
```

Refresh the cached `ImageData` from the canvas — call this after drawing on the
canvas (eg, via [`Img.getForm`](#image-img-get-form)) before reading pixels.

<a id="image-img-pattern"></a>
##### `pattern`

```ts
pattern(reptition: CanvasPatternRepetition = "repeat", dynamic: boolean = false): CanvasPattern
```

Create a canvas pattern for `fill()`

**Parameters**

- `reptition` (`CanvasPatternRepetition`; default `"repeat"`) — set how the pattern should repeat-fill
- `dynamic` (`boolean`; default `false`) — If true, use this Img's internal canvas content as pattern fill. This enables the pattern to update dynamically.

**Returns:** a `CanvasPattern` instance for use in `fill()`

<a id="image-img-pixel"></a>
##### `pixel`

```ts
pixel(p: PtLike, rescale: number | boolean = true): Pt
```

Get the RGBA values of a pixel in the image

**Parameters**

- `p` (`PtLike`) — position of the pixel
- `rescale` (`number | boolean`; default `true`) — Specify if the pixel position should be scaled. Usually use rescale when tracking image and don't rescale when tracking canvas. You may also set a custom scale value.

**Returns:** [R,G,B,A] values of the pixel at the specific position

<a id="image-img-resize"></a>
##### `resize`

```ts
resize(sizeOrScale: PtLike, asScale: boolean = false): this
```

Resize the canvas image. The original image is unchanged until `sync()`.

**Parameters**

- `sizeOrScale` (`PtLike`) — A PtLike array specifying either [x, y] scales or [x, y] sizes.
- `asScale` (`boolean`; default `false`) — If true, treat the first parameter as scales. Otherwise, treat it as specific sizes.

<a id="image-img-set-pixel"></a>
##### `setPixel`

```ts
setPixel(p: PtLike, rgba: PtLike, rescale: number | boolean = true): this
```

Set the RGBA values of a pixel in the cached `ImageData`. Call [`Img.updatePixels`](#image-img-update-pixels)
to write the changes onto the canvas.

**Parameters**

- `p` (`PtLike`) — position of the pixel
- `rgba` (`PtLike`) — [R,G,B,A] values, 0-255
- `rescale` (`number | boolean`; default `true`) — Specify if the pixel position should be scaled, matching [`Img.pixel`](#image-img-pixel)

<a id="image-img-sync"></a>
##### `sync`

```ts
sync(): Promise
```

Replace the image with the current canvas data. For example, you can use CanvasForm's static functions to draw on `this.ctx` and then update the current image.
To display the internal canvas, use `form.image( [0, 0], img.current )`.

<a id="image-img-to-base64"></a>
##### `toBase64`

```ts
toBase64(): string
```

Export current canvas image as base64 string

<a id="image-img-to-blob"></a>
##### `toBlob`

```ts
toBlob(): Promise
```

Export current canvas image as a blob

<a id="image-img-update-pixels"></a>
##### `updatePixels`

```ts
updatePixels(): this
```

Write the cached `ImageData` (eg, after [`Img.setPixel`](#image-img-set-pixel) calls) back onto
the canvas.

<a id="image-img-static-blank"></a>
##### `blank`

*static*

```ts
static blank(size: PtLike, space: CanvasSpace, scale: number): Img
```

Create an editable blank image

**Parameters**

- `size` (`PtLike`) — of image
- `space` (`CanvasSpace`) — Optionally set the `CanvasSpace` reference. This is optional but will make sure the image's pixelScale match the canvas and set the context for creating pattern.
- `scale` (`number`) — Optionally set a specific pixel scale (density) of the image canvas.

<a id="image-img-static-from-blob"></a>
##### `fromBlob`

*static*

```ts
static fromBlob(blob: Blob, editable: boolean | ImgOptions = false, space: CanvasSpace): Promise
```

Create a blob url that can be passed to `Img.load`

**Parameters**

- `blob` (`Blob`) — an image blob such as `new Blob([my_Uint8Array], {type: 'image/png'})`
- `editable` (`boolean | ImgOptions`; default `false`) — Specify if you want to manipulate pixels of this image. Default is `false`.
- `space` (`CanvasSpace`)

<a id="image-img-static-get-pixel"></a>
##### `getPixel`

*static*

```ts
static getPixel(imgData: ImageData, p: PtLike): Pt
```

Given an ImaegData object and a position, return the RGBA pixel value at that position.

**Parameters**

- `imgData` (`ImageData`) — an ImageData object
- `p` (`PtLike`) — a position on the image

**Returns:** [R,G,B,A] values of the pixel at the specific position

<a id="image-img-static-image-data-to-blob"></a>
##### `imageDataToBlob`

*static*

```ts
static imageDataToBlob(data: ImageData): Promise
```

Convert ImageData object to a Blob, which you can then create an Img instance via [`Img.fromBlob`](#image-img-static-from-blob). Note that the resulting image's dimensions will not account for pixel density.

**Parameters**

- `data` (`ImageData`)

<a id="image-img-static-load"></a>
##### `load`

*static*

```ts
static load(src: string, editable: boolean | ImgOptions = false, space: CanvasSpace, ready:  Fn(img:Img)): Promise
```

A static function to load an image, returning a Promise that resolves to the loaded Img.
A load failure rejects the Promise.

**Parameters**

- `src` (`string`) — an url of the image in same domain. Alternatively you can use a base64 string. To load from Blob, use `Img.fromBlob`.
- `editable` (`boolean | ImgOptions`; default `false`) — either an [`ImgOptions`](#image-imgoptions) object, or a boolean specifying if you want to manipulate pixels of this image. Default is `false`.
- `space` (`CanvasSpace`) — Set the `CanvasSpace` reference. This is optional but will make sure the image's pixelScale match the canvas and set the context for creating pattern.
- `ready` (` Fn(img:Img)`) — An optional callback, invoked with the Img when loading succeeds

**Example**

```ts
const img = await Img.load("photo.jpg", true)
```

<a id="image-img-static-load-async"></a>
##### `loadAsync`

*static*

```ts
static loadAsync(src: string, editable: boolean | ImgOptions = false, space: CanvasSpace): Promise
```

A static method to load an image using async/await.

**Parameters**

- `src` (`string`) — an url of the image in same domain. Alternatively you can use a base64 string. To load from Blob, use `Img.fromBlob`.
- `editable` (`boolean | ImgOptions`; default `false`) — Specify if you want to manipulate pixels of this image. Default is `false`.
- `space` (`CanvasSpace`) — Set the `CanvasSpace` reference. This is optional but will make sure the image's pixelScale match the canvas and set the context for creating pattern.

**deprecated:** Use [`Img.load`](#image-img-load), which now returns a Promise.

<a id="image-img-static-load-pattern"></a>
##### `loadPattern`

*static*

```ts
static loadPattern(src: string, space: CanvasSpace, repeat: CanvasPatternRepetition = "repeat", editable: boolean = false): Promise
```

A static method to load an image pattern using async/await.

**Parameters**

- `src` (`string`) — an url of the image in same domain. Alternatively you can use a base64 string. To load from Blob, use `Img.fromBlob`.
- `space` (`CanvasSpace`) — Set the `CanvasSpace` reference. This is optional but will make sure the image's pixelScale match the canvas and set the context for creating pattern.
- `repeat` (`CanvasPatternRepetition`; default `"repeat"`) — set how the pattern will repeat fills
- `editable` (`boolean`; default `false`) — Specify if you want to manipulate pixels of this image. Default is `false`.

**Returns:** a `CanvasPattern` instance for use in `fill()`

<a id="image-imgoptions"></a>
### `ImgOptions`

**Kind:** Typealias · **Source:** [`src/Image.ts:11`](https://github.com/williamngan/pts/blob/master/src/Image.ts#L11)

Options for creating an [`Img`](#image-img).

```ts
type ImgOptions = { crossOrigin:boolean, editable:boolean, pixelScale:number, space:CanvasSpace };
```

<a id="module-linear-algebra"></a>
## Module: `LinearAlgebra`

<a id="linearalgebra-mat"></a>
### `Mat`

**Kind:** Class · **Source:** [`src/LinearAlgebra.ts:212`](https://github.com/williamngan/pts/blob/master/src/LinearAlgebra.ts#L212)

Mat provides various static functions for matrix operations as well as a convenient way to chain a 3x3 transformation matrix. It's not fully optimized but good enough to use.

#### Constructors

<a id="linearalgebra-mat-constructor"></a>
##### Constructor

```ts
new Mat(): Mat
```

#### Accessors

<a id="linearalgebra-mat-dom-matrix"></a>
##### `domMatrix`

```ts
get domMatrix(): DOMMatrix
```

Convert the value of its stored 3x3 matrix to a 2D [`DOMMatrix`](https://developer.mozilla.org/en-US/docs/Web/API/DOMMatrix) instance

<a id="linearalgebra-mat-value"></a>
##### `value`

```ts
get value(): GroupLike
```

Get the current value of its stored 3x3 matrix

#### Methods

<a id="linearalgebra-mat-reset"></a>
##### `reset`

```ts
reset(): void
```

Reset the internal 3x3 matrix to its identity

<a id="linearalgebra-mat-rotate2-d"></a>
##### `rotate2D`

```ts
rotate2D(ang: number, at: PtLike = ...): this
```

Scale the internal 3x3 matrix. You can chain this function with other related functions.

**Parameters**

- `ang` (`number`) — Angle of rotation
- `at` (`PtLike`; default `...`) — Optional origin location to rotate from.

<a id="linearalgebra-mat-scale2-d"></a>
##### `scale2D`

```ts
scale2D(val: PtLike, at: PtLike = ...): this
```

Scale the internal 3x3 matrix. You can chain this function with other related functions.

**Parameters**

- `val` (`PtLike`) — [x, y] scale factors
- `at` (`PtLike`; default `...`) — Optional origin location to scale from.

<a id="linearalgebra-mat-shear2-d"></a>
##### `shear2D`

```ts
shear2D(val: PtLike, at: PtLike = ...): this
```

Shear the internal 3x3 matrix. You can chain this function with other related functions.

**Parameters**

- `val` (`PtLike`) — [x, y] shear factors (before tan() operation)
- `at` (`PtLike`; default `...`) — Optional origin location to scale from.

<a id="linearalgebra-mat-translate2-d"></a>
##### `translate2D`

```ts
translate2D(val: PtLike): this
```

Translate the internal 3x3 matrix. You can chain this function with other related functions.

**Parameters**

- `val` (`PtLike`) — [x, y] offset values

<a id="linearalgebra-mat-static-add"></a>
##### `add`

*static*

```ts
static add(a: GroupLike, b: number | GroupLike | number[][]): Group
```

Matrix addition. Matrices should have the same rows and columns.

**Parameters**

- `a` (`GroupLike`) — a group of Pt
- `b` (`number | GroupLike | number[][]`) — a scalar number, an array of numeric arrays, or a group of Pt

**Returns:** a new group with the same rows and columns as a and b

<a id="linearalgebra-mat-static-multiply"></a>
##### `multiply`

*static*

```ts
static multiply(a: GroupLike, b: number | GroupLike | number[][], transposed: boolean = false, elementwise: boolean = false): Group
```

Matrix multiplication.

**Parameters**

- `a` (`GroupLike`) — a Group of M Pts, each with K dimensions (M-rows, K-columns)
- `b` (`number | GroupLike | number[][]`) — a scalar number, an array of numeric arrays, or a Group of K Pts, each with N dimensions (K-rows, N-columns) -- or if transposed is true, then N Pts with K dimensions
- `transposed` (`boolean`; default `false`) — (Only applicable if it's not elementwise multiplication) If true, then a and b's columns should match (ie, each Pt should have the same dimensions). Default is `false`.
- `elementwise` (`boolean`; default `false`) — if true, then the multiplication is done element-wise. Default is `false`.

**Returns:** If not elementwise, this will return a new group with M Pt, each with N dimensions (M-rows, N-columns).

<a id="linearalgebra-mat-static-reflect-at2-dmatrix"></a>
##### `reflectAt2DMatrix`

*static*

```ts
static reflectAt2DMatrix(p1: PtLike, p2: PtLike): Pt[]
```

Get a matrix to reflect a point along a line. For use in `transform2D`.

**Parameters**

- `p1` (`PtLike`) — first end point to define the reflection line
- `p2` (`PtLike`)

<a id="linearalgebra-mat-static-rotate2-dmatrix"></a>
##### `rotate2DMatrix`

*static*

```ts
static rotate2DMatrix(cosA: number, sinA: number): GroupLike
```

Get a rotate matrix for use in `transform2D`.

**Parameters**

- `cosA` (`number`)
- `sinA` (`number`)

<a id="linearalgebra-mat-static-rotate-at2-dmatrix"></a>
##### `rotateAt2DMatrix`

*static*

```ts
static rotateAt2DMatrix(cosA: number, sinA: number, at: PtLike): GroupLike
```

Get a matrix to rotate a point from an origin point. For use in `transform2D`.

**Parameters**

- `cosA` (`number`)
- `sinA` (`number`)
- `at` (`PtLike`)

<a id="linearalgebra-mat-static-scale2-dmatrix"></a>
##### `scale2DMatrix`

*static*

```ts
static scale2DMatrix(x: number, y: number): GroupLike
```

Get a scale matrix for use in `transform2D`.

**Parameters**

- `x` (`number`)
- `y` (`number`)

<a id="linearalgebra-mat-static-scale-at2-dmatrix"></a>
##### `scaleAt2DMatrix`

*static*

```ts
static scaleAt2DMatrix(sx: number, sy: number, at: PtLike): GroupLike
```

Get a matrix to scale a point from an origin point. For use in `transform2D`.

**Parameters**

- `sx` (`number`)
- `sy` (`number`)
- `at` (`PtLike`)

<a id="linearalgebra-mat-static-shear2-dmatrix"></a>
##### `shear2DMatrix`

*static*

```ts
static shear2DMatrix(tanX: number, tanY: number): GroupLike
```

Get a shear matrix for use in `transform2D`.

**Parameters**

- `tanX` (`number`)
- `tanY` (`number`)

<a id="linearalgebra-mat-static-shear-at2-dmatrix"></a>
##### `shearAt2DMatrix`

*static*

```ts
static shearAt2DMatrix(tanX: number, tanY: number, at: PtLike): GroupLike
```

Get a matrix to shear a point from an origin point. For use in `transform2D`.

**Parameters**

- `tanX` (`number`)
- `tanY` (`number`)
- `at` (`PtLike`)

<a id="linearalgebra-mat-static-to-dommatrix"></a>
##### `toDOMMatrix`

*static*

```ts
static toDOMMatrix(m: GroupLike | number[][]): number[]
```

**Parameters**

- `m` (`GroupLike | number[][]`)

<a id="linearalgebra-mat-static-transform2-d"></a>
##### `transform2D`

*static*

```ts
static transform2D(pt: PtLike, m: GroupLike | number[][]): Pt
```

Transform a 2D point given a 2x3 or 3x3 matrix.

**Parameters**

- `pt` (`PtLike`) — a Pt to be transformed
- `m` (`GroupLike | number[][]`) — 2x3 or 3x3 matrix

**Returns:** a new transformed Pt

<a id="linearalgebra-mat-static-translate2-dmatrix"></a>
##### `translate2DMatrix`

*static*

```ts
static translate2DMatrix(x: number, y: number): GroupLike
```

Get a translate matrix for use in `transform2D`.

**Parameters**

- `x` (`number`)
- `y` (`number`)

<a id="linearalgebra-mat-static-transpose"></a>
##### `transpose`

*static*

```ts
static transpose(g: GroupLike | number[][], defaultValue: number | boolean = false, useLongest: boolean = false): Group
```

Same as `zip` function.

**Parameters**

- `g` (`GroupLike | number[][]`)
- `defaultValue` (`number | boolean`; default `false`)
- `useLongest` (`boolean`; default `false`)

<a id="linearalgebra-mat-static-zip"></a>
##### `zip`

*static*

```ts
static zip(g: GroupLike | number[][], defaultValue: number | boolean = false, useLongest: boolean = false): Group
```

Zip a group of Pt. For example, `[[1,2],[3,4],[5,6]]` will become `[[1,3,5],[2,4,6]]`.

**Parameters**

- `g` (`GroupLike | number[][]`) — a group of Pt
- `defaultValue` (`number | boolean`; default `false`) — a default value to fill if index out of bound. If not provided, it will throw an error instead.
- `useLongest` (`boolean`; default `false`) — If true, find the longest list of values in a Pt and use its length for zipping. Default is false, which uses the first item's length for zipping.

<a id="linearalgebra-mat-static-zip-slice"></a>
##### `zipSlice`

*static*

```ts
static zipSlice(g: GroupLike | number[][], index: number, defaultValue: number | boolean = false): Pt
```

Zip one slice of an array of Pts. For example, if the input `g` are organized in rows, then this function will take the values in a specific column.

**Parameters**

- `g` (`GroupLike | number[][]`) — a group of Pt
- `index` (`number`) — index to zip at
- `defaultValue` (`number | boolean`; default `false`) — a default value to fill if index out of bound. If not provided, it will throw an error instead.

<a id="linearalgebra-vec"></a>
### `Vec`

**Kind:** Class · **Source:** [`src/LinearAlgebra.ts:9`](https://github.com/williamngan/pts/blob/master/src/LinearAlgebra.ts#L9)

Vec provides various static functions for vector operations. It's not fully optimized but good enough to use.

#### Methods

<a id="linearalgebra-vec-static-abs"></a>
##### `abs`

*static*

```ts
static abs(a: PtLike): PtLike
```

Set `a` to its absolute value in each dimension.

**Parameters**

- `a` (`PtLike`)

**Returns:** vector `a`

<a id="linearalgebra-vec-static-add"></a>
##### `add`

*static*

```ts
static add(a: PtLike, b: number | PtLike): PtLike
```

Add `b` to vector `a`. Unlike `multiply`/`divide`, a shorter `b` is tolerated: missing (or NaN) dimensions are treated as 0.

**Parameters**

- `a` (`PtLike`)
- `b` (`number | PtLike`)

**Returns:** vector `a`

<a id="linearalgebra-vec-static-ceil"></a>
##### `ceil`

*static*

```ts
static ceil(a: PtLike): PtLike
```

Set `a` to its ceiling value in each dimension.

**Parameters**

- `a` (`PtLike`)

**Returns:** vector `a`

<a id="linearalgebra-vec-static-cross"></a>
##### `cross`

*static*

```ts
static cross(a: PtLike, b: PtLike): Pt
```

3D Cross product of `a` and `b`.

**Parameters**

- `a` (`PtLike`)
- `b` (`PtLike`)

<a id="linearalgebra-vec-static-cross2-d"></a>
##### `cross2D`

*static*

```ts
static cross2D(a: PtLike, b: PtLike): number
```

2D cross product of `a` and `b`.

**Parameters**

- `a` (`PtLike`)
- `b` (`PtLike`)

<a id="linearalgebra-vec-static-divide"></a>
##### `divide`

*static*

```ts
static divide(a: PtLike, b: number | PtLike): PtLike
```

Divide `a` over `b`.

**Parameters**

- `a` (`PtLike`)
- `b` (`number | PtLike`)

**Returns:** vector `a`

<a id="linearalgebra-vec-static-dot"></a>
##### `dot`

*static*

```ts
static dot(a: PtLike, b: PtLike): number
```

Dot product of `a` and `b`.

**Parameters**

- `a` (`PtLike`)
- `b` (`PtLike`)

<a id="linearalgebra-vec-static-floor"></a>
##### `floor`

*static*

```ts
static floor(a: PtLike): PtLike
```

Set `a` to its floor value in each dimension.

**Parameters**

- `a` (`PtLike`)

**Returns:** vector `a`

<a id="linearalgebra-vec-static-magnitude"></a>
##### `magnitude`

*static*

```ts
static magnitude(a: PtLike): number
```

Magnitude of `a`.

**Parameters**

- `a` (`PtLike`)

<a id="linearalgebra-vec-static-map"></a>
##### `map`

*static*

```ts
static map(a: PtLike, fn:  Fn(n:number, index:number, arr:PtLike)): PtLike
```

Given a mapping function, update `a`'s value in each dimension.

**Parameters**

- `a` (`PtLike`)
- `fn` (` Fn(n:number, index:number, arr:PtLike)`)

**Returns:** vector `a`

<a id="linearalgebra-vec-static-max"></a>
##### `max`

*static*

```ts
static max(a: PtLike): { index:number, value:number }
```

Find the max value within a vector's dimensions.

**Parameters**

- `a` (`PtLike`)

**Returns:** an object with `value` and `index` that specifies the max value and its corresponding dimension.

<a id="linearalgebra-vec-static-min"></a>
##### `min`

*static*

```ts
static min(a: PtLike): { index:number, value:number }
```

Find the min value within a vector's dimensions.

**Parameters**

- `a` (`PtLike`)

**Returns:** an object with `value` and `index` that specifies the min value and its corresponding dimension.

<a id="linearalgebra-vec-static-multiply"></a>
##### `multiply`

*static*

```ts
static multiply(a: PtLike, b: number | PtLike): PtLike
```

Multiply `b` with vector `a`.

**Parameters**

- `a` (`PtLike`)
- `b` (`number | PtLike`)

**Returns:** vector `a`

<a id="linearalgebra-vec-static-round"></a>
##### `round`

*static*

```ts
static round(a: PtLike): PtLike
```

Set `a` to its rounded value in each dimension.

**Parameters**

- `a` (`PtLike`)

**Returns:** vector `a`

<a id="linearalgebra-vec-static-subtract"></a>
##### `subtract`

*static*

```ts
static subtract(a: PtLike, b: number | PtLike): PtLike
```

Subtract `b` from vector `a`. Unlike `multiply`/`divide`, a shorter `b` is tolerated: missing (or NaN) dimensions are treated as 0.

**Parameters**

- `a` (`PtLike`)
- `b` (`number | PtLike`)

**Returns:** vector `a`

<a id="linearalgebra-vec-static-sum"></a>
##### `sum`

*static*

```ts
static sum(a: PtLike): number
```

Add up all the dimensions' values and returns a scalar of the sum.

**Parameters**

- `a` (`PtLike`)

<a id="linearalgebra-vec-static-unit"></a>
##### `unit`

*static*

```ts
static unit(a: PtLike, magnitude: number | undefined = undefined): PtLike
```

Unit vector of `a`. If magnitude of `a` is already known, pass it in the second paramter to optimize calculation.

**Parameters**

- `a` (`PtLike`)
- `magnitude` (`number | undefined`; default `undefined`)

<a id="module-num"></a>
## Module: `Num`

<a id="num-geom"></a>
### `Geom`

**Kind:** Class · **Source:** [`src/Num.ts:203`](https://github.com/williamngan/pts/blob/master/src/Num.ts#L203)

Geom class provides static helper functions for basic geometric operations.

#### Methods

<a id="num-geom-static-anchor"></a>
##### `anchor`

*static*

```ts
static anchor(pts: PtLikeIterable, ptOrIndex: number | PtLike = 0, direction: to | from = "to"): void
```

Given an anchor Pt, rebase all Pts in this group either to or from this anchor base.

**Parameters**

- `pts` (`PtLikeIterable`) — a Group or an Iterable<PtLike>
- `ptOrIndex` (`number | PtLike`; default `0`) — an index for the Pt array, or an external Pt
- `direction` (`to | from`; default `"to"`) — a string either "to" (subtract all Pt with this anchor base), or "from" (add all Pt from this anchor base)

<a id="num-geom-static-bound-angle"></a>
##### `boundAngle`

*static*

```ts
static boundAngle(angle: number): number
```

Bound an angle between 0 to 360 degrees.

**Parameters**

- `angle` (`number`) — angle value

<a id="num-geom-static-bounding-box"></a>
##### `boundingBox`

*static*

```ts
static boundingBox(pts: PtIterable): Group
```

Get a bounding box for a set of Pts.

**Parameters**

- `pts` (`PtIterable`) — a Group or an Iterable<Pt>

**Returns:** a Group of two Pts, representing the top-left and bottom-right corners

<a id="num-geom-static-bound-radian"></a>
##### `boundRadian`

*static*

```ts
static boundRadian(radian: number): number
```

Bound a radian between 0 to two PI.

**Parameters**

- `radian` (`number`) — radian value

<a id="num-geom-static-centroid"></a>
##### `centroid`

*static*

```ts
static centroid(pts: PtLikeIterable): Pt
```

Get a centroid (the average middle point) for a set of Pts.

**Parameters**

- `pts` (`PtLikeIterable`) — a Group or an Iterable<PtLike>

**Returns:** a centroid Pt

<a id="num-geom-static-cos-table"></a>
##### `cosTable`

*static*

```ts
static cosTable(): { cos: Fn(rad:number), table:Float64Array }
```

Generate a cosine lookup table.

**Returns:** an object with a cosine tables (array of 360 values) and a function to get cosine given a radian input.

<a id="num-geom-static-interpolate"></a>
##### `interpolate`

*static*

```ts
static interpolate(a: PtLike, b: PtLike, t: number = 0.5): Pt
```

Get an interpolated (or extrapolated) value between two Pts. For linear interpolation between 2 scalar values, use [`Num.lerp`](#num-num-static-lerp).

**Parameters**

- `a` (`PtLike`) — first Pt
- `b` (`PtLike`) — second Pt
- `t` (`number`; default `0.5`) — a value between 0 to 1 to interpolate, or any other value to extrapolate

**Returns:** interpolated point as a new Pt

<a id="num-geom-static-is-perpendicular"></a>
##### `isPerpendicular`

*static*

```ts
static isPerpendicular(p1: PtLike, p2: PtLike): boolean
```

Check if two Pts are perpendicular to each other (2D only).

**Parameters**

- `p1` (`PtLike`)
- `p2` (`PtLike`)

<a id="num-geom-static-perpendicular"></a>
##### `perpendicular`

*static*

```ts
static perpendicular(pt: PtLike, axis: string | PtLike = Const.xy): Group
```

Find two Pts that are perpendicular to this Pt (2D only).

**Parameters**

- `pt` (`PtLike`)
- `axis` (`string | PtLike`; default `Const.xy`) — a string such as "xy" (use Const.xy) or an array to specify index for two dimensions

**Returns:** an array of two Pt that are perpendicular to this Pt

<a id="num-geom-static-reflect2-d"></a>
##### `reflect2D`

*static*

```ts
static reflect2D(ps: Pt | PtIterable, line: PtLikeIterable, axis: string | PtLike): Geom
```

Reflect a Pt or a Group of Pts along a 2D line. You may also use [`Pt.reflect2D`](#pt-pt-reflect2-d) instance method.

**Parameters**

- `ps` (`Pt | PtIterable`) — either a single Pt, or a Group or an Iterable<Pt>
- `line` (`PtLikeIterable`) — a Group or an Iterable<PtLike> that defines a line for reflection
- `axis` (`string | PtLike`) — optional axis such as "xy" (use Const.xy) to define a 2D plane, or a number array to specify indices

<a id="num-geom-static-rotate2-d"></a>
##### `rotate2D`

*static*

```ts
static rotate2D(ps: Pt | PtIterable, angle: number, anchor: PtLike, axis: string | PtLike): Geom
```

Rotate a Pt or a Group of Pts in 2D space. You may also use [`Pt.rotate2D`](#pt-pt-rotate2-d) instance method.

**Parameters**

- `ps` (`Pt | PtIterable`) — either a single Pt, or a Group or an Iterable<Pt>
- `angle` (`number`) — rotate angle
- `anchor` (`PtLike`) — optional anchor point to rotate from
- `axis` (`string | PtLike`) — optional axis such as "xy" (use Const.xy) to define a 2D plane, or a number array to specify indices

<a id="num-geom-static-scale"></a>
##### `scale`

*static*

```ts
static scale(ps: Pt | PtIterable, scale: number | PtLike, anchor: PtLike): Geom
```

Scale a Pt or a Group of Pts. You may also use [`Pt.scale`](#pt-pt-scale) instance method.

**Parameters**

- `ps` (`Pt | PtIterable`) — either a single Pt, or a Group or an Iterable<Pt>
- `scale` (`number | PtLike`) — scale value
- `anchor` (`PtLike`) — optional anchor point to scale from

<a id="num-geom-static-shear2-d"></a>
##### `shear2D`

*static*

```ts
static shear2D(ps: Pt | PtIterable, scale: number | PtLike, anchor: PtLike, axis: string | PtLike): Geom
```

Shear a Pt or a Group of Pts in 2D space. You may also use [`Pt.shear2D`](#pt-pt-shear2-d) instance method.

**Parameters**

- `ps` (`Pt | PtIterable`) — either a single Pt, or a Group or an Iterable<Pt>
- `scale` (`number | PtLike`) — shearing value which can be a number or an array of 2 numbers
- `anchor` (`PtLike`) — optional anchor point to shear from
- `axis` (`string | PtLike`) — optional axis such as "xy" (use Const.xy) to define a 2D plane, or a number array to specify indices

<a id="num-geom-static-sin-table"></a>
##### `sinTable`

*static*

```ts
static sinTable(): { sin: Fn(rad:number), table:Float64Array }
```

Generate a sine lookup table.

**Returns:** an object with a sine tables (array of 360 values) and a function to get sine value given a radian input.

<a id="num-geom-static-sort-edges"></a>
##### `sortEdges`

*static*

```ts
static sortEdges(pts: PtIterable): GroupLike
```

Sort the Pts so that their edges will form a non-overlapping polygon. ([Reference](https://stackoverflow.com/questions/6989100/sort-points-in-clockwise-order))

**Parameters**

- `pts` (`PtIterable`) — a Group or an Iterable<Pt>

<a id="num-geom-static-to-degree"></a>
##### `toDegree`

*static*

```ts
static toDegree(radian: number): number
```

Convert an angle in radian to degree.

**Parameters**

- `radian` (`number`) — radian value

<a id="num-geom-static-to-radian"></a>
##### `toRadian`

*static*

```ts
static toRadian(angle: number): number
```

Convert an angle in degree to radian.

**Parameters**

- `angle` (`number`) — angle value

<a id="num-geom-static-within-bound"></a>
##### `withinBound`

*static*

```ts
static withinBound(pt: PtLike, boundPt1: PtLike, boundPt2: PtLike): boolean
```

Check if a Pt is within the rectangular boundary defined by two Pts.

**Parameters**

- `pt` (`PtLike`) — the Pt to check
- `boundPt1` (`PtLike`) — boundary Pt 1
- `boundPt2` (`PtLike`) — boundary Pt 2

<a id="num-num"></a>
### `Num`

**Kind:** Class · **Source:** [`src/Num.ts:18`](https://github.com/williamngan/pts/blob/master/src/Num.ts#L18)

Num class provides static helper functions for basic numeric operations.

#### Methods

<a id="num-num-static-average"></a>
##### `average`

*static*

```ts
static average(pts: PtLikeIterable): Pt
```

Average a group of numeric arrays

**Parameters**

- `pts` (`PtLikeIterable`) — a Group or an Iterable<PtLike>

**Returns:** a Pt of averages

<a id="num-num-static-bound-value"></a>
##### `boundValue`

*static*

```ts
static boundValue(val: number, min: number, max: number): number
```

Different from [`Num.clamp`](#num-num-static-clamp) in that the value out-of-bound will be "looped back" to the other end.

**Parameters**

- `val` (`number`) — value to bound
- `min` (`number`) — min value
- `max` (`number`) — max value

**Example**

```ts
boundValue(361, 0, 360)` will return 1
```

<a id="num-num-static-clamp"></a>
##### `clamp`

*static*

```ts
static clamp(val: number, min: number, max: number): number
```

Clamp values between min and max.

**Parameters**

- `val` (`number`) — value to clamp
- `min` (`number`) — min value
- `max` (`number`) — max value

<a id="num-num-static-cycle"></a>
##### `cycle`

*static*

```ts
static cycle(t: number, method:  Fn(t:number) = Shaping.sineInOut): number
```

Given a value between 0 to 1, returns a value that cycles between 0 -> 1 -> 0 using the provided shaping method.

**Parameters**

- `t` (`number`) — a value between 0 to 1
- `method` (` Fn(t:number)`; default `Shaping.sineInOut`) — a shaping method. Default to [`Shaping.sineInOut`](#num-shaping-static-sine-in-out).

**Returns:** a value between 0 to 1

<a id="num-num-static-equals"></a>
##### `equals`

*static*

```ts
static equals(a: number, b: number, threshold: number = 0.00001): boolean
```

Check if two numbers are equal or almost equal within a threshold.

**Parameters**

- `a` (`number`) — number a
- `b` (`number`) — number b
- `threshold` (`number`; default `0.00001`) — threshold value that specifies the minimum difference within which the two numbers are considered equal

<a id="num-num-static-lerp"></a>
##### `lerp`

*static*

```ts
static lerp(a: number, b: number, t: number): number
```

Calculate linear interpolation between 2 values.

**Parameters**

- `a` (`number`) — start value
- `b` (`number`) — end value
- `t` (`number`) — an interpolation value, usually between 0 to 1

<a id="num-num-static-map-to-range"></a>
##### `mapToRange`

*static*

```ts
static mapToRange(n: number, currA: number, currB: number, targetA: number, targetB: number): number
```

Map a value from one range to another.

**Parameters**

- `n` (`number`) — a value in the first range
- `currA` (`number`) — first endpoint of the input range
- `currB` (`number`) — second endpoint of the input range
- `targetA` (`number`) — first endpoint of the output range
- `targetB` (`number`) — second endpoint of the output range

**Returns:** a remapped value in the second range

<a id="num-num-static-normalize-value"></a>
##### `normalizeValue`

*static*

```ts
static normalizeValue(n: number, a: number, b: number): number
```

Normalize a value within a range.

**Parameters**

- `n` (`number`) — the value to normalize
- `a` (`number`) — range value 1
- `b` (`number`) — range value 1

<a id="num-num-static-random"></a>
##### `random`

*static*

```ts
static random(): number
```

Return a random number between 0 and 1. If a seed was set via [`Num.seed`](#num-num-static-seed),
draws come from the seeded generator with 32-bit resolution (exact multiples of 2^-32);
otherwise it uses `Math.random`.

**Returns:** a number between 0 and 1

<a id="num-num-static-random-pt"></a>
##### `randomPt`

*static*

```ts
static randomPt(a: PtLike, b: PtLike): Pt
```

Get a random Pt within the range defined by either 1 or 2 Pt

**Parameters**

- `a` (`PtLike`) — the range if only one Pt is used, or the start of the range if two Pt were used
- `b` (`PtLike`) — optional Pt to define the end of the range

<a id="num-num-static-random-range"></a>
##### `randomRange`

*static*

```ts
static randomRange(a: number, b: number = 0): number
```

Get a random number within a range.

**Parameters**

- `a` (`number`) — range value 1
- `b` (`number`; default `0`) — range value 2

<a id="num-num-static-seed"></a>
##### `seed`

*static*

```ts
static seed(seed: string): void
```

Seed the pseudorandom generator for reproducible [`Num.random`](#num-num-static-random) sequences.
The seed is hashed by its *effective* key: leading/trailing whitespace and embedded
control characters are stripped first, so seeds differing only in those collide.
An empty (or whitespace-only) seed yields a fixed default sequence. This generator
is deterministic and statistically strong, but not cryptographically secure.

**Parameters**

- `seed` (`string`) — seed string

<a id="num-num-static-sum"></a>
##### `sum`

*static*

```ts
static sum(pts: PtLikeIterable): Pt
```

Sum a group of numeric arrays.

**Parameters**

- `pts` (`PtLikeIterable`) — a Group or an Iterable<PtLike>

**Returns:** a Pt of the dimensional sums

<a id="num-num-static-within"></a>
##### `within`

*static*

```ts
static within(p: number, a: number, b: number): boolean
```

Check if a value is within two other values

**Parameters**

- `p` (`number`) — value to check
- `a` (`number`) — first bounding value
- `b` (`number`) — second bounding value

#### Properties

<a id="num-num-static-generator"></a>
##### `generator`

*static*

```ts
static generator: any
```

<a id="num-range"></a>
### `Range`

**Kind:** Class · **Source:** [`src/Num.ts:974`](https://github.com/williamngan/pts/blob/master/src/Num.ts#L974)

Range object keeps track of a Group of n-dimensional Pts to provide its minimum, maximum, and magnitude in each dimension.
It also provides convenient functions such as mapping the Group to another range. This class may be useful for visualizing data in charts.

#### Constructors

<a id="num-range-constructor"></a>
##### Constructor

```ts
new Range(g: PtIterable): Range
```

Construct a Range instance for a Group of Pts.

**Parameters**

- `g` (`PtIterable`) — a Group or an Iterable<Pt>

#### Accessors

<a id="num-range-magnitude"></a>
##### `magnitude`

```ts
get magnitude(): Pt
```

Get this Range's magnitude in each dimension.

<a id="num-range-max"></a>
##### `max`

```ts
get max(): Pt
```

Get this Range's maximum values per dimension.

<a id="num-range-min"></a>
##### `min`

```ts
get min(): Pt
```

Get this Range's minimum values per dimension.

#### Methods

<a id="num-range-append"></a>
##### `append`

```ts
append(pts: PtLikeIterable, update: boolean = true): this
```

Add more Pts to this Range and recalculate its min and max values.

**Parameters**

- `pts` (`PtLikeIterable`) — a Group or an Iterable<PtLike> to append to this Range
- `update` (`boolean`; default `true`) — Optional. Set the parameter to `false` if you want to append without immediately updating this Range's min and max values. Default is `true`.

<a id="num-range-calc"></a>
##### `calc`

```ts
calc(): Range | undefined
```

Go through the group and find its min and max values. Usually you don't need to call this function directly.

<a id="num-range-map-to"></a>
##### `mapTo`

```ts
mapTo(min: number, max: number, exclude: boolean[]): Group
```

Map this Range to another range of values.

**Parameters**

- `min` (`number`) — target range's minimum value
- `max` (`number`) — target range's maximum value
- `exclude` (`boolean[]`) — Optional boolean array where `true` means excluding the conversion in that specific dimension.

<a id="num-range-ticks"></a>
##### `ticks`

```ts
ticks(count: number): Group
```

Create a number of evenly spaced "ticks" that span this Range's min and max value.

**Parameters**

- `count` (`number`) — number of subdivision. For example, 10 subdivision will return 11 tick values, which include first(min) and last(max) values.

<a id="num-shaping"></a>
### `Shaping`

**Kind:** Class · **Source:** [`src/Num.ts:576`](https://github.com/williamngan/pts/blob/master/src/Num.ts#L576)

Shaping provides shaping functions to interpolate a value. These are useful for easing and transitions.

#### Methods

<a id="num-shaping-static-bounce-in"></a>
##### `bounceIn`

*static*

```ts
static bounceIn(t: number, c: number = 1): number
```

Bounce in, adapted from Robert Penner's [easing functions](http://robertpenner.com/easing/).

**Parameters**

- `t` (`number`) — a value between 0 to 1
- `c` (`number`; default `1`) — the value to shape, default is 1

<a id="num-shaping-static-bounce-in-out"></a>
##### `bounceInOut`

*static*

```ts
static bounceInOut(t: number, c: number = 1): number
```

Bounce in-out, adapted from Robert Penner's [easing functions](http://robertpenner.com/easing/).

**Parameters**

- `t` (`number`) — a value between 0 to 1
- `c` (`number`; default `1`) — the value to shape, default is 1

<a id="num-shaping-static-bounce-out"></a>
##### `bounceOut`

*static*

```ts
static bounceOut(t: number, c: number = 1): number
```

Bounce out, adapted from Robert Penner's [easing functions](http://robertpenner.com/easing/).

**Parameters**

- `t` (`number`) — a value between 0 to 1
- `c` (`number`; default `1`) — the value to shape, default is 1

<a id="num-shaping-static-circular-in"></a>
##### `circularIn`

*static*

```ts
static circularIn(t: number, c: number = 1): number
```

Circular in, adapted from Robert Penner's [easing functions](http://robertpenner.com/easing/).

**Parameters**

- `t` (`number`) — a value between 0 to 1
- `c` (`number`; default `1`) — the value to shape, default is 1

<a id="num-shaping-static-circular-in-out"></a>
##### `circularInOut`

*static*

```ts
static circularInOut(t: number, c: number = 1): number
```

Circular in-out, adapted from Robert Penner's [easing functions](http://robertpenner.com/easing/).

**Parameters**

- `t` (`number`) — a value between 0 to 1
- `c` (`number`; default `1`) — the value to shape, default is 1

<a id="num-shaping-static-circular-out"></a>
##### `circularOut`

*static*

```ts
static circularOut(t: number, c: number = 1): number
```

Circular out, adapted from Robert Penner's [easing functions](http://robertpenner.com/easing/).

**Parameters**

- `t` (`number`) — a value between 0 to 1
- `c` (`number`; default `1`) — the value to shape, default is 1

<a id="num-shaping-static-cliff"></a>
##### `cliff`

*static*

```ts
static cliff(t: number, c: number = 1, p: number = 0.5): number
```

Step function is a simple jump from 0 to 1 at a specific Pt in time.

**Parameters**

- `t` (`number`) — a value between 0 to 1
- `c` (`number`; default `1`) — the value to shape, default is 1
- `p` (`number`; default `0.5`) — usually a value between 0 to 1, which specify the Pt to "jump". Default is 0.5 which is in the middle.

<a id="num-shaping-static-cosine-approx"></a>
##### `cosineApprox`

*static*

```ts
static cosineApprox(t: number, c: number = 1): number
```

A faster way to approximate cosine ease in-out using Blinn-Wyvill Approximation. Adapated from Golan Levin's [polynomial shaping](http://www.flong.com/texts/code/shapers_poly/).

**Parameters**

- `t` (`number`) — a value between 0 to 1
- `c` (`number`; default `1`) — the value to shape, default is 1

<a id="num-shaping-static-cubic-bezier"></a>
##### `cubicBezier`

*static*

```ts
static cubicBezier(t: number, c: number = 1, p1: PtLike = ..., p2: PtLike = ...): number
```

Cubic bezier curve from (0, 0) to (1, 1) with two control points. Note that `t` is the curve parameter, not the x position: unlike CSS `cubic-bezier(...)`, this returns the curve's y value at parameter `t` rather than solving y at x = t.

**Parameters**

- `t` (`number`) — a value between 0 to 1
- `c` (`number`; default `1`) — the value to shape, default is 1
- `p1` (`PtLike`; default `...`) — ` a Pt object specifying the first control Pt. Default is `Pt(0.1, 0.7).
- `p2` (`PtLike`; default `...`) — ` a Pt object specifying the second control Pt. Default is `Pt(0.9, 0.2).

<a id="num-shaping-static-cubic-in"></a>
##### `cubicIn`

*static*

```ts
static cubicIn(t: number, c: number = 1): number
```

Cubic in, adapted from Robert Penner's [easing functions](http://robertpenner.com/easing/).

**Parameters**

- `t` (`number`) — a value between 0 to 1
- `c` (`number`; default `1`) — the value to shape, default is 1

<a id="num-shaping-static-cubic-in-out"></a>
##### `cubicInOut`

*static*

```ts
static cubicInOut(t: number, c: number = 1): number
```

Cubic in-out, adapted from Robert Penner's [easing functions](http://robertpenner.com/easing/).

**Parameters**

- `t` (`number`) — a value between 0 to 1
- `c` (`number`; default `1`) — the value to shape, default is 1

<a id="num-shaping-static-cubic-out"></a>
##### `cubicOut`

*static*

```ts
static cubicOut(t: number, c: number = 1): number
```

Cubic out, adapted from Robert Penner's [easing functions](http://robertpenner.com/easing/).

**Parameters**

- `t` (`number`) — a value between 0 to 1
- `c` (`number`; default `1`) — the value to shape, default is 1

<a id="num-shaping-static-elastic-in"></a>
##### `elasticIn`

*static*

```ts
static elasticIn(t: number, c: number = 1, p: number = 0.7): number
```

Elastic in, adapted from Robert Penner's [easing functions](http://robertpenner.com/easing/).

**Parameters**

- `t` (`number`) — a value between 0 to 1
- `c` (`number`; default `1`) — the value to shape, default is 1
- `p` (`number`; default `0.7`) — elastic parmeter between 0 to 1. The lower the number, the more elastic it will be. Default is 0.7.

<a id="num-shaping-static-elastic-in-out"></a>
##### `elasticInOut`

*static*

```ts
static elasticInOut(t: number, c: number = 1, p: number = 0.6): number
```

Elastic in-out, adapted from Robert Penner's [easing functions](http://robertpenner.com/easing/).

**Parameters**

- `t` (`number`) — a value between 0 to 1
- `c` (`number`; default `1`) — the value to shape, default is 1
- `p` (`number`; default `0.6`) — elastic parmeter between 0 to 1. The lower the number, the more elastic it will be. Default is 0.6.

<a id="num-shaping-static-elastic-out"></a>
##### `elasticOut`

*static*

```ts
static elasticOut(t: number, c: number = 1, p: number = 0.7): number
```

Elastic out, adapted from Robert Penner's [easing functions](http://robertpenner.com/easing/).

**Parameters**

- `t` (`number`) — a value between 0 to 1
- `c` (`number`; default `1`) — the value to shape, default is 1
- `p` (`number`; default `0.7`) — elastic parmeter between 0 to 1. The lower the number, the more elastic it will be. Default is 0.7.

<a id="num-shaping-static-exponential-in"></a>
##### `exponentialIn`

*static*

```ts
static exponentialIn(t: number, c: number = 1, p: number = 0.25): number
```

Exponential ease in, adapted from Golan Levin's [polynomial shapers](http://www.flong.com/texts/code/shapers_poly/).

**Parameters**

- `t` (`number`) — a value between 0 to 1
- `c` (`number`; default `1`) — the value to shape, default is 1
- `p` (`number`; default `0.25`) — a value between 0 to 1 to control the curve. Default is 0.25.

<a id="num-shaping-static-exponential-out"></a>
##### `exponentialOut`

*static*

```ts
static exponentialOut(t: number, c: number = 1, p: number = 0.25): number
```

Exponential ease out, adapted from Golan Levin's [polynomial shapers](http://www.flong.com/texts/code/shapers_poly/).

**Parameters**

- `t` (`number`) — a value between 0 to 1
- `c` (`number`; default `1`) — the value to shape, default is 1
- `p` (`number`; default `0.25`) — a value between 0 to 1 to control the curve. Default is 0.25.

<a id="num-shaping-static-linear"></a>
##### `linear`

*static*

```ts
static linear(t: number, c: number = 1): number
```

Linear mapping.

**Parameters**

- `t` (`number`) — a value between 0 to 1
- `c` (`number`; default `1`) — the value to shape, default is 1

<a id="num-shaping-static-log-sigmoid"></a>
##### `logSigmoid`

*static*

```ts
static logSigmoid(t: number, c: number = 1, p: number = 0.7): number
```

Logistic sigmoid, adapted from Golan Levin's [shaping function](http://www.flong.com/texts/code/shapers_exp/).

**Parameters**

- `t` (`number`) — a value between 0 to 1
- `c` (`number`; default `1`) — the value to shape, default is 1
- `p` (`number`; default `0.7`) — a parameter between 0 to 1 to control the steepness of the curve. Higher is steeper. Default is 0.7.

<a id="num-shaping-static-quadratic-bezier"></a>
##### `quadraticBezier`

*static*

```ts
static quadraticBezier(t: number, c: number = 1, p: number | PtLike = ...): number
```

Quadratic bezier curve, adapted from Golan Levin's [shaping functions](http://www.flong.com/texts/code/shapers_exp/).

**Parameters**

- `t` (`number`) — a value between 0 to 1
- `c` (`number`; default `1`) — the value to shape, default is 1
- `p` (`number | PtLike`; default `...`) — a Pt object specifying the control Pt, or a value specifying its x position (its y position will default to 0.5). Default is `[0.05, 0.95]`.

<a id="num-shaping-static-quadratic-in"></a>
##### `quadraticIn`

*static*

```ts
static quadraticIn(t: number, c: number = 1): number
```

Quadratic in, adapted from Robert Penner's [easing functions](http://robertpenner.com/easing/).

**Parameters**

- `t` (`number`) — a value between 0 to 1
- `c` (`number`; default `1`) — the value to shape, default is 1

<a id="num-shaping-static-quadratic-in-out"></a>
##### `quadraticInOut`

*static*

```ts
static quadraticInOut(t: number, c: number = 1): number
```

Quadratic in-out, adapted from Robert Penner's [easing functions](http://robertpenner.com/easing/).

**Parameters**

- `t` (`number`) — a value between 0 to 1
- `c` (`number`; default `1`) — the value to shape, default is 1

<a id="num-shaping-static-quadratic-out"></a>
##### `quadraticOut`

*static*

```ts
static quadraticOut(t: number, c: number = 1): number
```

Quadratic out, adapted from Robert Penner's [easing functions](http://robertpenner.com/easing/).

**Parameters**

- `t` (`number`) — a value between 0 to 1
- `c` (`number`; default `1`) — the value to shape, default is 1

<a id="num-shaping-static-quadratic-target"></a>
##### `quadraticTarget`

*static*

```ts
static quadraticTarget(t: number, c: number = 1, p1: PtLike = ...): number
```

Give a Pt, draw a quadratic curve that will pass through that Pt as closely as possible. Adapted from Golan Levin's [shaping functions](http://www.flong.com/texts/code/shapers_poly/).

**Parameters**

- `t` (`number`) — a value between 0 to 1
- `c` (`number`; default `1`) — the value to shape, default is 1
- `p1` (`PtLike`; default `...`) — ` a Pt object specifying the Pt to pass through. Default is `Pt(0.2, 0.35)

<a id="num-shaping-static-seat"></a>
##### `seat`

*static*

```ts
static seat(t: number, c: number = 1, p: number = 0.5): number
```

Exponential seat curve, adapted from Golan Levin's [shaping functions](http://www.flong.com/texts/code/shapers_exp/).

**Parameters**

- `t` (`number`) — a value between 0 to 1
- `c` (`number`; default `1`) — the value to shape, default is 1
- `p` (`number`; default `0.5`) — a parameter between 0 to 1 to control the steepness of the curve. Higher is steeper. Default is 0.5.

<a id="num-shaping-static-sigmoid"></a>
##### `sigmoid`

*static*

```ts
static sigmoid(t: number, c: number = 1, p: number = 10): number
```

Sigmoid curve changes its shape adapted from the input value, but always returns a value between 0 to 1.

**Parameters**

- `t` (`number`) — a value between 0 to 1
- `c` (`number`; default `1`) — the value to shape, default is 1
- `p` (`number`; default `10`) — the larger the value, the "steeper" the curve will be. Default is 10.

<a id="num-shaping-static-sine-in"></a>
##### `sineIn`

*static*

```ts
static sineIn(t: number, c: number = 1): number
```

Sinuous in, adapted from Robert Penner's [easing functions](http://robertpenner.com/easing/).

**Parameters**

- `t` (`number`) — a value between 0 to 1
- `c` (`number`; default `1`) — the value to shape, default is 1

<a id="num-shaping-static-sine-in-out"></a>
##### `sineInOut`

*static*

```ts
static sineInOut(t: number, c: number = 1): number
```

Sinuous in-out, adapted from Robert Penner's [easing functions](http://robertpenner.com/easing/).

**Parameters**

- `t` (`number`) — a value between 0 to 1
- `c` (`number`; default `1`) — the value to shape, default is 1

<a id="num-shaping-static-sine-out"></a>
##### `sineOut`

*static*

```ts
static sineOut(t: number, c: number = 1): number
```

Sinuous out, adapted from Robert Penner's [easing functions](http://robertpenner.com/easing/).

**Parameters**

- `t` (`number`) — a value between 0 to 1
- `c` (`number`; default `1`) — the value to shape, default is 1

<a id="num-shaping-static-step"></a>
##### `step`

*static*

```ts
static step(fn:  Fn(t:number, c:number, args:any[]), steps: number, t: number, c: number, args: any[]): number
```

Convert any shaping functions into a series of steps.

**Parameters**

- `fn` (` Fn(t:number, c:number, args:any[])`) — the original shaping function
- `steps` (`number`) — the number of steps
- `t` (`number`) — a value between 0 to 1
- `c` (`number`) — the value to shape, default is 1
- `args` (`any[]`) — optional paramters to pass to original function

<a id="module-op"></a>
## Module: `Op`

<a id="op-circle"></a>
### `Circle`

**Kind:** Class · **Source:** [`src/Op.ts:684`](https://github.com/williamngan/pts/blob/master/src/Op.ts#L684)

Circle class provides static functions to create and operate on circles. A circle is usually represented as a Group of 2 Pts, where the first Pt specifies the center, and the second Pt specifies the radius.
To move a circle without changing its radius, move only its center, eg `circle[0].to(20, 20)`. Group transforms such as `circle.moveTo(20, 20)` affect both Pts, including the radius.
You can use the static functions as-is, or apply the [`Group.op`](#pt-group-op) or [`Pt.op`](#pt-pt-op) to enable functional programming.
See [Op guide](https://ptsjs.org/guide/Op-0400.html) for details.

#### Methods

<a id="op-circle-static-from-center"></a>
##### `fromCenter`

*static*

```ts
static fromCenter(pt: PtLike, radius: number): Group
```

Create a circle based on a center point and a radius.

**Parameters**

- `pt` (`PtLike`) — center point of circle
- `radius` (`number`) — radius of circle

**Returns:** a Group that represents a circle

<a id="op-circle-static-from-rect"></a>
##### `fromRect`

*static*

```ts
static fromRect(pts: PtLikeIterable, enclose: boolean = false): Group
```

Create a circle that either fits within, or encloses, a rectangle.

**Parameters**

- `pts` (`PtLikeIterable`) — a Group or an Iterable<PtLike> with 2 Pt representing a rectangle
- `enclose` (`boolean`; default `false`) — if `true`, the circle will enclose the rectangle. Default is `false`, which will fit the circle inside the rectangle.

**Returns:** a Group that represents a circle

<a id="op-circle-static-from-triangle"></a>
##### `fromTriangle`

*static*

```ts
static fromTriangle(pts: PtIterable, enclose: boolean = false): Group | undefined
```

Create a circle that either fits within, or encloses, a triangle. Same as [`Triangle.circumcircle`](#op-triangle-static-circumcircle) or [`Triangle.incircle`](#op-triangle-static-incircle).

**Parameters**

- `pts` (`PtIterable`) — a Group or an Iterable<Pt> with 3 Pt representing a rectangle
- `enclose` (`boolean`; default `false`) — if `true`, the circle will enclose the triangle. Default is `false`, which will fit the circle inside the triangle.

**Returns:** a Group that represents a circle

<a id="op-circle-static-intersect-circle2-d"></a>
##### `intersectCircle2D`

*static*

```ts
static intersectCircle2D(circle1: PtIterable, circle2: PtIterable): Group
```

Get the intersection points between two circles.

**Parameters**

- `circle1` (`PtIterable`) — a Group or an Iterable<Pt> with 2 Pt representing a circle
- `circle2` (`PtIterable`) — a Group or an Iterable<Pt> with 2 Pt representing a circle

**Returns:** a Group of intersection points, or an empty Group if no intersection is found

<a id="op-circle-static-intersect-line2-d"></a>
##### `intersectLine2D`

*static*

```ts
static intersectLine2D(circle: PtIterable, line: PtIterable): Group
```

Get the intersection points between a circle and a line segment.

**Parameters**

- `circle` (`PtIterable`) — a Group or an Iterable<Pt> with Pt representing a circle
- `line` (`PtIterable`) — a Group or an Iterable<Pt> with 2 Pt representing a line

**Returns:** a Group of intersection points, or an empty Group if no intersection is found

<a id="op-circle-static-intersect-ray2-d"></a>
##### `intersectRay2D`

*static*

```ts
static intersectRay2D(circle: PtIterable, ray: PtIterable): Group
```

Get the intersection points between a circle and a ray (infinite line).

**Parameters**

- `circle` (`PtIterable`) — a Group or an Iterable<Pt> with 2 Pt representing a circle
- `ray` (`PtIterable`) — a Group or an Iterable<Pt> with 2 Pt representing a ray

**Returns:** a Group of intersection points, or an empty Group if no intersection is found

<a id="op-circle-static-intersect-rect2-d"></a>
##### `intersectRect2D`

*static*

```ts
static intersectRect2D(circle: PtIterable, rect: PtIterable): Group
```

Quick way to check rectangle intersection with a circle.
For more optimized implementation, store the rectangle's sides separately (eg, [`Rectangle.sides`](#op-rectangle-static-sides)) and use [`Polygon.intersectPolygon2D()`](#op-polygon-static-intersect-polygon2-d).

**Parameters**

- `circle` (`PtIterable`) — a Group or an Iterable<Pt> with 2 Pt representing a circle
- `rect` (`PtIterable`) — a Group or an Iterable<Pt> with 2 Pt representing a rectangle

**Returns:** a Group of intersection points, or an empty Group if no intersection is found

<a id="op-circle-static-to-rect"></a>
##### `toRect`

*static*

```ts
static toRect(circle: PtIterable, within: boolean = false): Group
```

Get a rectangle that either fits within or encloses this circle. See also [`Rectangle.toCircle`](#op-rectangle-static-to-circle)

**Parameters**

- `circle` (`PtIterable`) — a Group or an Iterable<Pt> with 2 Pt representing a circle
- `within` (`boolean`; default `false`) — if `true`, the rectangle will be within the circle. If `false`, the rectangle will enclose the circle.

**Returns:** a Group representing a rectangle

<a id="op-circle-static-to-triangle"></a>
##### `toTriangle`

*static*

```ts
static toTriangle(circle: PtIterable, within: boolean = true): Group
```

Get a triangle that fits within this circle.

**Parameters**

- `circle` (`PtIterable`) — a Group or an Iterable<Pt> with 2 Pt representing a circle
- `within` (`boolean`; default `true`) — if `true`, the triangle will be within the circle. If `false`, the triangle will enclose the circle.

<a id="op-circle-static-within-bound"></a>
##### `withinBound`

*static*

```ts
static withinBound(pts: PtIterable, pt: PtLike, threshold: number = 0): boolean
```

Check if a point is within a circle.

**Parameters**

- `pts` (`PtIterable`) — a Group or an Iterable<Pt> with 2 Pt representing a circle
- `pt` (`PtLike`) — the point to checks
- `threshold` (`number`; default `0`) — an optional small number to set threshold. Default is 0.

<a id="op-curve"></a>
### `Curve`

**Kind:** Class · **Source:** [`src/Op.ts:1823`](https://github.com/williamngan/pts/blob/master/src/Op.ts#L1823)

Curve class provides static functions to interpolate curves. A curve is usually represented as a Group of 3 or more control points.
You can use the static functions as-is, or apply the [`Group.op`](#pt-group-op) or [`Pt.op`](#pt-pt-op) to enable functional programming.
See [Op guide](https://ptsjs.org/guide/Op-0400.html) for details.

#### Methods

<a id="op-curve-static-bezier"></a>
##### `bezier`

*static*

```ts
static bezier(pts: GroupLike, steps: number = 10): Group
```

Create a Bezier curve. In a cubic bezier curve, the first and 4th anchors are end-points, and 2nd and 3rd anchors are control-points.

**Parameters**

- `pts` (`GroupLike`) — a group of anchor Pt
- `steps` (`number`; default `10`) — the number of line segments per curve. Defaults to 10 steps.

**Returns:** a curve as a group of interpolated Pt

<a id="op-curve-static-bezier-step"></a>
##### `bezierStep`

*static*

```ts
static bezierStep(step: Pt, ctrls: GroupLike): Pt
```

Interpolate to get a point on a cubic Bezier curve.

**Parameters**

- `step` (`Pt`) — the coefficients [t*t*t, t*t, t, 1]
- `ctrls` (`GroupLike`) — a group of anchor Pts

**Returns:** an interpolated Pt on the curve

<a id="op-curve-static-bezier-to-bspline"></a>
##### `bezierToBspline`

*static*

```ts
static bezierToBspline(pts: PtLikeIterable): Group
```

Convert a chain of cubic Bezier curves into the anchors of a B-spline curve: the inverse of [`Curve.bsplineToBezier`](#op-curve-static-bspline-to-bezier) at its default tension.
A B-spline does not pass through its anchors, so they are solved for: the result is the B-spline that passes through
every Bezier anchor and starts and ends along the Bezier's end handles (a tridiagonal system, solved in linear time).
For a chain that `bsplineToBezier` produced at tension 1 this recovers its anchors up to float32 rounding; for any other chain the B-spline keeps
the anchors and the end tangents, and its interior, being smooth to the second derivative, can only approximate the other handles.

**Parameters**

- `pts` (`PtLikeIterable`) — a Group or an Iterable<PtLike> in the layout of [`Curve.bezier`](#op-curve-static-bezier); an incomplete trailing segment is ignored

**Returns:** a Group of `m+3` anchors for `m` Bezier segments, for [`Curve.bspline`](#op-curve-static-bspline) or [`Curve.bsplineToBezier`](#op-curve-static-bspline-to-bezier)

**Example**

```ts
Curve.bspline( Curve.bezierToBspline( chain ) )
```

<a id="op-curve-static-bezier-to-cardinal"></a>
##### `bezierToCardinal`

*static*

```ts
static bezierToCardinal(pts: PtLikeIterable): Group
```

Convert a chain of cubic Bezier curves into the anchors of a Cardinal curve: the inverse of [`Curve.cardinalToBezier`](#op-curve-static-cardinal-to-bezier).
A Cardinal curve's tangents come from its neighboring anchors, so this keeps every Bezier anchor and drops the Bezier handles.
The Cardinal curve still passes through the same anchors; between them it follows the handles only when they were
in Cardinal form to begin with and the original tension and alpha are reused. Coordinates are rounded to float32.

**Parameters**

- `pts` (`PtLikeIterable`) — a Group or an Iterable<PtLike> in the layout of [`Curve.bezier`](#op-curve-static-bezier); an incomplete trailing segment is ignored

**Returns:** a Group of anchors for [`Curve.cardinal`](#op-curve-static-cardinal) or [`Curve.cardinalToBezier`](#op-curve-static-cardinal-to-bezier), with the tension and alpha of your choice

**Example**

```ts
Curve.cardinal( Curve.bezierToCardinal( chain ), 10, 0.5 )
```

<a id="op-curve-static-bspline"></a>
##### `bspline`

*static*

```ts
static bspline(pts: GroupLike, steps: number = 10, tension: number = 1): Group
```

Create a basis spline (NURBS) curve.

**Parameters**

- `pts` (`GroupLike`) — a group of anchor Pt
- `steps` (`number`; default `10`) — the number of line segments per curve. Defaults to 10 steps.
- `tension` (`number`; default `1`) — optional value between 0 to n to specify a "tension". Default is 1 which is the usual tension.

**Returns:** a curve as a group of interpolated Pt

<a id="op-curve-static-bspline-step"></a>
##### `bsplineStep`

*static*

```ts
static bsplineStep(step: Pt, ctrls: GroupLike): Pt
```

Interpolate to get a point on a basis spline curve.

**Parameters**

- `step` (`Pt`) — the coefficients [t*t*t, t*t, t, 1]
- `ctrls` (`GroupLike`) — a group of anchor Pts

**Returns:** an interpolated Pt on the curve

<a id="op-curve-static-bspline-tension-step"></a>
##### `bsplineTensionStep`

*static*

```ts
static bsplineTensionStep(step: Pt, ctrls: GroupLike, tension: number = 1): Pt
```

Interpolate to get a point on a basis spline curve with tension.

**Parameters**

- `step` (`Pt`) — the coefficients [t*t*t, t*t, t, 1]
- `ctrls` (`GroupLike`) — a group of anchor Pts
- `tension` (`number`; default `1`) — optional value between 0 to n to specify a "tension". Default to 1 which is the usual tension.

**Returns:** an interpolated Pt on the curve

<a id="op-curve-static-bspline-to-bezier"></a>
##### `bsplineToBezier`

*static*

```ts
static bsplineToBezier(pts: PtLikeIterable, tension: number = 1): Group
```

Convert the anchors of a B-spline curve into cubic Bezier control points, so the same curve can be drawn as a native path
with [`CanvasForm.bezier`](#canvas-canvasform-bezier) or sampled with [`Curve.bezier`](#op-curve-static-bezier).
The Bezier traces the curve that [`Curve.bspline`](#op-curve-static-bspline) approximates with line segments,
subject to the float32 rounding of a Pt. See a [demo here](https://ptsjs.org/demo/?name=curve.bspline).

**Parameters**

- `pts` (`PtLikeIterable`) — a Group or an Iterable<PtLike> of at least 4 anchor points
- `tension` (`number`; default `1`) — optional value between 0 to n to specify a "tension". Default is 1 which is the usual tension.

**Returns:** a Group of `3(n-3)+1` Pts in the layout that [`Curve.bezier`](#op-curve-static-bezier) takes

**Example**

```ts
form.bezier( Curve.bsplineToBezier( pts ) )
```

<a id="op-curve-static-cardinal"></a>
##### `cardinal`

*static*

```ts
static cardinal(pts: PtLikeIterable, steps: number = 10, tension: number = 0.5): Group
```

Create a Cardinal curve.

**Parameters**

- `pts` (`PtLikeIterable`) — a Group or an Iterable<PtLike>
- `steps` (`number`; default `10`) — the number of line segments per curve. Defaults to 10 steps.
- `tension` (`number`; default `0.5`) — optional value between 0 to 1 to specify a "tension". Default to 0.5 which is the tension for Catmull-Rom curve.

**Returns:** a curve as a group of interpolated Pt

<a id="op-curve-static-cardinal-step"></a>
##### `cardinalStep`

*static*

```ts
static cardinalStep(step: Pt, ctrls: GroupLike, tension: number = 0.5): Pt
```

Interpolate to get a point on Cardinal curve.

**Parameters**

- `step` (`Pt`) — the coefficients [t*t*t, t*t, t, 1]
- `ctrls` (`GroupLike`) — a group of anchor Pts
- `tension` (`number`; default `0.5`) — optional value between 0 to 1 to specify a "tension". Default to 0.5 which is the tension for Catmull-Rom curve

**Returns:** an interpolated Pt on the curve

<a id="op-curve-static-cardinal-to-bezier"></a>
##### `cardinalToBezier`

*static*

```ts
static cardinalToBezier(pts: PtLikeIterable, tension: number = 0.5, alpha: number = 0): Group
```

Convert the anchors of a Cardinal curve into cubic Bezier control points, so the same curve can be drawn as a native path
with [`CanvasForm.bezier`](#canvas-canvasform-bezier) or sampled with [`Curve.bezier`](#op-curve-static-bezier).
With the default `alpha`, the Bezier traces the curve that [`Curve.cardinal`](#op-curve-static-cardinal) approximates with line segments,
subject to the float32 rounding of a Pt.
See a [demo here](https://ptsjs.org/demo/?name=curve.cardinal).

Set `alpha` to 0.5 for centripetal or to 1 for chordal parameterization. At the default tension of 0.5,
centripetal Catmull-Rom segments with distinct adjacent anchors have no internal loops or cusps
(Yuksel, Schaefer and Keyser, 2011); changing tension can introduce them.
For non-uniform curves, coincident consecutive anchors give a constant segment and zero tangents at its ends.

**Parameters**

- `pts` (`PtLikeIterable`) — a Group or an Iterable<PtLike> of anchor points
- `tension` (`number`; default `0.5`) — optional value between 0 to 1 to specify a "tension". Default to 0.5 which is the tension for Catmull-Rom curve.
- `alpha` (`number`; default `0`) — optional knot parameterization: 0 (default) is uniform, 0.5 is centripetal, 1 is chordal

**Returns:** a Group of `3(n-1)+1` Pts in the layout that [`Curve.bezier`](#op-curve-static-bezier) takes: each anchor is followed by the 2 control points of the segment that starts there

**Example**

```ts
form.bezier( Curve.cardinalToBezier( pts ) )
```

<a id="op-curve-static-catmull-rom"></a>
##### `catmullRom`

*static*

```ts
static catmullRom(pts: PtLikeIterable, steps: number = 10): Group
```

Create a Catmull-Rom curve. Catmull-Rom is a kind of smooth-looking Cardinal curve.

**Parameters**

- `pts` (`PtLikeIterable`) — a Group or an Iterable<PtLike>
- `steps` (`number`; default `10`) — the number of line segments per curve. Defaults to 10 steps

**Returns:** a curve as a group of interpolated Pt

<a id="op-curve-static-catmull-rom-step"></a>
##### `catmullRomStep`

*static*

```ts
static catmullRomStep(step: Pt, ctrls: GroupLike): Pt
```

Interpolate to get a point on Catmull-Rom curve.

**Parameters**

- `step` (`Pt`) — the coefficients [t*t*t, t*t, t, 1]
- `ctrls` (`GroupLike`) — a group of anchor Pts

**Returns:** an interpolated Pt on the curve

<a id="op-curve-static-control-points"></a>
##### `controlPoints`

*static*

```ts
static controlPoints(pts: PtLikeIterable, index: number = 0, copyStart: boolean = false): Group
```

Given an index for the starting position in a Pt group, get the control and/or end points of a curve segment.

**Parameters**

- `pts` (`PtLikeIterable`) — a Group or an Iterable<PtLike>
- `index` (`number`; default `0`) — start index in `pts` array. Default is 0.
- `copyStart` (`boolean`; default `false`) — an optional boolean value to indicate if the start index should be used twice. Default is false.

**Returns:** a group of 4 Pts

<a id="op-curve-static-get-steps"></a>
##### `getSteps`

*static*

```ts
static getSteps(steps: number): Group
```

Get a precalculated coefficients per step.

**Parameters**

- `steps` (`number`) — number of steps

<a id="op-line"></a>
### `Line`

**Kind:** Class · **Source:** [`src/Op.ts:27`](https://github.com/williamngan/pts/blob/master/src/Op.ts#L27)

Line class provides static functions to create and operate on lines. A line is usually represented as a Group of 2 Pts.
You can use the static functions as-is, or apply the [`Group.op`](#pt-group-op) or [`Pt.op`](#pt-pt-op) to enable functional programming.
See [Op guide](https://ptsjs.org/guide/Op-0400.html) for details.

#### Methods

<a id="op-line-static-collinear"></a>
##### `collinear`

*static*

```ts
static collinear(p1: PtLike, p2: PtLike, p3: PtLike, threshold: number = 0.01): boolean
```

Check if three Pts are collinear, ie, on the same straight path.

**Parameters**

- `p1` (`PtLike`) — first Pt
- `p2` (`PtLike`) — second Pt
- `p3` (`PtLike`) — third Pt
- `threshold` (`number`; default `0.01`) — a threshold where a smaller value means higher precision threshold for the straight line. Default is 0.01.

<a id="op-line-static-crop"></a>
##### `crop`

*static*

```ts
static crop(line: PtIterable, size: PtLike, index: number = 0, cropAsCircle: boolean = true): Pt | undefined
```

Crop this line by a circle or rectangle at end points. This can be useful for creating arrows that connect to an object's edge.

**Parameters**

- `line` (`PtIterable`) — a Group or an Iterable<Pt> representing a line to crop
- `size` (`PtLike`) — size of circle or rectangle as Pt
- `index` (`number`; default `0`) — line's end point index, ie, 0 = start and 1 = end.
- `cropAsCircle` (`boolean`; default `true`) — a boolean to specify whether the `size` parameter should be treated as circle. Default is `true`.

**Returns:** an intersecting point on the line that can be used for cropping.

<a id="op-line-static-distance-from-pt"></a>
##### `distanceFromPt`

*static*

```ts
static distanceFromPt(line: GroupLike, pt: PtLike): number
```

Given a line and a point, find the shortest distance from the point to the line.

**Parameters**

- `line` (`GroupLike`) — a Group of 2 Pts
- `pt` (`PtLike`) — a Pt

**See also:** `Line.perpendicularFromPt`

<a id="op-line-static-from-angle"></a>
##### `fromAngle`

*static*

```ts
static fromAngle(anchor: PtLike, angle: number, magnitude: number): Group
```

Create a line that originates from an anchor point, given an angle and a magnitude.

**Parameters**

- `anchor` (`PtLike`) — an anchor Pt
- `angle` (`number`) — an angle in radian
- `magnitude` (`number`) — magnitude of the line

**Returns:** a Group of 2 Pts representing a line segement

<a id="op-line-static-intercept"></a>
##### `intercept`

*static*

```ts
static intercept(p1: PtLike, p2: PtLike): { slope:number, xi:number | undefined, yi:number } | undefined
```

Calculate the slope and xy intercepts of a line.

**Parameters**

- `p1` (`PtLike`) — line's first end point
- `p2` (`PtLike`) — line's second end point

**Returns:** an object with `slope`, `xi`, `yi` properties

<a id="op-line-static-intersect-grid-with-line2-d"></a>
##### `intersectGridWithLine2D`

*static*

```ts
static intersectGridWithLine2D(line: GroupLike, gridPt: PtLike): Group
```

Get two intersection Pts of a line segment with a 2D grid point.

**Parameters**

- `line` (`GroupLike`) — a ray specified by 2 Pts
- `gridPt` (`PtLike`) — a Pt on the grid

**Returns:** a group of two intersecting Pts. The first one is horizontal intersection and the second one is vertical intersection.

<a id="op-line-static-intersect-grid-with-ray2-d"></a>
##### `intersectGridWithRay2D`

*static*

```ts
static intersectGridWithRay2D(ray: PtIterable, gridPt: PtLike): Group
```

Get two points of a ray that intersects with a point on a 2D grid.

**Parameters**

- `ray` (`PtIterable`) — a Group or an Iterable<Pt> representing a ray
- `gridPt` (`PtLike`) — a Pt on the grid

**Returns:** a group of two intersecting Pts. The first one is horizontal intersection and the second one is vertical intersection.

<a id="op-line-static-intersect-line2-d"></a>
##### `intersectLine2D`

*static*

```ts
static intersectLine2D(la: PtIterable, lb: PtIterable): Pt | undefined
```

Given two line segemnts, find their intersection point if any.

**Parameters**

- `la` (`PtIterable`) — a Group or an Iterable<Pt> with 2 Pt representing a line segment
- `lb` (`PtIterable`) — a Group or an Iterable<Pt> with 2 Pt representing a line segment

**Returns:** an intersection Pt or undefined if no intersection

<a id="op-line-static-intersect-lines2-d"></a>
##### `intersectLines2D`

*static*

```ts
static intersectLines2D(lines1: Iterable, lines2: Iterable, isRay: boolean = false): Group
```

Find intersection points of 2 sets of lines. This checks all line segments in the two lists. Consider using a bounding-box check before calling this. If you are checking convex polygon intersections, using [`Polygon.intersectPolygon2D`](#op-polygon-static-intersect-polygon2-d) will be more efficient.

**Parameters**

- `lines1` (`Iterable`) — an Array/Iterable of (Groups or Iterables<Pt>)
- `lines2` (`Iterable`) — an Array/Iterable of (Groups or Iterables<Pt>)
- `isRay` (`boolean`; default `false`) — a boolean value to treat the line as a ray (infinite line). Default is `false`.

<a id="op-line-static-intersect-line-with-ray2-d"></a>
##### `intersectLineWithRay2D`

*static*

```ts
static intersectLineWithRay2D(line: PtIterable, ray: PtIterable): Pt | undefined
```

Given a line segemnt and a ray (infinite line), find their intersection point if any.

**Parameters**

- `line` (`PtIterable`) — a Group of 2 Pts representing a line segment
- `ray` (`PtIterable`) — a Group of 2 Pts representing a ray

**Returns:** an intersection Pt or undefined if no intersection

<a id="op-line-static-intersect-polygon2-d"></a>
##### `intersectPolygon2D`

*static*

```ts
static intersectPolygon2D(lineOrRay: PtIterable, poly: PtIterable, sourceIsRay: boolean = false): Group | undefined
```

Given a line segemnt or a ray (infinite line), find its intersection point(s) with a polygon.

**Parameters**

- `lineOrRay` (`PtIterable`) — a Group or an Iterable<Pt> with 2 Pt representing a line or ray
- `poly` (`PtIterable`) — a Group or an Iterable<Pt> representing a polygon
- `sourceIsRay` (`boolean`; default `false`) — a boolean value to treat the line as a ray (infinite line). Default is `false`.

<a id="op-line-static-intersect-ray2-d"></a>
##### `intersectRay2D`

*static*

```ts
static intersectRay2D(la: PtIterable, lb: PtIterable): Pt | undefined
```

Given two lines as rays (infinite lines), find their intersection point if any.

**Parameters**

- `la` (`PtIterable`) — a Group or an Iterable<Pt> with 2 Pt representing a ray
- `lb` (`PtIterable`) — a Group or an Iterable<Pt> with 2 Pts representing another ray

**Returns:** an intersection Pt or undefined if no intersection

<a id="op-line-static-intersect-rect2-d"></a>
##### `intersectRect2D`

*static*

```ts
static intersectRect2D(line: GroupLike, rect: GroupLike): Group
```

An easy way to get rectangle-line intersection points. For more optimized implementation, store the rectangle's sides separately (eg, `Rectangle.sides()`) and use `Polygon.intersectPolygon2D()`.

**Parameters**

- `line` (`GroupLike`) — a Group representing a line
- `rect` (`GroupLike`) — a Group representing a rectangle

**Returns:** a Group of intersecting Pts

<a id="op-line-static-magnitude"></a>
##### `magnitude`

*static*

```ts
static magnitude(line: PtIterable): number
```

Get magnitude of a line segment.

**Parameters**

- `line` (`PtIterable`) — a Group or an Iterable<Pt> with at least 2 Pt

<a id="op-line-static-magnitude-sq"></a>
##### `magnitudeSq`

*static*

```ts
static magnitudeSq(line: PtIterable): number
```

Get squared magnitude of a line segment.

**Parameters**

- `line` (`PtIterable`) — a Group or an Iterable<Pt> with at least 2 Pt

<a id="op-line-static-marker"></a>
##### `marker`

*static*

```ts
static marker(line: PtIterable, size: PtLike, graphic: string = "arrow", atTail: boolean = true): Group
```

Create an marker arrow or line, placed at an end point of this line.

**Parameters**

- `line` (`PtIterable`) — a Group or an Iterable<Pt> representing a line to place marker
- `size` (`PtLike`) — size of the marker as Pt
- `graphic` (`string`; default `"arrow"`) — either "arrow" or "line"
- `atTail` (`boolean`; default `true`) — a boolean, if `true`, the marker will be positioned at tail of the line (ie, index = 1). Default is `true`.

**Returns:** a Group that defines the marker's shape

<a id="op-line-static-perpendicular-from-pt"></a>
##### `perpendicularFromPt`

*static*

```ts
static perpendicularFromPt(line: PtIterable, pt: PtLike, asProjection: boolean = false): Pt | undefined
```

Find a point on a line that is perpendicular (shortest distance) to a target point.

**Parameters**

- `line` (`PtIterable`) — a Group or an Iterable<Pt> that defines a line
- `pt` (`PtLike`) — a target Pt
- `asProjection` (`boolean`; default `false`) — if true, this returns the projection vector instead. Default is false.

**Returns:** a Pt on the line that is perpendicular to the target Pt, or a projection vector if `asProjection` is true.

<a id="op-line-static-side-of-pt2-d"></a>
##### `sideOfPt2D`

*static*

```ts
static sideOfPt2D(line: PtLikeIterable, pt: PtLike): number
```

Given a 2D path and a point, find whether the point is on left or right side of the line.

**Parameters**

- `line` (`PtLikeIterable`) — a Group or an Iterable<PtLike> representing a line
- `pt` (`PtLike`) — a Pt or numeric array

**Returns:** a negative value if on left and a positive value if on right. If collinear, then the return value is 0.

<a id="op-line-static-slope"></a>
##### `slope`

*static*

```ts
static slope(p1: PtLike, p2: PtLike): number | undefined
```

Calculate the slope of a line.

**Parameters**

- `p1` (`PtLike`) — line's first end point
- `p2` (`PtLike`) — line's second end point

<a id="op-line-static-subpoints"></a>
##### `subpoints`

*static*

```ts
static subpoints(line: PtLikeIterable, num: number): Group
```

Get evenly distributed points on a line. Similar to [`Create.distributeLinear`](#create-create-static-distribute-linear) but excluding end points.

**Parameters**

- `line` (`PtLikeIterable`) — a Group or an Iterable<PtLike> representing a line
- `num` (`number`) — number of points to get

<a id="op-line-static-to-rect"></a>
##### `toRect`

*static*

```ts
static toRect(line: GroupLike): Group
```

Convert this line to a new rectangle representation.

**Parameters**

- `line` (`GroupLike`) — a Group representing a line

<a id="op-path"></a>
### `Path`

**Kind:** Class · **Source:** [`src/Op.ts:1743`](https://github.com/williamngan/pts/blob/master/src/Op.ts#L1743)

Path class provides static functions to combine polygons with boolean operations:
unite, intersect, exclude, subtract the shapes in front or behind, divide into faces, or crop by the top shape.
Shapes are listed in stacking order, the first at the back and the last in front, like the order you would draw them in.
A shape is a polygon (a Group, or any iterable of points), or a list of rings that together form a polygon with holes,
such as the result of another Path function. Every result is such a list of rings: an outer ring followed by its
holes, in opposite orientations, which [`CanvasForm.compound`](#canvas-canvasform-compound) draws as one path. Rings are open (the first point
is not repeated), 2D, and never share Pts with the input. Clockwise and counterclockwise rings are the same shape, and
a self-intersecting ring covers what `form.polygon` would fill (the nonzero rule). Input vertices closer together than a
millionth of the largest absolute coordinate are merged before finding intersections. For small shapes at large offsets,
work in local coordinates to avoid losing detail to this tolerance or the Float32 output.
See [Op guide](https://ptsjs.org/guide/Op-0400.html) for details.

#### Methods

<a id="op-path-static-crop"></a>
##### `crop`

*static*

```ts
static crop(shapes: PtLikeIterable | Iterable): Group[][]
```

Crop: use the frontmost (last) shape as a mask, keeping the faces of the other shapes inside it and deleting the mask itself.
Like [`Path.divide`](#op-path-static-divide), the shapes under the mask stay divided where they overlap.
See a [demo here](https://ptsjs.org/demo/?name=path.crop).

**Parameters**

- `shapes` (`PtLikeIterable | Iterable`) — an Array/Iterable of polygons in stacking order, back to front. Each is a Group or an Iterable<PtLike>, or a list of rings for a polygon with holes. A single ring is taken as one shape.

**Returns:** an array of polygons, one per face inside the mask, each an outer ring followed by its holes

**Example**

```ts
Path.crop( [photo, frame] )
```

<a id="op-path-static-divide"></a>
##### `divide`

*static*

```ts
static divide(shapes: PtLikeIterable | Iterable): Group[][]
```

Divide: split the shapes at every crossing into separate faces. Each face is the largest area not cut by any edge, so
a region inside two shapes is its own face, and a self-overlapping region of one shape is too.

**Parameters**

- `shapes` (`PtLikeIterable | Iterable`) — an Array/Iterable of polygons in stacking order, back to front. Each is a Group or an Iterable<PtLike>, or a list of rings for a polygon with holes. A single ring is taken as one shape.

**Returns:** an array of polygons, one per face, each an outer ring followed by its holes

**Example**

```ts
Path.divide( [a, b] ).forEach( (face, i) => form.fillOnly( colors[i] ).compound( face ) )
```

<a id="op-path-static-exclude"></a>
##### `exclude`

*static*

```ts
static exclude(shapes: PtLikeIterable | Iterable): Group[]
```

Exclude: keep the area inside an odd number of shapes, so where two shapes overlap becomes a hole.

**Parameters**

- `shapes` (`PtLikeIterable | Iterable`) — an Array/Iterable of polygons in stacking order, back to front. Each is a Group or an Iterable<PtLike>, or a list of rings for a polygon with holes. A single ring is taken as one shape.

**Returns:** the rings of the result: each outer ring followed by its holes; empty if the shapes cancel out

**Example**

```ts
Path.exclude( [a, b] )
```

<a id="op-path-static-intersect"></a>
##### `intersect`

*static*

```ts
static intersect(shapes: PtLikeIterable | Iterable): Group[]
```

Intersect: keep only the area inside every shape.

**Parameters**

- `shapes` (`PtLikeIterable | Iterable`) — an Array/Iterable of polygons in stacking order, back to front. Each is a Group or an Iterable<PtLike>, or a list of rings for a polygon with holes. A single ring is taken as one shape.

**Returns:** the rings of the common polygon: each outer ring followed by its holes; empty if the shapes do not all overlap

**Example**

```ts
Path.intersect( [a, b, c] )
```

<a id="op-path-static-minus-back"></a>
##### `minusBack`

*static*

```ts
static minusBack(shapes: PtLikeIterable | Iterable): Group[]
```

Minus Back: subtract every shape behind from the frontmost (last) shape.

**Parameters**

- `shapes` (`PtLikeIterable | Iterable`) — an Array/Iterable of polygons in stacking order, back to front. Each is a Group or an Iterable<PtLike>, or a list of rings for a polygon with holes. A single ring is taken as one shape.

**Returns:** the rings of what remains of the last shape: each outer ring followed by its holes; empty if nothing remains

**Example**

```ts
Path.minusBack( [wall, window] )` keeps the part of `window` not covered by `wall
```

<a id="op-path-static-minus-front"></a>
##### `minusFront`

*static*

```ts
static minusFront(shapes: PtLikeIterable | Iterable): Group[]
```

Minus Front: subtract every shape in front from the backmost (first) shape.

**Parameters**

- `shapes` (`PtLikeIterable | Iterable`) — an Array/Iterable of polygons in stacking order, back to front. Each is a Group or an Iterable<PtLike>, or a list of rings for a polygon with holes. A single ring is taken as one shape.

**Returns:** the rings of what remains of the first shape: each outer ring followed by its holes; empty if nothing remains

**Example**

```ts
Path.minusFront( [disc, hole] )` cuts `hole` out of `disc
```

<a id="op-path-static-unite"></a>
##### `unite`

*static*

```ts
static unite(shapes: PtLikeIterable | Iterable): Group[]
```

Unite: merge all shapes into one polygon (the area inside any shape).

**Parameters**

- `shapes` (`PtLikeIterable | Iterable`) — an Array/Iterable of polygons in stacking order, back to front. Each is a Group or an Iterable<PtLike>, or a list of rings for a polygon with holes. A single ring is taken as one shape.

**Returns:** the rings of the merged polygon: each outer ring followed by its holes; empty if the shapes have no area

**Example**

```ts
form.fillOnly("#f03").compound( Path.unite( [star, disc] ) )
```

<a id="op-polygon"></a>
### `Polygon`

**Kind:** Class · **Source:** [`src/Op.ts:1068`](https://github.com/williamngan/pts/blob/master/src/Op.ts#L1068)

Polygon class provides static functions to create and operate on polygons. A polygon is usually represented as a Group of 3 or more Pts.
You can use the static functions as-is, or apply the [`Group.op`](#pt-group-op) or [`Pt.op`](#pt-pt-op) to enable functional programming.
See [Op guide](https://ptsjs.org/guide/Op-0400.html) for details.

#### Methods

<a id="op-polygon-static-adjacent-sides"></a>
##### `adjacentSides`

*static*

```ts
static adjacentSides(poly: PtIterable, index: number, closePath: boolean = false): Group[]
```

Given a Pt in the polygon group, the adjacent sides are the two sides which the Pt touches.

**Parameters**

- `poly` (`PtIterable`) — a Group or an Iterable<Pt>
- `index` (`number`) — the target Pt
- `closePath` (`boolean`; default `false`) — a boolean to specify whether the polygon should be closed (ie, whether the final segment should be counted).

<a id="op-polygon-static-area"></a>
##### `area`

*static*

```ts
static area(pts: PtLikeIterable): number
```

Find the area of a simple (non-self-intersecting) polygon using the shoelace formula.

**Parameters**

- `pts` (`PtLikeIterable`) — a Group or an Iterable<PtLike> representing a polygon

<a id="op-polygon-static-bisector"></a>
##### `bisector`

*static*

```ts
static bisector(poly: PtIterable, index: number): Pt | undefined
```

Get a bisector which is a line that split between two sides of a polygon equally.

**Parameters**

- `poly` (`PtIterable`) — a Group or an Iterable<Pt>
- `index` (`number`) — the Pt in the polygon to bisect from

**Returns:** a bisector direction Pt, the average of the two adjacent sides' unit vectors (not itself normalized)

<a id="op-polygon-static-centroid"></a>
##### `centroid`

*static*

```ts
static centroid(pts: PtLikeIterable): Pt
```

Get the centroid of a polygon, which is the average of all its points.

**Parameters**

- `pts` (`PtLikeIterable`) — a Group or an Iterable<PtLike> representing a polygon

<a id="op-polygon-static-convex-hull"></a>
##### `convexHull`

*static*

```ts
static convexHull(pts: PtLikeIterable, sorted: boolean = false): Group
```

Get a convex hull of a set of points, using Melkman's algorithm. ([Reference](http://geomalgorithms.com/a12-_hull-3.html)).

**Parameters**

- `pts` (`PtLikeIterable`) — a Group or an Iterable<PtLike>
- `sorted` (`boolean`; default `false`) — a boolean value to indicate if the group is pre-sorted by x position. Default is false.

**Returns:** a group of Pt that defines the convex hull polygon

<a id="op-polygon-static-from-center"></a>
##### `fromCenter`

*static*

```ts
static fromCenter(center: PtLike, radius: number, sides: number): Group
```

Create a regular polygon.

**Parameters**

- `center` (`PtLike`) — The center position of the polygon
- `radius` (`number`) — The radius, ie, a length from the center position to one of the polygon's corners.
- `sides` (`number`) — Number of sides

<a id="op-polygon-static-has-intersect-circle"></a>
##### `hasIntersectCircle`

*static*

```ts
static hasIntersectCircle(poly: PtIterable, circle: PtIterable): IntersectContext | null
```

Check if a convex polygon and a circle has intersections using Separating Axis Theorem.

**Parameters**

- `poly` (`PtIterable`) — a Group or an Iterable<Pt> representing a convex polygon
- `circle` (`PtIterable`) — a Group or an Iterable<Pt> representing a circle

**Returns:** an `IntersectContext` object that stores the intersection info, or undefined if there's no intersection

<a id="op-polygon-static-has-intersect-point"></a>
##### `hasIntersectPoint`

*static*

```ts
static hasIntersectPoint(poly: PtLikeIterable, pt: PtLike): boolean
```

Check if a Pt is inside a convex polygon.

**Parameters**

- `poly` (`PtLikeIterable`) — a Group or an Iterable<PtLike> representing a convex polygon
- `pt` (`PtLike`) — the Pt to check

<a id="op-polygon-static-has-intersect-polygon"></a>
##### `hasIntersectPolygon`

*static*

```ts
static hasIntersectPolygon(poly1: PtIterable, poly2: PtIterable): IntersectContext | null
```

Check if two convex polygons have intersections using Separating Axis Theorem.

**Parameters**

- `poly1` (`PtIterable`) — a Group or an Iterable<Pt> representing a convex polygon
- `poly2` (`PtIterable`) — a Group or an Iterable<Pt> representing another convex polygon

**Returns:** an `IntersectContext` object that stores the intersection info, or undefined if there's no intersection

<a id="op-polygon-static-intersect-polygon2-d"></a>
##### `intersectPolygon2D`

*static*

```ts
static intersectPolygon2D(poly1: PtIterable, poly2: PtIterable): Group
```

Find intersection points of 2 polygons by checking every side of both polygons. Performance may be slow for complex polygons.

**Parameters**

- `poly1` (`PtIterable`) — a Group or an Iterable<Pt> representing a polygon
- `poly2` (`PtIterable`) — a Group or an Iterable<Pt> representing another polygon

<a id="op-polygon-static-line-at"></a>
##### `lineAt`

*static*

```ts
static lineAt(pts: PtLikeIterable, index: number): Group
```

Given a polygon, get one edge using an index.

**Parameters**

- `pts` (`PtLikeIterable`) — a Group or an Iterable<PtLike> representing a polygon
- `index` (`number`) — index of a Pt in the Group

<a id="op-polygon-static-lines"></a>
##### `lines`

*static*

```ts
static lines(poly: PtIterable, closePath: boolean = true): Group[]
```

Get the line segments in this polygon.

**Parameters**

- `poly` (`PtIterable`) — a Group or an Iterable<Pt>
- `closePath` (`boolean`; default `true`) — a boolean to specify whether the polygon should be closed (ie, whether the final segment should be counted).

**Returns:** an array of Groups which has 2 Pts in each group

<a id="op-polygon-static-midpoints"></a>
##### `midpoints`

*static*

```ts
static midpoints(poly: PtIterable, closePath: boolean = false, t: number = 0.5): Group
```

Get a new polygon group that is derived from midpoints in this polygon.

**Parameters**

- `poly` (`PtIterable`) — a Group or an Iterable<Pt>
- `closePath` (`boolean`; default `false`) — a boolean to specify whether the polygon should be closed (ie, whether the final segment should be counted).
- `t` (`number`; default `0.5`) — a value between 0 to 1 for interpolation. Default to 0.5 which will get the middle point.

<a id="op-polygon-static-nearest-pt"></a>
##### `nearestPt`

*static*

```ts
static nearestPt(poly: PtIterable, pt: PtLike): number
```

Given a target Pt, find a Pt in the polygon's corners that's nearest to it.

**Parameters**

- `poly` (`PtIterable`) — a Group or an Iterable<Pt>
- `pt` (`PtLike`) — Pt to check

**Returns:** an index in the pts indicating the nearest Pt, or -1 if none found

<a id="op-polygon-static-network"></a>
##### `network`

*static*

```ts
static network(poly: PtIterable, originIndex: number = 0): Group[]
```

Given a point in the polygon as an origin, get an array of lines that connect all the remaining points to the origin point.

**Parameters**

- `poly` (`PtIterable`) — a Group or an Iterable<Pt> representing a polygon
- `originIndex` (`number`; default `0`) — the origin point's index in the polygon

**Returns:** an array of Groups of line segments

<a id="op-polygon-static-perimeter"></a>
##### `perimeter`

*static*

```ts
static perimeter(poly: PtIterable, closePath: boolean = false): { segments:Pt, total:number }
```

Find the perimeter of this polygon, ie, the lengths of its sides.

**Parameters**

- `poly` (`PtIterable`) — a Group or an Iterable<Pt>
- `closePath` (`boolean`; default `false`) — a boolean to specify whether the polygon should be closed (ie, whether the final segment should be counted).

**Returns:** an object with `total` length, and `segments` which is a Pt that stores each segment's length

<a id="op-polygon-static-project-axis"></a>
##### `projectAxis`

*static*

```ts
static projectAxis(poly: PtIterable, unitAxis: Pt): Pt
```

Project axis (eg, for use in Separation Axis Theorem).

**Parameters**

- `poly` (`PtIterable`) — a Group or an Iterable<Pt>
- `unitAxis` (`Pt`) — unit axis for calculating dot product

<a id="op-polygon-static-rectangle"></a>
##### `rectangle`

*static*

```ts
static rectangle(center: PtLike, widthOrSize: number | PtLike, height: number): Group
```

Create a rectangular polygon. Same as creating a Rectangle and then getting its corners via [`Rectangle.corners`](#op-rectangle-static-corners).

**Parameters**

- `center` (`PtLike`) — center point of the rectangle
- `widthOrSize` (`number | PtLike`) — width as number, or a Pt representing the size of the rectangle
- `height` (`number`) — optional height

<a id="op-polygon-static-to-rects"></a>
##### `toRects`

*static*

```ts
static toRects(polys: Iterable): Group[]
```

Get a bounding box for each polygon group, as well as a union bounding-box for all groups.

**Parameters**

- `polys` (`Iterable`) — an Array/Iterable of (Groups or Iterables<Pt>)

<a id="op-rectangle"></a>
### `Rectangle`

**Kind:** Class · **Source:** [`src/Op.ts:425`](https://github.com/williamngan/pts/blob/master/src/Op.ts#L425)

Rectangle class provides static functions to create and operate on rectangles. A rectangle is usually represented as a Group of 2 Pts, marking the top-left and bottom-right corners of the rectangle.
You can use the static functions as-is, or apply the [`Group.op`](#pt-group-op) or [`Pt.op`](#pt-pt-op) to enable functional programming.
See [Op guide](https://ptsjs.org/guide/Op-0400.html) for details.

#### Methods

<a id="op-rectangle-static-bounding-box"></a>
##### `boundingBox`

*static*

```ts
static boundingBox(rects: Iterable): Group
```

Given an array of rectangles, get a rectangle that bounds all of them.

**Parameters**

- `rects` (`Iterable`) — an array of (Groups or Iterables<PtLike>) that represents a set of rectangles

**Returns:** the bounding rectangle as a Group

<a id="op-rectangle-static-center"></a>
##### `center`

*static*

```ts
static center(pts: PtIterable): Pt
```

Get the center of this rectangle.

**Parameters**

- `pts` (`PtIterable`) — a Group or an Iterable<Pt> with 2 Pt representing a Rectangle

<a id="op-rectangle-static-corners"></a>
##### `corners`

*static*

```ts
static corners(rect: PtIterable): Group
```

Get the 4 corners of this rectangle as a Group.

**Parameters**

- `rect` (`PtIterable`) — a Group or an Iterable<Pt> with 2 Pt representing a Rectangle

<a id="op-rectangle-static-from"></a>
##### `from`

*static*

```ts
static from(topLeft: PtLike, widthOrSize: number | PtLike, height: number): Group
```

Create a rectangle from top-left anchor point. Same as [`Rectangle.fromTopLeft`](#op-rectangle-static-from-top-left).

**Parameters**

- `topLeft` (`PtLike`) — top-left point
- `widthOrSize` (`number | PtLike`) — width as a number, or a Pt that defines its size
- `height` (`number`) — optional height as a number

**Returns:** a Group of 2 Pts representing a rectangle

<a id="op-rectangle-static-from-center"></a>
##### `fromCenter`

*static*

```ts
static fromCenter(center: PtLike, widthOrSize: number | PtLike, height: number): Group
```

Create a rectangle given a center position and a size.

**Parameters**

- `center` (`PtLike`) — center point
- `widthOrSize` (`number | PtLike`) — width as a number, or a Pt that defines its size
- `height` (`number`) — optional height as a number

**Returns:** a Group of 2 Pts representing a rectangle

<a id="op-rectangle-static-from-top-left"></a>
##### `fromTopLeft`

*static*

```ts
static fromTopLeft(topLeft: PtLike, widthOrSize: number | PtLike, height: number): Group
```

Create a rectangle given a top-left position and a size.

**Parameters**

- `topLeft` (`PtLike`) — top-left point
- `widthOrSize` (`number | PtLike`) — width as a number, or a Pt that defines its size
- `height` (`number`) — optional height as a number

**Returns:** a Group of 2 Pts representing a rectangle

<a id="op-rectangle-static-halves"></a>
##### `halves`

*static*

```ts
static halves(rect: PtIterable, ratio: number = 0.5, asRows: boolean = false): Group[]
```

Subdivde a rectangle into 2 rectangles, by row or by column.

**Parameters**

- `rect` (`PtIterable`) — a Group or an Iterable<Pt> with 2 Pt representing a Rectangle
- `ratio` (`number`; default `0.5`) — a value between 0 to 1 to indicate the split ratio
- `asRows` (`boolean`; default `false`) — if `true`, split into 2 rows. Default is `false` which splits into 2 columns.

**Returns:** an array of 2 Groups of rectangles

<a id="op-rectangle-static-has-intersect-rect2-d"></a>
##### `hasIntersectRect2D`

*static*

```ts
static hasIntersectRect2D(rect1: GroupLike, rect2: GroupLike, resetBoundingBox: boolean = false): boolean
```

Check if a rectangle is within the bounds of another rectangle.

**Parameters**

- `rect1` (`GroupLike`) — a Group of 2 Pts representing a rectangle
- `rect2` (`GroupLike`) — a Group of 2 Pts representing a rectangle
- `resetBoundingBox` (`boolean`; default `false`) — if `true`, reset the bounding box. Default is `false` which assumes the rect's first Pt at is its top-left corner.

<a id="op-rectangle-static-intersect-rect2-d"></a>
##### `intersectRect2D`

*static*

```ts
static intersectRect2D(rect1: GroupLike, rect2: GroupLike): Group
```

An easy way to get rectangle-rectangle intersection points. For more optimized implementation, store the rectangle's sides separately (eg, `Rectangle.sides()`) and use `Polygon.intersectPolygon2D()`.

**Parameters**

- `rect1` (`GroupLike`) — a Group of 2 Pts representing a rectangle
- `rect2` (`GroupLike`) — a Group of 2 Pts representing a rectangle

<a id="op-rectangle-static-polygon"></a>
##### `polygon`

*static*

```ts
static polygon(rect: PtIterable): Group
```

Convert this rectangle into a Group representing a polygon. An alias for [`Rectangle.corners`](#op-rectangle-static-corners)

**Parameters**

- `rect` (`PtIterable`) — a Group or an Iterable<Pt> with 2 Pt representing a Rectangle

<a id="op-rectangle-static-quadrants"></a>
##### `quadrants`

*static*

```ts
static quadrants(rect: PtIterable, center: PtLike): Group[]
```

Subdivide a rectangle into 4 rectangles, one for each quadrant.

**Parameters**

- `rect` (`PtIterable`) — a Group or an Iterable<Pt> with 2 Pt representing a Rectangle
- `center` (`PtLike`)

**Returns:** an array of 4 Groups of rectangles

<a id="op-rectangle-static-sides"></a>
##### `sides`

*static*

```ts
static sides(rect: PtIterable): Group[]
```

Get the 4 sides of this rectangle as an array of 4 Groups.

**Parameters**

- `rect` (`PtIterable`) — a Group or an Iterable<Pt> with 2 Pt representing a Rectangle

**Returns:** an array of 4 Groups, each of which represents a line segment

<a id="op-rectangle-static-size"></a>
##### `size`

*static*

```ts
static size(pts: PtIterable): Pt
```

Get the size of this rectangle as a Pt.

**Parameters**

- `pts` (`PtIterable`) — a Group or an Iterable<Pt> with 2 Pt representing a Rectangle

<a id="op-rectangle-static-to-circle"></a>
##### `toCircle`

*static*

```ts
static toCircle(pts: PtIterable, enclose: boolean = true): Group
```

Create a new circle that either fits within or encloses the rectangle. Same as [`Circle.fromRect`](#op-circle-static-from-rect).

**Parameters**

- `pts` (`PtIterable`) — a Group or an Iterable<Pt> with 2 Pt representing a rectangle
- `enclose` (`boolean`; default `true`) — if `true`, the circle will enclose the rectangle. If `false`, the circle will fit inside the rectangle.

**Returns:** a Group that represents a circle

<a id="op-rectangle-static-to-square"></a>
##### `toSquare`

*static*

```ts
static toSquare(pts: PtIterable, enclose: boolean = false): Group
```

Create a square that either fits within or encloses a rectangle.

**Parameters**

- `pts` (`PtIterable`) — a Group or an Iterable<Pt> with 2 Pt representing a rectangle
- `enclose` (`boolean`; default `false`) — if `true`, the square will enclose the rectangle. Default is `false`, which will fit the square inside the rectangle.

**Returns:** a Group of 2 Pts representing a rectangle

<a id="op-rectangle-static-within-bound"></a>
##### `withinBound`

*static*

```ts
static withinBound(rect: GroupLike, pt: PtLike): boolean
```

Check if a point is within a rectangle.

**Parameters**

- `rect` (`GroupLike`) — a Group of 2 Pts representing a Rectangle
- `pt` (`PtLike`) — the point to check

<a id="op-triangle"></a>
### `Triangle`

**Kind:** Class · **Source:** [`src/Op.ts:907`](https://github.com/williamngan/pts/blob/master/src/Op.ts#L907)

Triangle class provides static functions to create and operate on trianges. A triange is a polygon represented as a Group of 3 Pts.
You can use the static functions as-is, or apply the [`Group.op`](#pt-group-op) or [`Pt.op`](#pt-pt-op) to enable functional programming.
See [Op guide](https://ptsjs.org/guide/Op-0400.html) for details.

#### Methods

<a id="op-triangle-static-altitude"></a>
##### `altitude`

*static*

```ts
static altitude(tri: PtIterable, index: number): Group
```

Get a triangle's altitude, which is a line from a triangle's point to its opposite side, and perpendicular to its opposite side.

**Parameters**

- `tri` (`PtIterable`) — a Group or an Iterable<Pt> representing a triangle
- `index` (`number`) — a Pt on the triangle group

**Returns:** a Group that represents the altitude line

<a id="op-triangle-static-circumcenter"></a>
##### `circumcenter`

*static*

```ts
static circumcenter(tri: PtIterable): Pt | undefined
```

Get circumcenter, which is the intersection point of its 3 perpendicular bisectors lines ( each of which divides a side in half and is perpendicular to the side).

**Parameters**

- `tri` (`PtIterable`) — a Group or an Iterable<Pt> representing a triangle

**Returns:** the circumcenter as a Pt

<a id="op-triangle-static-circumcircle"></a>
##### `circumcircle`

*static*

```ts
static circumcircle(tri: PtIterable, center: Pt): Group | undefined
```

Get circumcenter, which is the intersection point of its 3 perpendicular bisectors lines ( each of which divides a side in half and is perpendicular to the side).

**Parameters**

- `tri` (`PtIterable`) — a Group or an Iterable<Pt> representing a triangle
- `center` (`Pt`) — Optional parameter if the circumcenter is already known. Otherwise, leave it empty and the circumcenter will be calculated

<a id="op-triangle-static-from-center"></a>
##### `fromCenter`

*static*

```ts
static fromCenter(pt: PtLike, size: number): Group
```

Create an equilateral triangle based on a center point and a size.

**Parameters**

- `pt` (`PtLike`) — the center point
- `size` (`number`) — size is the magnitude of lines from center to the triangle's vertices, like a "radius".

<a id="op-triangle-static-from-circle"></a>
##### `fromCircle`

*static*

```ts
static fromCircle(circle: PtIterable): Group
```

Create a triangle that fits within a circle.

**Parameters**

- `circle` (`PtIterable`) — a Group or an Iterable<Pt> with 2 Pt representing a circle

<a id="op-triangle-static-from-rect"></a>
##### `fromRect`

*static*

```ts
static fromRect(rect: PtIterable): Group
```

Create a triangle from a rectangle. The triangle will be isosceles, with the bottom of the rectangle as its base.

**Parameters**

- `rect` (`PtIterable`) — a Group or an Iterable<Pt> with 2 Pt representing a rectangle

<a id="op-triangle-static-incenter"></a>
##### `incenter`

*static*

```ts
static incenter(tri: PtIterable): Pt | undefined
```

Get incenter, which is the center point of its inner circle, and also the intersection point of its 3 angle bisector lines (each of which cuts one of the 3 angles in half).

**Parameters**

- `tri` (`PtIterable`) — a Group or an Iterable<Pt> representing a triangle

**Returns:** the incenter as a Pt

<a id="op-triangle-static-incircle"></a>
##### `incircle`

*static*

```ts
static incircle(tri: PtIterable, center: Pt): Group | undefined
```

Get an interior circle, which is the largest circle completed enclosed by this triangle.

**Parameters**

- `tri` (`PtIterable`) — a Group or an Iterable<Pt> representing a triangle
- `center` (`Pt`) — Optional parameter if the incenter is already known. Otherwise, leave it empty and the incenter will be calculated

<a id="op-triangle-static-medial"></a>
##### `medial`

*static*

```ts
static medial(tri: PtIterable): Group
```

Get the medial, which is an inner triangle formed by connecting the midpoints of this triangle's sides.

**Parameters**

- `tri` (`PtIterable`) — a Group or an Iterable<Pt> representing a triangle

**Returns:** a Group representing a medial triangle

<a id="op-triangle-static-opposite-side"></a>
##### `oppositeSide`

*static*

```ts
static oppositeSide(tri: PtIterable, index: number): Group
```

Given a point of the triangle, the opposite side is the side which the point doesn't touch.

**Parameters**

- `tri` (`PtIterable`) — a Group or an Iterable<Pt> representing a triangle
- `index` (`number`) — a Pt on the triangle group

**Returns:** a Group that represents a line of the opposite side

<a id="op-triangle-static-orthocenter"></a>
##### `orthocenter`

*static*

```ts
static orthocenter(tri: PtIterable): Pt | undefined
```

Get orthocenter, which is the intersection point of a triangle's 3 altitudes (the 3 lines that are perpendicular to its 3 opposite sides).

**Parameters**

- `tri` (`PtIterable`) — a Group or an Iterable<Pt> representing a triangle

**Returns:** the orthocenter as a Pt

<a id="module-physics"></a>
## Module: `Physics`

<a id="physics-body"></a>
### `Body`

**Kind:** Class · **Source:** [`src/Physics.ts:951`](https://github.com/williamngan/pts/blob/master/src/Physics.ts#L951)

**Extends:** `Group`

Body is a subclass of [`Group`](#pt-group) that stores a set of [`Particle`](#physics-particle)s and edge constraints. It is usually added into a [`World`](#physics-world) to create physics simulations.
See [a demo here](https://ptsjs.org/demo/?name=physics.shapes).

#### Constructors

<a id="physics-body-constructor"></a>
##### Constructor

*overrides `Group.__constructor`*

```ts
new Body(): Body
```

Create an empty Body, this is usually followed by [`Body.init`](#physics-body-init) to populate the Body. Alternatively, use static function [`Body.fromGroup`](#physics-body-static-from-group) to create and initate a body directly.

#### Accessors

<a id="physics-body-mass"></a>
##### `mass`

```ts
get mass(): number
set mass(m: number): void
```

Get mass of this body.

#### Methods

<a id="physics-body-auto-mass"></a>
##### `autoMass`

```ts
autoMass(): this
```

Automatically calculate a body's `mass` based on the area of the polygon.

<a id="physics-body-init"></a>
##### `init`

```ts
init(body: PtIterable, stiff: number = 1): this
```

Initiate a body.

**Parameters**

- `body` (`PtIterable`) — a Group or an Iterable<Pt> to define a body
- `stiff` (`number`; default `1`) — stiffness value from 0 to 1, where 1 is the most stiff. Default is 1.

<a id="physics-body-link"></a>
##### `link`

```ts
link(index1: number, index2: number, stiff: number): this
```

Create a linked edge between two points.

**Parameters**

- `index1` (`number`) — first point by index
- `index2` (`number`) — first point by index
- `stiff` (`number`) — optionally stiffness value between 0 to 1, where 1 is the most stiff.

<a id="physics-body-link-all"></a>
##### `linkAll`

```ts
linkAll(stiff: number): void
```

Automatically create links for all the points to preserve the initial body shape. This usually works for regular convex polygon.

**Parameters**

- `stiff` (`number`) — optionally stiffness value between 0 to 1, where 1 is the most stiff.

<a id="physics-body-links-to-lines"></a>
##### `linksToLines`

```ts
linksToLines(): Group[]
```

Return a list of all the linked edges as line segments.

**Returns:** an array of Groups, each of which represents an edge

<a id="physics-body-process-body"></a>
##### `processBody`

```ts
processBody(b: Body): void
```

Check and respond to collisions between two bodies.

**Parameters**

- `b` (`Body`) — another body

<a id="physics-body-process-edges"></a>
##### `processEdges`

```ts
processEdges(): void
```

Recalculate all edge constraints.

<a id="physics-body-process-particle"></a>
##### `processParticle`

```ts
processParticle(b: Particle): void
```

Check and respond to collisions between this body and a particle.

**Parameters**

- `b` (`Particle`) — a particle

<a id="physics-body-solve-edges"></a>
##### `solveEdges`

```ts
solveEdges(dt: number, iterations: number = 1, substeps: number = 1): this
```

Solve all edge constraints for one substep in XPBD form. A link's `stiff` value is a
geometric knob: it is the fraction of the remaining constraint violation resolved per
update, independent of the particles' masses and of the substep/iteration counts
(per Müller et al. 2007, the per-pass fraction is `1-(1-stiff)^(1/passes)`), and
`stiff=1` is a rigid projection. Mapping the fraction to a mass-relative compliance
keeps a heavy body exactly as stiff as a light one at the same value.
This is the solver used internally by [`World.update`](#physics-world-update);
[`Body.processEdges`](#physics-body-process-edges) remains the simpler relaxation for direct use.

**Parameters**

- `dt` (`number`) — substep time in seconds (reserved; the geometric stiffness does not depend on it)
- `iterations` (`number`; default `1`) — solver iterations for this substep. Default is 1.
- `substeps` (`number`; default `1`) — the caller's substeps per update, for pass-count-independent stiffness. Default is 1.

<a id="physics-body-static-from-group"></a>
##### `fromGroup`

*static*

```ts
static fromGroup(body: PtIterable, stiff: number = 1, autoLink: boolean = true, autoMass: boolean = true): Body
```

Create and populate a body.

**Parameters**

- `body` (`PtIterable`) — a Group or an Iterable<Pt> to define the body
- `stiff` (`number`; default `1`) — stiffness value from 0 to 1, where 1 is the most stiff. Default is 1.
- `autoLink` (`boolean`; default `true`) — Automatically create links between the Pts. This usually works for regular convex polygons. Default is true.
- `autoMass` (`boolean`; default `true`) — Automatically calculate the mass based on the area of the polygon. Default is true.

#### Inherited API

- From [`Group`](#pt-group): [`id`](#pt-group-id), [`p1`](#pt-group-p1), [`p2`](#pt-group-p2), [`p3`](#pt-group-p3), [`p4`](#pt-group-p4), [`q1`](#pt-group-q1), [`q2`](#pt-group-q2), [`q3`](#pt-group-q3), [`q4`](#pt-group-q4), [`$matrixAdd`](#pt-group-dollar-matrix-add), [`$matrixMultiply`](#pt-group-dollar-matrix-multiply), [`$zip`](#pt-group-dollar-zip), [`add`](#pt-group-add), [`anchorFrom`](#pt-group-anchor-from), [`anchorTo`](#pt-group-anchor-to), [`boundingBox`](#pt-group-bounding-box), [`centroid`](#pt-group-centroid), [`clone`](#pt-group-clone), [`divide`](#pt-group-divide), [`forEachPt`](#pt-group-for-each-pt), [`insert`](#pt-group-insert), [`interpolate`](#pt-group-interpolate), [`lines`](#pt-group-lines), [`moveBy`](#pt-group-move-by), [`moveTo`](#pt-group-move-to), [`multiply`](#pt-group-multiply), [`op`](#pt-group-op), [`ops`](#pt-group-ops), [`reflect2D`](#pt-group-reflect2-d), [`remove`](#pt-group-remove), [`rotate2D`](#pt-group-rotate2-d), [`scale`](#pt-group-scale), [`segments`](#pt-group-segments), [`shear2D`](#pt-group-shear2-d), [`sortByDimension`](#pt-group-sort-by-dimension), [`split`](#pt-group-split), [`subtract`](#pt-group-subtract), [`toBound`](#pt-group-to-bound), [`toString`](#pt-group-to-string), [`zipSlice`](#pt-group-zip-slice), [`fromArray`](#pt-group-static-from-array), [`fromPtArray`](#pt-group-static-from-pt-array).
- From [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array): 21 standard properties and methods (not repeated here).

<a id="physics-particle"></a>
### `Particle`

**Kind:** Class · **Source:** [`src/Physics.ts:682`](https://github.com/williamngan/pts/blob/master/src/Physics.ts#L682)

**Extends:** `Pt`

Particle is a subclass of [`Pt`](#pt-pt) that has radius and mass. It's usually added into [`World`](#physics-world) to create physics simulations.
See [a demo here](https://ptsjs.org/demo/?name=physics.particles).

#### Constructors

<a id="physics-particle-constructor"></a>
##### Constructor

*overrides `Pt.__constructor`*

```ts
new Particle(args: any[]): Particle
```

Create a particle. Once a particle is created, you can set its mass and radius via the corresponding accessors.

**Parameters**

- `args` (`any[]`) — a list of numeric parameters, an array of numbers, or an object with {x,y,z,w} properties

#### Accessors

<a id="physics-particle-body"></a>
##### `body`

```ts
get body(): Body
set body(b: Body): void
```

Get the body of this particle, if any.

<a id="physics-particle-changed"></a>
##### `changed`

```ts
get changed(): Pt
```

Get the change in position per 60 Hz frame, ie, the current velocity in the same unit
as [`Particle.hit`](#physics-particle-hit). The raw displacement since the last step is
`particle.$subtract( particle.previous )`.

<a id="physics-particle-force"></a>
##### `force`

```ts
get force(): Pt
set force(g: Pt): void
```

Get current accumulated force.

<a id="physics-particle-lock"></a>
##### `lock`

```ts
get lock(): boolean
set lock(b: boolean): void
```

Lock this particle in current position.

<a id="physics-particle-mass"></a>
##### `mass`

```ts
get mass(): number
set mass(m: number): void
```

Mass of this particle.

<a id="physics-particle-position"></a>
##### `position`

```ts
set position(p: Pt): void
```

Set a new position, and update previous and lock states if needed. The move is stored as
this particle's velocity per frame, so dragging a locked particle knocks others away.

<a id="physics-particle-previous"></a>
##### `previous`

```ts
get previous(): Pt
set previous(p: Pt): void
```

Get this particle's previous position.

<a id="physics-particle-radius"></a>
##### `radius`

```ts
get radius(): number
set radius(f: number): void
```

Radius of this particle.

<a id="physics-particle-time-step"></a>
##### `timeStep`

```ts
get timeStep(): number
set timeStep(t: number): void
```

The time in seconds spanned by the displacement from [`Particle.previous`](#physics-particle-previous) to the
current position. A [`World`](#physics-world) sets it to the substep length on every step, and
[`Particle.hit`](#physics-particle-hit) and the `position` setter reset it to one 60 Hz frame (1/60),
which is the unit of their velocities. 0 means unknown and is treated as one frame.

#### Methods

<a id="physics-particle-add-force"></a>
##### `addForce`

```ts
addForce(args: any[]): Pt
```

Add to the accumulated force.

**Parameters**

- `args` (`any[]`) — a list of numeric parameters, an array of numbers, or an object with {x,y,z,w} properties

<a id="physics-particle-collide"></a>
##### `collide`

```ts
collide(p2: Particle, damp: number = 1): void
```

Check and respoond to collisions between this and another particle.

**Parameters**

- `p2` (`Particle`) — another particle
- `damp` (`number`; default `1`) — damping value between 0 to 1, where 1 means no damping.

<a id="physics-particle-hit"></a>
##### `hit`

```ts
hit(args: any[]): this
```

Hit this particle with an impulse, in pixels per 60 Hz frame. The impulse is scaled by 1/√mass, so a heavier particle moves less from the same hit.
The result is the same at any frame rate and any [`World.substeps`](#physics-world-substeps) setting.

**Parameters**

- `args` (`any[]`) — an impulse vector defined by either a list of numeric parameters, an array of numbers, or an object with {x,y,z,w} properties

**Example**

```ts
hit(10, 20)`, `hit( new Pt(5, 9) )
```

<a id="physics-particle-size"></a>
##### `size`

```ts
size(r: number): this
```

Set the size of this particle. This sets both the radius and the mass.

**Parameters**

- `r` (`number`) — `radius` value, and also set `mass` to the same value.

<a id="physics-particle-to-string"></a>
##### `toString`

*overrides `Pt.toString`*

```ts
toString(): string
```

Get a string representation of this particle

<a id="physics-particle-verlet"></a>
##### `verlet`

```ts
verlet(dt: number, friction: number, lastDt: number): this
```

Verlet integration.

**Parameters**

- `dt` (`number`) — change in time in seconds
- `friction` (`number`) — friction from 0 to 1, where 1 means no friction
- `lastDt` (`number`) — optional last change in time in seconds. Default is [`Particle.timeStep`](#physics-particle-time-step), or `dt` if unknown.

#### Inherited API

- From [`Pt`](#pt-pt): [`id`](#pt-pt-id), [`w`](#pt-pt-w), [`x`](#pt-pt-x), [`y`](#pt-pt-y), [`z`](#pt-pt-z), [`$abs`](#pt-pt-dollar-abs), [`$add`](#pt-pt-dollar-add), [`$ceil`](#pt-pt-dollar-ceil), [`$concat`](#pt-pt-dollar-concat), [`$cross`](#pt-pt-dollar-cross), [`$cross2D`](#pt-pt-dollar-cross2-d), [`$divide`](#pt-pt-dollar-divide), [`$floor`](#pt-pt-dollar-floor), [`$max`](#pt-pt-dollar-max), [`$min`](#pt-pt-dollar-min), [`$multiply`](#pt-pt-dollar-multiply), [`$project`](#pt-pt-dollar-project), [`$round`](#pt-pt-dollar-round), [`$subtract`](#pt-pt-dollar-subtract), [`$take`](#pt-pt-dollar-take), [`$to`](#pt-pt-dollar-to), [`$unit`](#pt-pt-dollar-unit), [`abs`](#pt-pt-abs), [`add`](#pt-pt-add), [`angle`](#pt-pt-angle), [`angleBetween`](#pt-pt-angle-between), [`ceil`](#pt-pt-ceil), [`clone`](#pt-pt-clone), [`divide`](#pt-pt-divide), [`dot`](#pt-pt-dot), [`equals`](#pt-pt-equals), [`floor`](#pt-pt-floor), [`magnitude`](#pt-pt-magnitude), [`magnitudeSq`](#pt-pt-magnitude-sq), [`maxValue`](#pt-pt-max-value), [`minValue`](#pt-pt-min-value), [`multiply`](#pt-pt-multiply), [`op`](#pt-pt-op), [`ops`](#pt-pt-ops), [`projectScalar`](#pt-pt-project-scalar), [`reflect2D`](#pt-pt-reflect2-d), [`rotate2D`](#pt-pt-rotate2-d), [`round`](#pt-pt-round), [`scale`](#pt-pt-scale), [`shear2D`](#pt-pt-shear2-d), [`subtract`](#pt-pt-subtract), [`to`](#pt-pt-to), [`toAngle`](#pt-pt-to-angle), [`toArray`](#pt-pt-to-array), [`toBound`](#pt-pt-to-bound), [`toGroup`](#pt-pt-to-group), [`unit`](#pt-pt-unit), [`make`](#pt-pt-static-make).
- From [`Float32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array): 26 standard properties and methods (not repeated here).

<a id="physics-world"></a>
### `World`

**Kind:** Class · **Source:** [`src/Physics.ts:21`](https://github.com/williamngan/pts/blob/master/src/Physics.ts#L21)

#### Constructors

<a id="physics-world-constructor"></a>
##### Constructor

```ts
new World(bound: PtIterable, friction: number = 1, gravity: number | PtLike = 0): World
```

Create a `World` for 2D physics simulation.

**Parameters**

- `bound` (`PtIterable`) — a Group or an Iterable<Pt> representing a rectangular bounding box
- `friction` (`number`; default `1`) — a value between 0 to 1, where 1 means no friction. Default is 1
- `gravity` (`number | PtLike`; default `0`) — a number of a Pt to define gravitational force. A number is a shorthand to set `new Pt(0, n)`. Default is 0.

#### Accessors

<a id="physics-world-body-count"></a>
##### `bodyCount`

```ts
get bodyCount(): number
```

Get the number of bodies.

<a id="physics-world-bound"></a>
##### `bound`

```ts
get bound(): Bound
set bound(bound: Bound): void
```

Current bound in this `World`.

<a id="physics-world-damping"></a>
##### `damping`

```ts
get damping(): number
set damping(f: number): void
```

Current damping in this `World`.

<a id="physics-world-friction"></a>
##### `friction`

```ts
get friction(): number
set friction(f: number): void
```

Current friction in this `World`.

<a id="physics-world-gravity"></a>
##### `gravity`

```ts
get gravity(): Pt
set gravity(g: Pt): void
```

Current gravity in this `World`.

<a id="physics-world-iterations"></a>
##### `iterations`

```ts
get iterations(): number
set iterations(f: number): void
```

Constraint solver iterations per substep.

<a id="physics-world-max-time-step"></a>
##### `maxTimeStep`

```ts
get maxTimeStep(): number
set maxTimeStep(ms: number): void
```

Maximum simulated time in milliseconds per [`World.update`](#physics-world-update) call. Larger elapsed
times are clamped so that a hitch (eg, a backgrounded tab) cannot destabilize the
simulation. Default is 50.

<a id="physics-world-particle-count"></a>
##### `particleCount`

```ts
get particleCount(): number
```

Get the number of particles.

<a id="physics-world-substeps"></a>
##### `substeps`

```ts
get substeps(): number
set substeps(n: number): void
```

Target number of solver substeps per 60 Hz frame (16.7 ms). Each [`World.update`](#physics-world-update)
runs enough substeps of about that size to cover its elapsed time, so a 30 Hz frame solves
twice as many substeps as a 60 Hz frame rather than larger ones. More substeps produce a
more stable and accurate simulation at a linear cost. Default is 4.

#### Methods

<a id="physics-world-add"></a>
##### `add`

```ts
add(p: Particle | Body, name: string = ""): this
```

Add a particle or body to this world.

**Parameters**

- `p` (`Particle | Body`) — `Particle` or `Body` instance
- `name` (`string`; default `""`) — optional name, which can be referenced in `body()` or `particle()` function to retrieve this back.

<a id="physics-world-body"></a>
##### `body`

```ts
body(id: string | number): Body | undefined
```

Get a body in this world by index or string id.

**Parameters**

- `id` (`string | number`) — numeric index of the body, or a string id that associates with it.

**Returns:** a Body, or undefined if not found

<a id="physics-world-body-index"></a>
##### `bodyIndex`

```ts
bodyIndex(name: string): number
```

Given a body's name, return its index in the bodies array, or -1 if not found.

**Parameters**

- `name` (`string`) — name of the body

**Returns:** index number, or -1 if not found

<a id="physics-world-draw-bodies"></a>
##### `drawBodies`

```ts
drawBodies(fn:  Fn(p:Body, i:number)): void
```

Draw bodies using the provided function.

**Parameters**

- `fn` (` Fn(p:Body, i:number)`) — a function that draws a body passed in the parameters `(body, index)`.

<a id="physics-world-draw-particles"></a>
##### `drawParticles`

```ts
drawParticles(fn:  Fn(p:Particle, i:number)): void
```

Draw particles using the provided function.

**Parameters**

- `fn` (` Fn(p:Particle, i:number)`) — a function that draws a particle passed in the parameters `(particle, index)`.

<a id="physics-world-integrate"></a>
##### `integrate`

*protected*

```ts
integrate(p: Particle, dt: number, prevDt: number = ...): Particle
```

Integrate a particle for one substep: Verlet with the accumulated force plus gravity as
acceleration, and the substep-adjusted friction as drag. Forces are read but not cleared
here — they persist across the substeps of one update and are cleared when it completes.

**Parameters**

- `p` (`Particle`) — particle
- `dt` (`number`) — substep time in seconds
- `prevDt` (`number`; default `...`) — time in seconds spanned by the particle's current displacement (see [`Particle.timeStep`](#physics-particle-time-step)); the velocity is rescaled to `dt` so that it is preserved when the step size changes.

<a id="physics-world-particle"></a>
##### `particle`

```ts
particle(id: string | number): Particle | undefined
```

Get a particle in this world by index or string id.

**Parameters**

- `id` (`string | number`) — numeric index of the particle, or a string id that associates with it.

**Returns:** a Particle, or undefined if not found

<a id="physics-world-particle-index"></a>
##### `particleIndex`

```ts
particleIndex(name: string): number
```

Given a particle's name, return its index in the particles array, or -1 if not found.

**Parameters**

- `name` (`string`) — name of the particle

**Returns:** index number, or -1 if not found

<a id="physics-world-remove-body"></a>
##### `removeBody`

```ts
removeBody(from: string | number, count: number = 1): this
```

Remove bodies from this world. Support removing a range and negative index.

**Parameters**

- `from` (`string | number`) — Start index, which can be negative (where -1 is at index 0, -2 at index 1, etc)
- `count` (`number`; default `1`) — Number of items to remove. Default is 1.

<a id="physics-world-remove-particle"></a>
##### `removeParticle`

```ts
removeParticle(from: string | number, count: number = 1): this
```

Remove particles from this world. Support removing a range and negative index.

**Parameters**

- `from` (`string | number`) — Start index, which can be negative (where -1 is at index 0, -2 at index 1, etc)
- `count` (`number`; default `1`) — Number of items to remove. Default is 1.

<a id="physics-world-update"></a>
##### `update`

```ts
update(ms: number): void
```

Advance this world by an amount of time, solved in substeps sized by
[`World.substeps`](#physics-world-substeps). The time is clamped to [`World.maxTimeStep`](#physics-world-max-time-step), and an
elapsed time under 2 ms is carried into the next call. Draw callbacks fire once per call,
after the solve completes.

**Parameters**

- `ms` (`number`) — change in time in milliseconds

<a id="physics-world-static-bound-constraint"></a>
##### `boundConstraint`

*static*

```ts
static boundConstraint(p: Particle, rect: PtIterable, damping: number = 0.75): void
```

Static function to calculate bounding box constraints.

**Parameters**

- `p` (`Particle`) — particle
- `rect` (`PtIterable`) — a Group or an Iterable<Pt> representing a bounding box
- `damping` (`number`; default `0.75`) — damping between 0 to 1, where 1 means no damping. Default is 0.75.

<a id="physics-world-static-edge-constraint"></a>
##### `edgeConstraint`

*static*

```ts
static edgeConstraint(p1: Particle, p2: Particle, dist: number, stiff: number = 1, precise: boolean = false): Particle
```

Static function to calculate edge constraints between 2 particles.

**Parameters**

- `p1` (`Particle`) — particle 1
- `p2` (`Particle`) — particle 2
- `dist` (`number`) — distance between particles
- `stiff` (`number`; default `1`) — stiffness between 0 to 1.
- `precise` (`boolean`; default `false`) — use precise distance calculation. Default is `false`.

<a id="module-play"></a>
## Module: `Play`

<a id="play-sound"></a>
### `Sound`

**Kind:** Class · **Source:** [`src/Play.ts:206`](https://github.com/williamngan/pts/blob/master/src/Play.ts#L206)

Sound class simplifies common tasks like audio inputs and visualizations using a subset of Web Audio API. It can be used with other audio libraries like tone.js, and extended to support additional web audio functions. See [the guide](https://ptsjs.org/guide/Sound-0800.html) to get started.

#### Constructors

<a id="play-sound-constructor"></a>
##### Constructor

```ts
new Sound(type: SoundType, ctx: AudioContext): Sound
```

Construct a `Sound` instance. Usually, it's more convenient to use one of the static methods like [`Sound.load`](#play-sound-static-load) or [`Sound.from`](#play-sound-static-from).
By default, all instances share a single `AudioContext` (browsers limit how many can be live at once).

**Parameters**

- `type` (`SoundType`) — a `SoundType` string: "file", "input", or "gen"
- `ctx` (`AudioContext`) — Optionally provide your own AudioContext instead of the shared one

#### Accessors

<a id="play-sound-bin-size"></a>
##### `binSize`

```ts
get binSize(): number
```

If an analyzer is added (see [`analyze`](#play-sound-analyze) function), get the number of frequency bins in the analyzer. Returns 0 if no analyzer is added.

<a id="play-sound-buffer"></a>
##### `buffer`

```ts
get buffer(): AudioBuffer
set buffer(b: AudioBuffer): void
```

Get this Sound's AudioBuffer (if any) instance for advanced use-cases. See [`Sound.loadAsBuffer`](#play-sound-static-load-as-buffer).

<a id="play-sound-ctx"></a>
##### `ctx`

```ts
get ctx(): AudioContext
```

Get this Sound's AudioContext instance for advanced use-cases.

<a id="play-sound-frequency"></a>
##### `frequency`

```ts
get frequency(): number
set frequency(f: number): void
```

If the sound is generated, this sets and gets the frequency of the tone.

<a id="play-sound-node"></a>
##### `node`

```ts
get node(): AudioNode
```

Get this Sound's AudioNode subclass instance for advanced use-cases.

<a id="play-sound-output-node"></a>
##### `outputNode`

```ts
get outputNode(): AudioNode
```

Get this Sound's Output node AudioNode instance for advanced use-cases.

<a id="play-sound-playable"></a>
##### `playable`

```ts
get playable(): boolean
```

Indicate whether the sound is ready to play. When loading from a file, this corresponds to a ["canplaythrough"](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/readyState) event.
You can also use `this.source.addEventListener( 'canplaythrough', ...)` if needed. See also [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canplaythrough_event).

<a id="play-sound-playing"></a>
##### `playing`

```ts
get playing(): boolean
```

Indicate whether the sound is currently playing.

<a id="play-sound-progress"></a>
##### `progress`

```ts
get progress(): number
```

A value between 0 to 1 to indicate playback progress. Returns 0 if the sound has no duration (eg, generated or input sounds).

<a id="play-sound-sample-rate"></a>
##### `sampleRate`

```ts
get sampleRate(): number
```

Get the sample rate of the audio, for example, at 44100 hz.

<a id="play-sound-source"></a>
##### `source`

```ts
get source(): HTMLMediaElement
```

Get this Sound's Audio element (if used) instance for advanced use-cases. See [`Sound.load`](#play-sound-static-load).

<a id="play-sound-stream"></a>
##### `stream`

```ts
get stream(): MediaStream
```

Get this Sound's MediaStream (eg, from microphone, if in use) instance for advanced use-cases. See [`Sound.input`](#play-sound-static-input)

<a id="play-sound-type"></a>
##### `type`

```ts
get type(): SoundType
```

Get the type of input for this Sound instance. Either "file", "input", or "gen"

<a id="play-sound-volume"></a>
##### `volume`

```ts
get volume(): number
set volume(v: number): void
```

Get and set the volume of this sound. Default is 1. Values above 1 amplify the sound. Can be set before or during playback.

#### Methods

<a id="play-sound-analyze"></a>
##### `analyze`

```ts
analyze(size: number = 256, minDb: number = -100, maxDb: number = -30, smooth: number = 0.8): this
```

Add an analyzer to this `Sound`. Calling it again replaces the existing analyzer.

**Parameters**

- `size` (`number`; default `256`) — the number of frequency bins. Should be a power of 2.
- `minDb` (`number`; default `-100`) — Optional minimum decibels (corresponds to `AnalyserNode.minDecibels`)
- `maxDb` (`number`; default `-30`) — Optional maximum decibels (corresponds to `AnalyserNode.maxDecibels`)
- `smooth` (`number`; default `0.8`) — Optional smoothing value (corresponds to `AnalyserNode.smoothingTimeConstant`)

<a id="play-sound-connect"></a>
##### `connect`

```ts
connect(node: AudioNode): this
```

Connect another AudioNode to this `Sound` instance's AudioNode. Using this function, you can extend the capabilities of this `Sound` instance for advanced use cases such as filtering. The connection is restored if a generated sound is restarted.

**Parameters**

- `node` (`AudioNode`) — another AudioNode

<a id="play-sound-create-buffer"></a>
##### `createBuffer`

```ts
createBuffer(buf: AudioBuffer): this
```

Create or re-use an AudioBuffer. Only needed if you are using `Sound.loadAsBuffer` and want to prepare a replay manually — [`start`](#play-sound-start) re-creates a used buffer automatically.

**Parameters**

- `buf` (`AudioBuffer`) — an AudioBuffer. Optionally, you can call this without parameters to re-use existing buffer.

<a id="play-sound-dispose"></a>
##### `dispose`

```ts
dispose(): this
```

Stop playing and disconnect all nodes (including analyzer and volume), and release stream, source, and buffer references.
The instance should not be used after calling this. Note that this never closes an `AudioContext`: the shared context lives for the page, and a context you provided is yours to close.

<a id="play-sound-freq-domain"></a>
##### `freqDomain`

```ts
freqDomain(): Uint8Array
```

Get the raw frequency-domain data from analyzer as unsigned 8-bit integers. An analyzer must be added before calling this function (See [analyze](#play-sound-analyze) function).

<a id="play-sound-freq-domain-to"></a>
##### `freqDomainTo`

```ts
freqDomainTo(size: PtLike, position: PtLike = ..., trim: number[] = ..., out: Group): Group
```

Map the frequency-domain data from analyzer to a range. An analyzer must be added before calling this function (See [analyze](#play-sound-analyze) function).

**Parameters**

- `size` (`PtLike`) — map each data point `[index, value]` to `[width, height]`
- `position` (`PtLike`; default `...`) — Optionally, set a starting `[x, y]` position. Default is `[0, 0]`
- `trim` (`number[]`; default `...`) — Optionally, trim the start and end values by `[startTrim, data.length-endTrim]`
- `out` (`Group`) — Optionally, provide a `Group` (usually one returned by a previous call) whose Pts will be reused instead of allocating new ones — recommended when calling once per frame

**Returns:** a Group containing the mapped values

**Example**

```ts
form.point( s.freqDomainTo( space.size ) )
```

<a id="play-sound-remove-output-node"></a>
##### `removeOutputNode`

```ts
removeOutputNode(): this
```

Removes the 'output' node added from setOutputNode
Note: if you start the Sound after calling this, it will play via the default node

<a id="play-sound-reset"></a>
##### `reset`

```ts
reset(): this
```

Stop playing and disconnect the AudioNode.

<a id="play-sound-set-output-node"></a>
##### `setOutputNode`

```ts
setOutputNode(outputNode: AudioNode): this
```

Sets the 'output' node for this Sound
This would typically be used after Sound.connect, if you are adding nodes
in your chain for filtering purposes.

**Parameters**

- `outputNode` (`AudioNode`) — The AudioNode that should connect to the AudioContext

<a id="play-sound-start"></a>
##### `start`

```ts
start(timeAt: number = 0): this
```

Start playing. Internally this connects the `AudioNode` to `AudioContext`'s destination.
Calling `start( timeAt )` while a file or buffer sound is playing seeks to that time; a generated sound that is already playing is unaffected.

**Parameters**

- `timeAt` (`number`; default `0`) — optional parameter to play from a specific time, in seconds

<a id="play-sound-stop"></a>
##### `stop`

```ts
stop(): this
```

Stop playing. Internally this also disconnects the `AudioNode` from `AudioContext`'s destination. Calling `stop` when the sound is not playing has no effect.

<a id="play-sound-time-domain"></a>
##### `timeDomain`

```ts
timeDomain(): Uint8Array
```

Get the raw time-domain data from analyzer as unsigned 8-bit integers. An analyzer must be added before calling this function (See [analyze](#play-sound-analyze) function).

<a id="play-sound-time-domain-to"></a>
##### `timeDomainTo`

```ts
timeDomainTo(size: PtLike, position: PtLike = ..., trim: number[] = ..., out: Group): Group
```

Map the time-domain data from analyzer to a range. An analyzer must be added before calling this function (See [analyze](#play-sound-analyze) function).

**Parameters**

- `size` (`PtLike`) — map each data point `[index, value]` to `[width, height]`
- `position` (`PtLike`; default `...`) — Optionally, set a starting `[x, y]` position. Default is `[0, 0]`
- `trim` (`number[]`; default `...`) — Optionally, trim the start and end values by `[startTrim, data.length-endTrim]`
- `out` (`Group`) — Optionally, provide a `Group` (usually one returned by a previous call) whose Pts will be reused instead of allocating new ones — recommended when calling once per frame

**Returns:** a Group containing the mapped values

**Example**

```ts
form.point( s.timeDomainTo( space.size ) )
```

<a id="play-sound-toggle"></a>
##### `toggle`

```ts
toggle(): this
```

Toggle between `start` and `stop`.

<a id="play-sound-static-from"></a>
##### `from`

*static*

```ts
static from(node: AudioNode, ctx: AudioContext, type: SoundType = "gen", stream: MediaStream): Sound
```

Create a `Sound` given an [AudioNode](https://developer.mozilla.org/en-US/docs/Web/API/AudioNode) and an [AudioContext](https://developer.mozilla.org/en-US/docs/Web/API/AudioContext) from Web Audio API. See also [this example](https://ptsjs.org/guide/js/examples/tone.html) using tone.js in the [guide](https://ptsjs.org/guide/Sound-0800.html).

**Parameters**

- `node` (`AudioNode`) — an AudioNode instance
- `ctx` (`AudioContext`) — an AudioContext instance
- `type` (`SoundType`; default `"gen"`) — a string representing a type of input source: either "file", "input", or "gen".
- `stream` (`MediaStream`) — Optionally include a MediaStream, if the type is "input"

**Returns:** a `Sound` instance

<a id="play-sound-static-generate"></a>
##### `generate`

*static*

```ts
static generate(type: OscillatorType, val: number | PeriodicWave): Sound
```

Create a `Sound` by generating a waveform using [OscillatorNode](https://developer.mozilla.org/en-US/docs/Web/API/OscillatorNode).

**Parameters**

- `type` (`OscillatorType`) — a string representing the waveform type: "sine", "square", "sawtooth", "triangle", "custom"
- `val` (`number | PeriodicWave`) — the frequency value in Hz to play, or a PeriodicWave instance if type is "custom".

**Returns:** a `Sound` instance

**Example**

```ts
Sound.generate( 'sine', 120 )
```

<a id="play-sound-static-input"></a>
##### `input`

*static*

```ts
static input(constraint: MediaStreamConstraints): Promise
```

Create a `Sound` by streaming from an input device like microphone. Note that this function returns a Promise which resolves to a Sound instance, and rejects if the input device is unavailable or permission is denied.

**Parameters**

- `constraint` (`MediaStreamConstraints`) — Optional constraints which can be used to select a specific input device. For example, you may use [`enumerateDevices`](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices) to find a specific deviceId;

**Returns:** a `Promise` which resolves to `Sound` instance

**Example**

```ts
Sound.input().then( s => sound = s ).catch( err => ... );
```

<a id="play-sound-static-load"></a>
##### `load`

*static*

```ts
static load(source: string | HTMLMediaElement, crossOrigin: string = "anonymous"): Promise
```

Create a `Sound` by loading from a sound file or an audio element.

**Parameters**

- `source` (`string | HTMLMediaElement`) — either an url string to load a sound file, or an audio element.
- `crossOrigin` (`string`; default `"anonymous"`) — whether to support loading cross-origin. Default is "anonymous". When passing an audio element, set the attribute in markup before the element loads for it to take effect.

**Returns:** a `Sound` instance

**Example**

```ts
Sound.load( '/path/to/file.mp3' )
```

<a id="play-sound-static-load-as-buffer"></a>
##### `loadAsBuffer`

*static*

```ts
static loadAsBuffer(url: string): Promise
```

Create a `Sound` by loading and decoding a sound file URL as an `AudioBufferSourceNode`.
Unlike [`Sound.load`](#play-sound-static-load), this loads the complete file instead of streaming it, which can provide more consistent analysis and replay behavior across browsers.

**Parameters**

- `url` (`string`) — an url to the sound file

#### Properties

<a id="play-sound-analyzer"></a>
##### `analyzer`

```ts
analyzer: ISoundAnalyzer
```

Analyzer if any

<a id="play-tempo"></a>
### `Tempo`

**Kind:** Class · **Source:** [`src/Play.ts:19`](https://github.com/williamngan/pts/blob/master/src/Play.ts#L19)

**Implements:** `IPlayer`

Tempo helps you create synchronized and rhythmic animations.

#### Constructors

<a id="play-tempo-constructor"></a>
##### Constructor

```ts
new Tempo(bpm: number): Tempo
```

Construct a new Tempo instance by beats-per-minute. Alternatively, you can use [`Tempo.fromBeat`](#play-tempo-static-from-beat) to create from milliseconds.

**Parameters**

- `bpm` (`number`) — beats per minute. Must be greater than 0.

#### Accessors

<a id="play-tempo-bpm"></a>
##### `bpm`

```ts
get bpm(): number
set bpm(n: number): void
```

Beats-per-minute value. Must be greater than 0.

<a id="play-tempo-ms"></a>
##### `ms`

```ts
get ms(): number
set ms(n: number): void
```

Milliseconds per beat (Note that this is derived from the bpm value).

#### Methods

<a id="play-tempo-action"></a>
##### `action`

```ts
action(type: string, px: number, py: number, evt: Event): void
```

IPlayer interface. Not implemented.

**Parameters**

- `type` (`string`)
- `px` (`number`)
- `py` (`number`)
- `evt` (`Event`)

<a id="play-tempo-animate"></a>
##### `animate`

```ts
animate(time: number, ftime: number): void
```

IPlayer interface. Internal implementation that calls `track( time )`.

**Parameters**

- `time` (`number`)
- `ftime` (`number`)

<a id="play-tempo-every"></a>
##### `every`

```ts
every(beats: number | number[]): ITempoResponses
```

This is a core function that let you specify a rhythm and then define responses by calling the `start` and `progress` functions from the returned object. See [Animation guide](https://ptsjs.org/guide/Animation-0700.html) for more details.
The `start` function lets you set a callback on every start. It takes a function ([`ITempoStartFn`](#types-itempostartfn)).
The `progress` function lets you set a callback during progress. It takes a function ([`ITempoProgressFn`](#types-itempoprogressfn)). Both functions let you optionally specify a time offset and a custom name.
A positive offset shifts the beat earlier (fires sooner), a negative offset shifts it later.

**Parameters**

- `beats` (`number | number[]`) — a rhythm in beats as a number or an array of numbers

**Returns:** an object with chainable functions

**Example**

```ts
tempo.every(2).start( (count) => ... )`, `tempo.every([2,4,6]).progress( (count, t) => ... )
```

<a id="play-tempo-resize"></a>
##### `resize`

```ts
resize(bound: Bound, evt: Event): void
```

IPlayer interface. Not implemented.

**Parameters**

- `bound` (`Bound`)
- `evt` (`Event`)

<a id="play-tempo-stop"></a>
##### `stop`

```ts
stop(name: string): void
```

Remove a `start` or `progress` callback function from the list of callbacks. See [`Tempo.every`](#play-tempo-every) for details

**Parameters**

- `name` (`string`) — a name string specified when creating the callback function.

<a id="play-tempo-track"></a>
##### `track`

```ts
track(time: number): void
```

Usually you can add a tempo instance to a space via [`Space.add`](#space-space-add) and it will track time automatically.
But if necessary, you can track time manually via this function.

**Parameters**

- `time` (`number`) — current time in milliseconds

<a id="play-tempo-static-from-beat"></a>
##### `fromBeat`

*static*

```ts
static fromBeat(ms: number): Tempo
```

Create a new Tempo instance by specifying milliseconds-per-beat.

**Parameters**

- `ms` (`number`) — milliseconds per beat. Must be greater than 0.

#### Properties

<a id="play-tempo-animate-id"></a>
##### `animateID`

*public*

```ts
animateID: string
```

<a id="module-pt"></a>
## Module: `Pt`

<a id="pt-bound"></a>
### `Bound`

**Kind:** Class · **Source:** [`src/Pt.ts:1060`](https://github.com/williamngan/pts/blob/master/src/Pt.ts#L1060)

**Extends:** `Group`

**Implements:** `IPt`

Bound is a subclass of [`Group`](#pt-group) that represents a rectangular boundary.
It includes some convenient accessors (eg, bottomRight, center) for bounding box calculations.

#### Constructors

<a id="pt-bound-constructor"></a>
##### Constructor

*overrides `Group.__constructor`*

```ts
new Bound(args: Pt[]): Bound
```

Create a Bound. This is similar to the Group constructor. You can also create a Bound via the static function [`Bound.fromGroup`](#pt-bound-static-from-group), or alternatively via the [Group.toBound](#pt-group-to-bound) function.

**Parameters**

- `args` (`Pt[]`) — a list of Pt as parameters

**See also:** Bound.fromGroup

#### Accessors

<a id="pt-bound-bottom-right"></a>
##### `bottomRight`

```ts
get bottomRight(): Pt
set bottomRight(p: Pt): void
```

Bottom-right position of this Bound

<a id="pt-bound-center"></a>
##### `center`

```ts
get center(): Pt
set center(p: Pt): void
```

Center position of this Bound

<a id="pt-bound-depth"></a>
##### `depth`

```ts
get depth(): number
set depth(d: number): void
```

Depth of this Bound

<a id="pt-bound-height"></a>
##### `height`

```ts
get height(): number
set height(h: number): void
```

Height of this Bound

<a id="pt-bound-inited"></a>
##### `inited`

```ts
get inited(): boolean
```

Whether this Bound has been initiated

<a id="pt-bound-size"></a>
##### `size`

```ts
get size(): Pt
set size(p: Pt): void
```

Size of this Bound

<a id="pt-bound-top-left"></a>
##### `topLeft`

```ts
get topLeft(): Pt
set topLeft(p: Pt): void
```

Top-left position of this Bound

<a id="pt-bound-width"></a>
##### `width`

```ts
get width(): number
set width(w: number): void
```

Width of this Bound

<a id="pt-bound-x"></a>
##### `x`

```ts
get x(): number | undefined
```

First value of the Bound's top-left position

<a id="pt-bound-y"></a>
##### `y`

```ts
get y(): number | undefined
```

Second value of the Bound's top-left position

<a id="pt-bound-z"></a>
##### `z`

```ts
get z(): number | undefined
```

Third value of the Bound's top-left position

#### Methods

<a id="pt-bound-clone"></a>
##### `clone`

*overrides `Group.clone`*

```ts
clone(): Bound
```

Clone this bound and return a new one.

<a id="pt-bound-init"></a>
##### `init`

*protected*

```ts
init(): void
```

Initiate the bound's properties.

<a id="pt-bound-update"></a>
##### `update`

```ts
update(): Bound
```

If the Bound's Pts are changed, call this function to update the Bound's properties.
It's simpler and preferable to change the Bound's properties (eg, topLeft, bottomRight) instead of updating the Bound's Pts.
Note that this recomputes from the current corner Pts in place; it does not replace them with fresh instances.

<a id="pt-bound-static-from-bounding-rect"></a>
##### `fromBoundingRect`

*static*

```ts
static fromBoundingRect(rect: ClientRect): Bound
```

Create a Bound from a [`ClientRect`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect) object.

**Parameters**

- `rect` (`ClientRect`) — an object that has {top, left, bottom, right, width, height} properties

**Returns:** a Bound object

<a id="pt-bound-static-from-group"></a>
##### `fromGroup`

*static*

```ts
static fromGroup(g: PtLikeIterable): Bound
```

Create a Bound from a Group or an array of Pts

**Parameters**

- `g` (`PtLikeIterable`) — a Group or an Iterable<PtLike>

#### Inherited API

- From [`Group`](#pt-group): [`id`](#pt-group-id), [`p1`](#pt-group-p1), [`p2`](#pt-group-p2), [`p3`](#pt-group-p3), [`p4`](#pt-group-p4), [`q1`](#pt-group-q1), [`q2`](#pt-group-q2), [`q3`](#pt-group-q3), [`q4`](#pt-group-q4), [`$matrixAdd`](#pt-group-dollar-matrix-add), [`$matrixMultiply`](#pt-group-dollar-matrix-multiply), [`$zip`](#pt-group-dollar-zip), [`add`](#pt-group-add), [`anchorFrom`](#pt-group-anchor-from), [`anchorTo`](#pt-group-anchor-to), [`boundingBox`](#pt-group-bounding-box), [`centroid`](#pt-group-centroid), [`divide`](#pt-group-divide), [`forEachPt`](#pt-group-for-each-pt), [`insert`](#pt-group-insert), [`interpolate`](#pt-group-interpolate), [`lines`](#pt-group-lines), [`moveBy`](#pt-group-move-by), [`moveTo`](#pt-group-move-to), [`multiply`](#pt-group-multiply), [`op`](#pt-group-op), [`ops`](#pt-group-ops), [`reflect2D`](#pt-group-reflect2-d), [`remove`](#pt-group-remove), [`rotate2D`](#pt-group-rotate2-d), [`scale`](#pt-group-scale), [`segments`](#pt-group-segments), [`shear2D`](#pt-group-shear2-d), [`sortByDimension`](#pt-group-sort-by-dimension), [`split`](#pt-group-split), [`subtract`](#pt-group-subtract), [`toBound`](#pt-group-to-bound), [`toString`](#pt-group-to-string), [`zipSlice`](#pt-group-zip-slice), [`fromArray`](#pt-group-static-from-array), [`fromPtArray`](#pt-group-static-from-pt-array).
- From [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array): 21 standard properties and methods (not repeated here).

<a id="pt-group"></a>
### `Group`

**Kind:** Class · **Source:** [`src/Pt.ts:570`](https://github.com/williamngan/pts/blob/master/src/Pt.ts#L570)

**Extends:** `Array`

A Group is a subclass of standard javascript [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array). It should only contain Pt instances. You can think of it as an array of Float32Arrays.
See [Group guide](https://ptsjs.org/guide/Group-0300.html) for details.

#### Constructors

<a id="pt-group-constructor"></a>
##### Constructor

```ts
new Group(args: Pt[]): Group
```

Create a Group by passing an array of [`Pt`](#pt-pt). You may also create a Group using [`Group.fromArray`](#pt-group-static-from-array) or [`Group.fromPtArray`](#pt-group-static-from-pt-array).

**Parameters**

- `args` (`Pt[]`) — an array of Pts

#### Accessors

<a id="pt-group-id"></a>
##### `id`

```ts
get id(): string
set id(s: string): void
```

ID string of this Group

<a id="pt-group-p1"></a>
##### `p1`

```ts
get p1(): Pt
```

The first Pt in this Group

<a id="pt-group-p2"></a>
##### `p2`

```ts
get p2(): Pt
```

The second Pt in this Group

<a id="pt-group-p3"></a>
##### `p3`

```ts
get p3(): Pt
```

The third Pt in this Group

<a id="pt-group-p4"></a>
##### `p4`

```ts
get p4(): Pt
```

The forth Pt in this Group

<a id="pt-group-q1"></a>
##### `q1`

```ts
get q1(): Pt
```

The last Pt in this Group

<a id="pt-group-q2"></a>
##### `q2`

```ts
get q2(): Pt
```

The second-last Pt in this Group

<a id="pt-group-q3"></a>
##### `q3`

```ts
get q3(): Pt
```

The third-last Pt in this Group

<a id="pt-group-q4"></a>
##### `q4`

```ts
get q4(): Pt
```

The forth-last Pt in this Group

#### Methods

<a id="pt-group-dollar-matrix-add"></a>
##### `$matrixAdd`

```ts
$matrixAdd(g: number | GroupLike | number[][]): Group
```

Apply this group as a matrix and calculate matrix addition.

**Parameters**

- `g` (`number | GroupLike | number[][]`) — a scalar number, an array of numeric arrays, or a group of Pt

**Returns:** a new Group

<a id="pt-group-dollar-matrix-multiply"></a>
##### `$matrixMultiply`

```ts
$matrixMultiply(g: number | GroupLike, transposed: boolean = false, elementwise: boolean = false): Group
```

Apply this group as a matrix and calculate matrix multiplication.

**Parameters**

- `g` (`number | GroupLike`) — a scalar number, an array of numeric arrays, or a Group of K Pts, each with N dimensions (K-rows, N-columns) -- or if transposed is true, then N Pts with K dimensions
- `transposed` (`boolean`; default `false`) — (Only applicable if it's not elementwise multiplication) If true, then a and b's columns should match (ie, each Pt should have the same dimensions). Default is `false`.
- `elementwise` (`boolean`; default `false`) — if true, then the multiplication is done element-wise. Default is `false`.

**Returns:** If not elementwise, this will return a new  Group with M Pt, each with N dimensions (M-rows, N-columns).

<a id="pt-group-dollar-zip"></a>
##### `$zip`

```ts
$zip(defaultValue: number | boolean | undefined = undefined, useLongest: boolean = false): Group
```

Zip a group of Pt. eg, [[1,2],[3,4],[5,6]] => [[1,3,5],[2,4,6]].

**Parameters**

- `defaultValue` (`number | boolean | undefined`; default `undefined`) — a default value to fill if index out of bound. If not provided, it will throw an error instead.
- `useLongest` (`boolean`; default `false`) — If true, find the longest list of values in a Pt and use its length for zipping. Default is false, which uses the first item's length for zipping.

<a id="pt-group-add"></a>
##### `add`

```ts
add(args: any[]): this
```

Add scalar or vector values to this group's Pts.

**Parameters**

- `args` (`any[]`) — can be either a list of numbers, an array, a Pt, or an object with {x,y,z,w} properties

<a id="pt-group-anchor-from"></a>
##### `anchorFrom`

```ts
anchorFrom(ptOrIndex: number | PtLike = 0): void
```

Anchor all the Pts in this Group by its absolute position from a target Pt. (ie, add all Pt with the target anchor to get an absolute position).  All the Pts' values will be updated.

**Parameters**

- `ptOrIndex` (`number | PtLike`; default `0`) — a Pt, or a numeric index to target a specific Pt in this Group

<a id="pt-group-anchor-to"></a>
##### `anchorTo`

```ts
anchorTo(ptOrIndex: number | PtLike = 0): void
```

Anchor all the Pts in this Group using a target Pt as origin. (ie, subtract all Pt with the target anchor to get a relative position). All the Pts' values will be updated.

**Parameters**

- `ptOrIndex` (`number | PtLike`; default `0`) — a Pt, or a numeric index to target a specific Pt in this Group

<a id="pt-group-bounding-box"></a>
##### `boundingBox`

```ts
boundingBox(): Group
```

Find the rectangular bounding box of this group's Pts.

**Returns:** a Group of 2 Pts representing the top-left and bottom-right of the rectangle

<a id="pt-group-centroid"></a>
##### `centroid`

```ts
centroid(): Pt
```

Find the centroid of this group's Pts, which is the average middle point.

<a id="pt-group-clone"></a>
##### `clone`

```ts
clone(): Group
```

Depp clone this group and its Pts.

<a id="pt-group-divide"></a>
##### `divide`

```ts
divide(args: any[]): this
```

Divide this group's Pts over scalar or vector values (as element-wise).

**Parameters**

- `args` (`any[]`) — can be either a list of numbers, an array, a Pt, or an object with {x,y,z,w} properties

<a id="pt-group-for-each-pt"></a>
##### `forEachPt`

```ts
forEachPt(ptFn: string, args: any[]): this
```

Update each Pt in this Group with an existing Pt function.

**Parameters**

- `ptFn` (`string`) — string name of an existing Pt function. Note that the function must return Pt.
- `args` (`any[]`) — arguments for the function specified in ptFn

<a id="pt-group-insert"></a>
##### `insert`

```ts
insert(pts: PtIterable, index: number = 0): this
```

Insert more Pt into this group.

**Parameters**

- `pts` (`PtIterable`) — a Group or an Iterable<Pt>
- `index` (`number`; default `0`) — the index position to insert into

<a id="pt-group-interpolate"></a>
##### `interpolate`

```ts
interpolate(t: number): Pt
```

Get an interpolated point on the line segments defined by this Group.

**Parameters**

- `t` (`number`) — a value between 0 to 1 usually

<a id="pt-group-lines"></a>
##### `lines`

```ts
lines(): Group[]
```

Get all the line segments (ie, edges in a graph) of this group.

<a id="pt-group-move-by"></a>
##### `moveBy`

```ts
moveBy(args: any[]): this
```

Move every Pt's position by a specific amount. Same as [`Group.add`](#pt-group-add).

**Parameters**

- `args` (`any[]`) — can be either a list of numbers, an array, a Pt, or an object with {x,y,z,w} properties

<a id="pt-group-move-to"></a>
##### `moveTo`

```ts
moveTo(args: any[]): this
```

Move the first Pt in this group to a specific position, and move all the other Pts correspondingly.

**Parameters**

- `args` (`any[]`) — can be either a list of numbers, an array, a Pt, or an object with {x,y,z,w} properties

<a id="pt-group-multiply"></a>
##### `multiply`

```ts
multiply(args: any[]): this
```

Multiply scalar or vector values (as element-wise) with this group's Pts.

**Parameters**

- `args` (`any[]`) — can be either a list of numbers, an array, a Pt, or an object with {x,y,z,w} properties

<a id="pt-group-op"></a>
##### `op`

```ts
op(fn:  Fn(g1:PtIterable, rest:any[])):  Fn(rest:any[])
```

Create an operation using this Group, passing this Group into a custom function's first parameter.  See the [Op guide](https://ptsjs.org/guide/Op-0400.html) for details.

**Parameters**

- `fn` (` Fn(g1:PtIterable, rest:any[])`) — any function that takes a Group as its first parameter

**Returns:** a resulting function that takes other parameters required in `fn`

**Example**

```ts
let myOp = group.op( fn ); let result = myOp( [1,2,3] );
```

<a id="pt-group-ops"></a>
##### `ops`

```ts
ops(fns:  Fn(g1:PtIterable, rest:any[])[]):  Fn(rest:any[])[]
```

This combines a series of operations into an array. See the [Op guide](https://ptsjs.org/guide/Op-0400.html) for details.

**Parameters**

- `fns` (` Fn(g1:PtIterable, rest:any[])[]`) — an array of functions for `op`

**Returns:** an array of resulting functions

**Example**

```ts
let myOps = pt.ops([fn1, fn2, fn3]); let results = myOps.map( (op) => op([1,2,3]) );
```

<a id="pt-group-reflect2-d"></a>
##### `reflect2D`

```ts
reflect2D(line: PtLikeIterable, axis: string): this
```

Reflect this group's Pts along a 2D line. Default anchor point is the first Pt in this group.

**Parameters**

- `line` (`PtLikeIterable`) — a Group or an Iterable<PtLike> with 2 Pt that defines a line for reflection
- `axis` (`string`) — optional axis such as "yz" to define a 2D plane of reflection

<a id="pt-group-remove"></a>
##### `remove`

```ts
remove(index: number = 0, count: number = 1): Group
```

Like Array's splice function, with support for negative index and a friendlier name.

**Parameters**

- `index` (`number`; default `0`) — start index, which can be negative (where -1 is at index 0, -2 at index 1, etc)
- `count` (`number`; default `1`) — number of items to remove

**Returns:** The items that are removed.

<a id="pt-group-rotate2-d"></a>
##### `rotate2D`

```ts
rotate2D(angle: number, anchor: PtLike, axis: string): this
```

Rotate this group's Pt from an anchor point in 2D. Default anchor point is the first Pt in this group.

**Parameters**

- `angle` (`number`) — rotate angle
- `anchor` (`PtLike`) — optional anchor point to scale from
- `axis` (`string`) — optional string such as "yz" to specify a 2D plane

<a id="pt-group-scale"></a>
##### `scale`

```ts
scale(scale: number | PtLike, anchor: PtLike): this
```

Scale this group's Pts from an anchor point. Default anchor point is the first Pt in this group.

**Parameters**

- `scale` (`number | PtLike`) — scale ratio
- `anchor` (`PtLike`) — optional anchor point to scale from

<a id="pt-group-segments"></a>
##### `segments`

```ts
segments(pts_per_segment: number = 2, stride: number = 1, loopBack: boolean = false): Group[]
```

Split this group into an array of sub-group segments.

**Parameters**

- `pts_per_segment` (`number`; default `2`) — number of Pts in each segment
- `stride` (`number`; default `1`) — forward-step to take
- `loopBack` (`boolean`; default `false`) — if `true`, always go through the array till the end and loop back to the beginning to complete the segments if needed

<a id="pt-group-shear2-d"></a>
##### `shear2D`

```ts
shear2D(scale: number | PtLike, anchor: PtLike, axis: string): this
```

Shear this group's Pt from an anchor point in 2D. Default anchor point is the first Pt in this group.

**Parameters**

- `scale` (`number | PtLike`) — shearing value which can be a number or an array of 2 numbers
- `anchor` (`PtLike`) — optional anchor point to scale from
- `axis` (`string`) — optional string such as "yz" to specify a 2D plane

<a id="pt-group-sort-by-dimension"></a>
##### `sortByDimension`

```ts
sortByDimension(dim: number, desc: boolean = false): this
```

Sort this group's Pts by values in a specific dimension.

**Parameters**

- `dim` (`number`) — dimensional index
- `desc` (`boolean`; default `false`) — if true, sort descending. Default is false (ascending)

<a id="pt-group-split"></a>
##### `split`

```ts
split(chunkSize: number, stride: number, loopBack: boolean = false): Group[]
```

Split this Group into an array of sub-groups.

**Parameters**

- `chunkSize` (`number`) — number of items per sub-group
- `stride` (`number`) — forward-steps after each sub-group
- `loopBack` (`boolean`; default `false`) — if `true`, always go through the array till the end and loop back to the beginning to complete the segments if needed

<a id="pt-group-subtract"></a>
##### `subtract`

```ts
subtract(args: any[]): this
```

Subtract scalar or vector values from this group's Pts.

**Parameters**

- `args` (`any[]`) — can be either a list of numbers, an array, a Pt, or an object with {x,y,z,w} properties

<a id="pt-group-to-bound"></a>
##### `toBound`

```ts
toBound(): Bound
```

Get a Bound instance of this group

<a id="pt-group-to-string"></a>
##### `toString`

*overrides `Array.toString`*

```ts
toString(): string
```

Get a string representation of this group.

<a id="pt-group-zip-slice"></a>
##### `zipSlice`

```ts
zipSlice(index: number, defaultValue: number | boolean = false): Pt
```

Zip one slice of an array of Pt. Imagine the Pts are organized in rows, then this function will take the values in a specific column.

**Parameters**

- `index` (`number`) — index to zip at
- `defaultValue` (`number | boolean`; default `false`) — a default value to fill if index out of bound. If not provided, it will throw an error instead.

<a id="pt-group-static-from-array"></a>
##### `fromArray`

*static*

```ts
static fromArray(list: PtLikeIterable): Group
```

Convert an array of numeric arrays into a Group.

**Parameters**

- `list` (`PtLikeIterable`) — an Iterable<PtLike> such as an array or a generator (of PtLike numeric arrays)

**Example**

```ts
Group.fromArray( [[1,2], [3,4], [5,6]] )
```

<a id="pt-group-static-from-pt-array"></a>
##### `fromPtArray`

*static*

```ts
static fromPtArray(list: PtIterable): Group
```

Convert an Array/Iterable of Pt into a Group.

**Parameters**

- `list` (`PtIterable`) — an Iterable<Pt>

#### Inherited API

- From [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array): 31 standard properties and methods (not repeated here).

<a id="pt-pt"></a>
### `Pt`

**Kind:** Class · **Source:** [`src/Pt.ts:18`](https://github.com/williamngan/pts/blob/master/src/Pt.ts#L18)

**Extends:** `Float32Array`

**Implements:** `IPt`, `Iterable`

Pt is a subclass of standard [`Float32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array) with additional properties and functions to support vector and geometric calculations.
See [Pt guide](https://ptsjs.org/guide/Pt-0200.html) for details.

#### Constructors

<a id="pt-pt-constructor"></a>
##### Constructor

```ts
new Pt(args: (number | number[] | Float32Array | IPt)[]): Pt
```

Create a Pt. If no parameter is provided, this will instantiate a Pt with 2 dimensions [0, 0].
Note that `new Pt(3)` will only instantiate Pt with length of 3 (ie, same as `new Float32Array(3)` ). If you need a Pt with 1 dimension of value 3, use `new Pt([3])`.

**Parameters**

- `args` (`(number | number[] | Float32Array | IPt)[]`) — a list of numeric parameters, an array of numbers, or an object with {x,y,z,w} properties

**Example**

```ts
new Pt()`, `new Pt(1,2,3,4,5)`, `new Pt([1,2])`, `new Pt({x:0, y:1})`, `new Pt(pt)
```

#### Accessors

<a id="pt-pt-id"></a>
##### `id`

```ts
get id(): string
set id(s: string): void
```

ID string of this Pt

<a id="pt-pt-w"></a>
##### `w`

```ts
get w(): number
set w(n: number): void
```

Value in the forth dimension of this Pt

<a id="pt-pt-x"></a>
##### `x`

```ts
get x(): number
set x(n: number): void
```

Value in the first dimensional of this Pt

<a id="pt-pt-y"></a>
##### `y`

```ts
get y(): number
set y(n: number): void
```

Value in the second dimension of this Pt

<a id="pt-pt-z"></a>
##### `z`

```ts
get z(): number
set z(n: number): void
```

Value in the third dimension of this Pt

#### Methods

<a id="pt-pt-dollar-abs"></a>
##### `$abs`

```ts
$abs(): Pt
```

Get a new Pt with absolute values of this Pt.

<a id="pt-pt-dollar-add"></a>
##### `$add`

```ts
$add(args: any[]): Pt
```

Like [`Pt.add`](#pt-pt-add), but returns result as a new Pt.

**Parameters**

- `args` (`any[]`) — can be either a list of numbers, an array, a Pt, or an object with {x,y,z,w} properties

<a id="pt-pt-dollar-ceil"></a>
##### `$ceil`

```ts
$ceil(): Pt
```

Get a new Pt with ceiling values of this Pt.

<a id="pt-pt-dollar-concat"></a>
##### `$concat`

```ts
$concat(args: any[]): Pt
```

Concatenate this Pt with addition dimensional values and return as a new Pt.

**Parameters**

- `args` (`any[]`) — can be either a list of numbers, an array, a Pt,  or an object with {x,y,z,w} properties

<a id="pt-pt-dollar-cross"></a>
##### `$cross`

```ts
$cross(args: any[]): Pt
```

3D Cross product of this Pt and another Pt. Return results as a new Pt.

**Parameters**

- `args` (`any[]`) — can be either a list of numbers, an array, a Pt, or an object with {x,y,z,w} properties

<a id="pt-pt-dollar-cross2-d"></a>
##### `$cross2D`

```ts
$cross2D(args: any[]): number
```

2D Cross product of this Pt and another Pt. Return results as a new Pt.

**Parameters**

- `args` (`any[]`) — can be either a list of numbers, an array, a Pt, or an object with {x,y,z,w} properties

<a id="pt-pt-dollar-divide"></a>
##### `$divide`

```ts
$divide(args: any[]): Pt
```

Like [`Pt.divide`](#pt-pt-divide), but returns result as a new Pt.

**Parameters**

- `args` (`any[]`) — can be either a list of numbers, an array, a Pt, or an object with {x,y,z,w} properties

<a id="pt-pt-dollar-floor"></a>
##### `$floor`

```ts
$floor(): Pt
```

Get a new Pt with floor values of this Pt.

<a id="pt-pt-dollar-max"></a>
##### `$max`

```ts
$max(args: any[]): Pt
```

Get a new Pt that has the maximum dimensional values of this Pt and another Pt.

**Parameters**

- `args` (`any[]`) — can be either a list of numbers, an array, a Pt, or an object with {x,y,z,w} properties

<a id="pt-pt-dollar-min"></a>
##### `$min`

```ts
$min(args: any[]): Pt
```

Get a new Pt that has the minimum dimensional values of this Pt and another Pt.

**Parameters**

- `args` (`any[]`) — can be either a list of numbers, an array, a Pt, or an object with {x,y,z,w} properties

<a id="pt-pt-dollar-multiply"></a>
##### `$multiply`

```ts
$multiply(args: any[]): Pt
```

Like [`Pt.multiply`](#pt-pt-multiply), but returns result as a new Pt.

**Parameters**

- `args` (`any[]`) — can be either a list of numbers, an array, a Pt, or an object with {x,y,z,w} properties

<a id="pt-pt-dollar-project"></a>
##### `$project`

```ts
$project(args: any[]): Pt
```

Calculate the vector projection of another Pt onto this Pt — ie, the component of the other Pt along this Pt's direction. Note that this Pt must be non-zero.

**Parameters**

- `args` (`any[]`) — the other Pt, as either a list of numbers, an array, a Pt, or an object with {x,y,z,w} properties

**Returns:** the projection vector as a Pt

<a id="pt-pt-dollar-round"></a>
##### `$round`

```ts
$round(): Pt
```

Get a new Pt with rounded values of this Pt.

<a id="pt-pt-dollar-subtract"></a>
##### `$subtract`

```ts
$subtract(args: any[]): Pt
```

Like [`Pt.subtract`](#pt-pt-subtract), but returns result as a new Pt.

**Parameters**

- `args` (`any[]`) — can be either a list of numbers, an array, a Pt, or an object with {x,y,z,w} properties

<a id="pt-pt-dollar-take"></a>
##### `$take`

```ts
$take(axis: string | number[]): Pt
```

Take specific dimensional values from this Pt and create a new Pt.

**Parameters**

- `axis` (`string | number[]`) — a string such as "xy" (use Const.xy) or an array to specify indices

<a id="pt-pt-dollar-to"></a>
##### `$to`

```ts
$to(args: any[]): Pt
```

Like [`Pt.to`](#pt-pt-to) but returns a new Pt.

**Parameters**

- `args` (`any[]`) — can be either a list of numbers, an array, a Pt, or an object with {x,y,z,w} properties

<a id="pt-pt-dollar-unit"></a>
##### `$unit`

```ts
$unit(magnitude: number | undefined = undefined): Pt
```

Get a new unit vector from this Pt.

**Parameters**

- `magnitude` (`number | undefined`; default `undefined`)

<a id="pt-pt-abs"></a>
##### `abs`

```ts
abs(): Pt
```

Absolute values for all values in this pt.

<a id="pt-pt-add"></a>
##### `add`

```ts
add(args: any[]): this
```

Add scalar or vector values to this Pt.

**Parameters**

- `args` (`any[]`) — can be either a list of numbers, an array, a Pt, or an object with {x,y,z,w} properties

<a id="pt-pt-angle"></a>
##### `angle`

```ts
angle(axis: string | number[] = Const.xy): number
```

Get angle of this Pt from origin.

**Parameters**

- `axis` (`string | number[]`; default `Const.xy`) — a string such as "xy" (use Const.xy) or an array to specify index for two dimensions

<a id="pt-pt-angle-between"></a>
##### `angleBetween`

```ts
angleBetween(p: Pt, axis: string | number[] = Const.xy): number
```

Get the signed angle between this and another Pt, normalized to [-π, π).

**Parameters**

- `p` (`Pt`) — the other Pt
- `axis` (`string | number[]`; default `Const.xy`) — a string such as "xy" (use Const.xy) or an array to specify index for two dimensions

<a id="pt-pt-ceil"></a>
##### `ceil`

```ts
ceil(): Pt
```

Ceiling values for all values in this Pt.

<a id="pt-pt-clone"></a>
##### `clone`

```ts
clone(): Pt
```

Clone this Pt and return it as a new Pt.

<a id="pt-pt-divide"></a>
##### `divide`

```ts
divide(args: any[]): this
```

Divide this Pt over scalar or vector values (as element-wise).

**Parameters**

- `args` (`any[]`) — can be either a list of numbers, an array, a Pt, or an object with {x,y,z,w} properties

<a id="pt-pt-dot"></a>
##### `dot`

```ts
dot(args: any[]): number
```

Dot product of this Pt and another Pt.

**Parameters**

- `args` (`any[]`) — can be either a list of numbers, an array, a Pt, or an object with {x,y,z,w} properties

<a id="pt-pt-equals"></a>
##### `equals`

```ts
equals(p: PtLike, threshold: number = 0.000001): boolean
```

Check if another Pt is equal to this Pt, within a threshold. Every dimension of this Pt must be matched: a shorter Pt, or one with a NaN dimension, is not equal (following IEEE semantics, NaN never equals NaN).

**Parameters**

- `p` (`PtLike`) — another Pt to compare with
- `threshold` (`number`; default `0.000001`) — a threshold value within which the two Pts are considered equal. Default is 0.000001.

<a id="pt-pt-floor"></a>
##### `floor`

```ts
floor(): Pt
```

Floor values for all values in this Pt.

<a id="pt-pt-magnitude"></a>
##### `magnitude`

```ts
magnitude(): number
```

Get the distance (magnitude) of this Pt from origin.

<a id="pt-pt-magnitude-sq"></a>
##### `magnitudeSq`

```ts
magnitudeSq(): number
```

Get the squared distance (magnitude) of this Pt from origin.

<a id="pt-pt-max-value"></a>
##### `maxValue`

```ts
maxValue(): { index:number, value:number }
```

Find the maximum value across all dimensions in this Pt.

**Returns:** an object with `value` and `index` which returns the maximum value and its dimensional index

<a id="pt-pt-min-value"></a>
##### `minValue`

```ts
minValue(): { index:number, value:number }
```

Find the minimum value across all dimensions in this Pt.

**Returns:** an object with `value` and `index` which returns the minimum value and its dimensional index

<a id="pt-pt-multiply"></a>
##### `multiply`

```ts
multiply(args: any[]): this
```

Multiply scalar or vector values (as element-wise) with this Pt.

**Parameters**

- `args` (`any[]`) — can be either a list of numbers, an array, a Pt, or an object with {x,y,z,w} properties

<a id="pt-pt-op"></a>
##### `op`

```ts
op(fn:  Fn(p1:PtLike, rest:any[])):  Fn(rest:any[])
```

Create an operation using this Pt, passing this Pt into a custom function's first parameter. See the [Op guide](https://ptsjs.org/guide/Op-0400.html) for details.

**Parameters**

- `fn` (` Fn(p1:PtLike, rest:any[])`) — any function that takes a Pt as its first parameter

**Returns:** a resulting function that takes other parameters required in `fn`

**Example**

```ts
let myOp = pt.op( fn ); let result = myOp( [1,2,3] );
```

<a id="pt-pt-ops"></a>
##### `ops`

```ts
ops(fns:  Fn(p1:PtLike, rest:any[])[]):  Fn(rest:any[])[]
```

This combines a series of operations into an array. See the [Op guide](https://ptsjs.org/guide/Op-0400.html) for details.

**Parameters**

- `fns` (` Fn(p1:PtLike, rest:any[])[]`) — an array of functions for `op`

**Returns:** an array of resulting functions

**Example**

```ts
let myOps = pt.ops([fn1, fn2, fn3]); let results = myOps.map( (op) => op([1,2,3]) );
```

<a id="pt-pt-project-scalar"></a>
##### `projectScalar`

```ts
projectScalar(args: any[]): number
```

Calculate the scalar projection of another Pt onto this Pt — the signed length of the other Pt's component along this Pt's direction. Note that this Pt must be non-zero.

**Parameters**

- `args` (`any[]`) — the other Pt, as either a list of numbers, an array, a Pt, or an object with {x,y,z,w} properties

<a id="pt-pt-reflect2-d"></a>
##### `reflect2D`

```ts
reflect2D(line: GroupLike, axis: string): this
```

Reflect this Pt along a 2D line.

**Parameters**

- `line` (`GroupLike`) — a Group of 2 Pts that defines a line for reflection
- `axis` (`string`) — optional axis such as "yz" to define a 2D plane of reflection

<a id="pt-pt-rotate2-d"></a>
##### `rotate2D`

```ts
rotate2D(angle: number, anchor: PtLike, axis: string): Pt
```

Rotate this Pt from origin or from an anchor point in 2D.

**Parameters**

- `angle` (`number`) — rotate angle
- `anchor` (`PtLike`) — optional anchor point to scale from
- `axis` (`string`) — optional string such as "yz" to specify a 2D plane

<a id="pt-pt-round"></a>
##### `round`

```ts
round(): Pt
```

Rounded values for all values in this Pt.

<a id="pt-pt-scale"></a>
##### `scale`

```ts
scale(scale: number | PtLike, anchor: PtLike): Pt
```

Scale this Pt from origin or from an anchor point.

**Parameters**

- `scale` (`number | PtLike`) — scale ratio
- `anchor` (`PtLike`) — optional anchor point to scale from

<a id="pt-pt-shear2-d"></a>
##### `shear2D`

```ts
shear2D(scale: number | PtLike, anchor: PtLike, axis: string): Pt
```

Shear this Pt from origin or from an anchor point in 2D.

**Parameters**

- `scale` (`number | PtLike`) — shearing value which can be a number or an array of 2 numbers
- `anchor` (`PtLike`) — optional anchor point to scale from
- `axis` (`string`) — optional string such as "yz" to specify a 2D plane

<a id="pt-pt-subtract"></a>
##### `subtract`

```ts
subtract(args: any[]): this
```

Subtract scalar or vector values from this Pt.

**Parameters**

- `args` (`any[]`) — can be either a list of numbers, an array, a Pt, or an object with {x,y,z,w} properties

<a id="pt-pt-to"></a>
##### `to`

```ts
to(args: any[]): this
```

Update the values of this Pt.

**Parameters**

- `args` (`any[]`) — can be either a list of numbers, an array, a Pt, or an object with {x,y,z,w} properties

<a id="pt-pt-to-angle"></a>
##### `toAngle`

```ts
toAngle(radian: number, magnitude: number, anchorFromPt: boolean = false): this
```

Update the values of this Pt to point at a specific angle.

**Parameters**

- `radian` (`number`) — target angle in radian
- `magnitude` (`number`) — Optional magnitude if known. If not provided, it'll calculate and use this Pt's magnitude.
- `anchorFromPt` (`boolean`; default `false`) — If `true`, add it from this Pt's current position. Default is `false` which update the position from origin (0,0). See also [`Geom.rotate2D`](#num-geom-static-rotate2-d) for rotating a point from another anchor point.

<a id="pt-pt-to-array"></a>
##### `toArray`

```ts
toArray(): number[]
```

Convert this Pt to a javascript Array.

<a id="pt-pt-to-bound"></a>
##### `toBound`

```ts
toBound(): Bound
```

Convert this Pt to a Bound as new Group([0,...], pt)

<a id="pt-pt-to-group"></a>
##### `toGroup`

```ts
toGroup(): Group
```

Convert this Pt to a Group as new Group([0,...], pt)

<a id="pt-pt-to-string"></a>
##### `toString`

*overrides `Float32Array.toString`*

```ts
toString(): string
```

A string representation of this Pt. Eg, "Pt(1, 2, 3)".

<a id="pt-pt-unit"></a>
##### `unit`

```ts
unit(magnitude: number | undefined = undefined): Pt
```

Convert to a unit vector, which is a normalized vector whose magnitude equals to 1.

**Parameters**

- `magnitude` (`number | undefined`; default `undefined`) — Optional: if the magnitude is known, pass it as a parameter to avoid duplicate calculation.

<a id="pt-pt-static-make"></a>
##### `make`

*static*

```ts
static make(dimensions: number, defaultValue: number = 0, randomize: boolean = false): Pt
```

Create an n-dimensional Pt with either default value or random values.

**Parameters**

- `dimensions` (`number`) — number of dimensions
- `defaultValue` (`number`; default `0`) — optional default value to fill the dimensions
- `randomize` (`boolean`; default `false`) — if `true`, randomize the value between 0 to default value

#### Inherited API

- From [`Float32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array): 32 standard properties and methods (not repeated here).

<a id="module-space"></a>
## Module: `Space`

<a id="space-multitouchspace"></a>
### `MultiTouchSpace`

**Kind:** Class · **Source:** [`src/Space.ts:353`](https://github.com/williamngan/pts/blob/master/src/Space.ts#L353)

**Extends:** `Space`

MultiTouchSpace is an abstract class that extends [`Space`](#space-space) to support user interactions via touch events.
It's extended through subclasses such as [`CanvasSpace`](#canvas-canvasspace) and [`SVGSpace`](#svg-svgspace).

#### Accessors

<a id="space-multitouchspace-pointer"></a>
##### `pointer`

*public*

```ts
get pointer(): Pt
```

Get the mouse or touch pointer that stores the last action.

#### Methods

<a id="space-multitouchspace-bind-canvas"></a>
##### `bindCanvas`

```ts
bindCanvas(evt: string, callback: EventListener, options: any = {}, customTarget: Element): void
```

Bind event listener in canvas element. You can also use [`MultiTouchSpace.bindMouse`](#space-multitouchspace-bind-mouse) or [`MultiTouchSpace.bindTouch`](#space-multitouchspace-bind-touch) to bind mouse or touch events conveniently.

**Parameters**

- `evt` (`string`) — an event string such as "mousedown"
- `callback` (`EventListener`) — callback function for this event
- `options` (`any`; default `{}`) — options for [addEventListener](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener).
- `customTarget` (`Element`) — an optional event target to use instead of the canvas element

<a id="space-multitouchspace-bind-doc"></a>
##### `bindDoc`

```ts
bindDoc(evt: string, callback: EventListener, options: any = {}): void
```

**Parameters**

- `evt` (`string`)
- `callback` (`EventListener`)
- `options` (`any`; default `{}`)

<a id="space-multitouchspace-bind-keyboard"></a>
##### `bindKeyboard`

```ts
bindKeyboard(bind: boolean = true, customTarget: EventTarget): this
```

Bind or unbind keyboard events. Events are attached to `document` by
default, or to `customTarget` when one is provided.

**Parameters**

- `bind` (`boolean`; default `true`)
- `customTarget` (`EventTarget`)

<a id="space-multitouchspace-bind-mouse"></a>
##### `bindMouse`

```ts
bindMouse(bind: boolean = true, customTarget: Element): this
```

A convenient method to bind (or unbind) all mouse events in canvas element.
All [`IPlayer`](#types-iplayer) objects added to this space that implement an `action` callback property will receive mouse event callbacks.
Mouse action names are defined by [`UIPointerActions`](#ui-uipointeractions), including "up", "down", "move", "drag", "drop", "over", "out", "click", "pointerdown", "pointerup", and "contextmenu".

**Parameters**

- `bind` (`boolean`; default `true`) — a boolean value to bind mouse events if set to `true`. If `false`, all mouse events will be unbound. Default is true.
- `customTarget` (`Element`) — an optional event target to use instead of the canvas element

**See also:** [`Space.add`](#space-space-add)

<a id="space-multitouchspace-bind-touch"></a>
##### `bindTouch`

```ts
bindTouch(bind: boolean = true, passive: boolean = false, customTarget: Element): this
```

A convenient method to bind (or unbind) all touch events in canvas element.
All [`IPlayer`](#types-iplayer) objects added to this space that implement an `action` callback property will receive touch event callbacks.
Touch action names are defined by [`UIPointerActions`](#ui-uipointeractions), including "up", "down", "move", "drag", "drop", "over", and "out".

**Parameters**

- `bind` (`boolean`; default `true`) — a boolean value to bind touch events if set to `true`. If `false`, all touch events will be unbound. Default is true.
- `passive` (`boolean`; default `false`) — a boolean value to set passive mode, ie, it won't block scrolling. Default is false.
- `customTarget` (`Element`) — an optional event target to use instead of the canvas element

**See also:** [`Space.add`](#space-space-add)

<a id="space-multitouchspace-remove-all"></a>
##### `removeAll`

*overrides `Space.removeAll`*

```ts
removeAll(): this
```

Remove all players and the UI registrations forwarded by them.

<a id="space-multitouchspace-touches-to-points"></a>
##### `touchesToPoints`

```ts
touchesToPoints(evt: TouchEvent, which: TouchPointsKey = "touches"): Pt[]
```

A convenient method to convert the touch points in a touch event to an array of Pts.

**Parameters**

- `evt` (`TouchEvent`) — a touch event which contains touches, changedTouches, and targetTouches list
- `which` (`TouchPointsKey`; default `"touches"`) — a string to select a touches list: "touches", "changedTouches", or "targetTouches". Default is "touches"

**Returns:** an array of Pt, whose origin position (0,0) is offset to the top-left of this space

<a id="space-multitouchspace-track"></a>
##### `track`

```ts
track(uis: UI | UI[]): this
```

Track one or more [`UI`](#ui-ui) elements: every pointer, touch, and keyboard
action dispatched by this space is forwarded to them via [`UI.track`](#ui-ui-static-track),
so no manual `action` wiring is needed. Remember to also bind the events,
eg via [`MultiTouchSpace.bindMouse`](#space-multitouchspace-bind-mouse). Keyboard actions are forwarded
too (their x/y carry the shift/alt flags, as the space dispatches them).

**Parameters**

- `uis` (`UI | UI[]`) — a UI, or an array of UIs

<a id="space-multitouchspace-unbind-canvas"></a>
##### `unbindCanvas`

```ts
unbindCanvas(evt: string, callback: EventListener, options: any = {}, customTarget: Element): void
```

Unbind a callback from the event listener.

**Parameters**

- `evt` (`string`) — an event string such as "mousedown"
- `callback` (`EventListener`) — callback function to unbind
- `options` (`any`; default `{}`) — options for [removeEventListener](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener). This should match the options set in bindCanvas.
- `customTarget` (`Element`) — If customTarget is set in bindCanvas, you'll need to pass the same instance here to unbind

<a id="space-multitouchspace-unbind-doc"></a>
##### `unbindDoc`

```ts
unbindDoc(evt: string, callback: EventListener, options: any = {}): void
```

**Parameters**

- `evt` (`string`)
- `callback` (`EventListener`)
- `options` (`any`; default `{}`)

<a id="space-multitouchspace-untrack"></a>
##### `untrack`

```ts
untrack(uis: UI | UI[]): this
```

Stop tracking one or more [`UI`](#ui-ui) elements added via [`MultiTouchSpace.track`](#space-multitouchspace-track).

**Parameters**

- `uis` (`UI | UI[]`) — a UI or an array of UIs to remove from tracking, or omit to stop tracking all

#### Inherited API

- From [`Space`](#space-space): [`center`](#space-space-center), [`customRendering`](#space-space-custom-rendering), [`height`](#space-space-height), [`innerBound`](#space-space-inner-bound), [`isPlaying`](#space-space-is-playing), [`outerBound`](#space-space-outer-bound), [`size`](#space-space-size), [`width`](#space-space-width), [`add`](#space-space-add), [`clear`](#space-space-clear), [`getForm`](#space-space-get-form), [`minFrameTime`](#space-space-min-frame-time), [`pause`](#space-space-pause), [`play`](#space-space-play), [`playItems`](#space-space-play-items), [`playOnce`](#space-space-play-once), [`refresh`](#space-space-refresh), [`remove`](#space-space-remove), [`render`](#space-space-render), [`replay`](#space-space-replay), [`resize`](#space-space-resize), [`resume`](#space-space-resume), [`stop`](#space-space-stop), [`bound`](#space-space-bound), [`id`](#space-space-id), [`playerCount`](#space-space-player-count), [`players`](#space-space-players).

<a id="space-space"></a>
### `Space`

**Kind:** Class · **Source:** [`src/Space.ts:19`](https://github.com/williamngan/pts/blob/master/src/Space.ts#L19)

Space is an abstract class that represents a general context for expressing Pts. It's extended through subclasses such as [`CanvasSpace`](#canvas-canvasspace) and [`SVGSpace`](#svg-svgspace). You can also create your own extension of Space.
See [Space guide](https://ptsjs.org/guide/Space-0500.html) for details.

#### Accessors

<a id="space-space-center"></a>
##### `center`

```ts
get center(): Pt
```

The center of this space's bounding box.

<a id="space-space-custom-rendering"></a>
##### `customRendering`

```ts
get customRendering():  Fn(context:any, self:Space)
set customRendering(f:  Fn(context:any, self:Space)): void
```

Set a custom rendering function `fn(graphics_context, canvas_space)` if needed.

<a id="space-space-height"></a>
##### `height`

```ts
get height(): number
```

The height of this space's bounding box.

<a id="space-space-inner-bound"></a>
##### `innerBound`

*public*

```ts
get innerBound(): Bound
```

The inner bounding box of the space, excluding its positions.

<a id="space-space-is-playing"></a>
##### `isPlaying`

```ts
get isPlaying(): boolean
```

Indicate whether the animation is playing.

<a id="space-space-outer-bound"></a>
##### `outerBound`

```ts
get outerBound(): Bound
```

The outer bounding box which includes its positions.

<a id="space-space-size"></a>
##### `size`

```ts
get size(): Pt
```

The size of this space's bounding box.

<a id="space-space-width"></a>
##### `width`

```ts
get width(): number
```

The width of this space's bounding box.

#### Methods

<a id="space-space-add"></a>
##### `add`

```ts
add(p: IPlayer | AnimateCallbackFn): this
```

Add an [`IPlayer`](#types-iplayer) object or a [`AnimateCallbackFn`](#types-animatecallbackfn) callback function to handle events in this Space. An IPlayer is an object with the following callback functions:
- required: `animate: fn( time, ftime, space )`
- optional: `start: fn(bound, space)`
- optional: `resize: fn( size, event )`
- optional: `action: fn( type, x, y, event )`
Subclasses of Space may define other callback functions.

**Parameters**

- `p` (`IPlayer | AnimateCallbackFn`) — an [`IPlayer`](#types-iplayer) object with animate function, or a callback function `fn(time, ftime)`.

<a id="space-space-clear"></a>
##### `clear`

*abstract*

```ts
clear(): this
```

clear all contents in the space. To be implemented in subclasses.

<a id="space-space-get-form"></a>
##### `getForm`

*abstract*

```ts
getForm(): Form
```

Get a default form for drawing in this space. To be implemented in subclasses.

<a id="space-space-min-frame-time"></a>
##### `minFrameTime`

```ts
minFrameTime(ms: number = 0): this
```

Set a minimum frame time

**Parameters**

- `ms` (`number`; default `0`) — at least this amount of milliseconds must have elapsed before frame advances

<a id="space-space-pause"></a>
##### `pause`

```ts
pause(toggle: boolean = false): this
```

Pause the animation.

**Parameters**

- `toggle` (`boolean`; default `false`) — a boolean value to set if this function call should be a toggle (between pause and resume)

<a id="space-space-play"></a>
##### `play`

```ts
play(time: number = 0): this
```

Main play loop. This implements `window.requestAnimationFrame` and calls it recursively.
You may override this `play()` function to implement your own animation loop.

**Parameters**

- `time` (`number`; default `0`) — current time

<a id="space-space-play-items"></a>
##### `playItems`

*protected*

```ts
playItems(time: number): void
```

Main animate function. This calls all the items to perform.

**Parameters**

- `time` (`number`) — current time

<a id="space-space-play-once"></a>
##### `playOnce`

```ts
playOnce(duration: number = 0): this
```

Play animation loop once. Optionally set a `duration` time to play for that specific duration.

**Parameters**

- `duration` (`number`; default `0`) — a value in millisecond to specify a time period to play before stopping, or `-1` to play forever

<a id="space-space-refresh"></a>
##### `refresh`

```ts
refresh(b: boolean): this
```

Set whether the rendering should be repainted on each frame.

**Parameters**

- `b` (`boolean`) — a boolean value to set whether to repaint each frame

<a id="space-space-remove"></a>
##### `remove`

```ts
remove(player: IPlayer): this
```

Remove a player from this Space.

**Parameters**

- `player` (`IPlayer`) — an IPlayer that has an `animateID` property

<a id="space-space-remove-all"></a>
##### `removeAll`

```ts
removeAll(): this
```

Remove all players from this Space.

<a id="space-space-render"></a>
##### `render`

*protected*

```ts
render(context: any): this
```

Custom rendering.

**Parameters**

- `context` (`any`) — rendering context

<a id="space-space-replay"></a>
##### `replay`

```ts
replay(): void
```

Replay the animation after [`Space.stop`](#space-space-stop). This resets the end-time counter.
You may also use [`Space.pause`](#space-space-pause) and [`resume`](#space-space-resume) for temporary pause.

<a id="space-space-resize"></a>
##### `resize`

*abstract*

```ts
resize(b: Bound, evt: Event | null): this
```

Resize the space. To be implemented in subclasses.

**Parameters**

- `b` (`Bound`) — a Bound representing the position and size of the space
- `evt` (`Event | null`) — event

<a id="space-space-resume"></a>
##### `resume`

```ts
resume(): this
```

Resume the pause animation.

<a id="space-space-stop"></a>
##### `stop`

```ts
stop(t: number = 0): this
```

Specify when the animation should stop: immediately, after a time period, or never stops.
After stopping, use [`Space.replay`](#space-space-replay) to play again.

**Parameters**

- `t` (`number`; default `0`) — a value in millisecond to specify a time period to play before stopping, or `-1` to play forever, or `0` to end immediately. Default is 0 which will stop the animation immediately.

#### Properties

<a id="space-space-bound"></a>
##### `bound`

*protected*

```ts
bound: Bound
```

<a id="space-space-id"></a>
##### `id`

```ts
id: string
```

<a id="space-space-player-count"></a>
##### `playerCount`

*protected*

```ts
playerCount: number
```

<a id="space-space-players"></a>
##### `players`

*protected*

```ts
players: ISpacePlayers
```

<a id="module-svg"></a>
## Module: `Svg`

<a id="svg-svgcontext2d"></a>
### `SVGContext2D`

**Kind:** Class · **Source:** [`src/Svg.ts:147`](https://github.com/williamngan/pts/blob/master/src/Svg.ts#L147)

**`SVGContext2D`** implements the subset of `CanvasRenderingContext2D` that
[`CanvasForm`](#canvas-canvasform) draws through, and renders it as SVG. Consecutive shapes that share
paint state are merged into single `<path>` elements ("style runs"), so the DOM cost per
frame is proportional to the number of style changes, not the number of shapes. This is
what lets sketches using the supported subset run unchanged on canvas and SVG.

Capability notes: blend-mode composites map to `mix-blend-mode`; Porter-Duff composites,
`clip`, and `putImageData` warn once and no-op. Text metrics come from a hidden canvas, so
`textBox` layout matches canvas exactly. When shapes with both fill and stroke are merged,
all fills in a run paint before its strokes — visible only for overlapping same-styled
shapes.

**Writing your own renderer**: this class is the reference implementation of the rendering
contract — any object implementing the same context surface can be handed to
[`CanvasForm`](#canvas-canvasform)'s constructor to become a Pts renderer (a PDF writer, a command
recorder, a test snapshotter, and so on). The surface is the subset of
`CanvasRenderingContext2D` that `CanvasForm` draws through:
- path verbs: `beginPath`, `moveTo`, `lineTo`, `quadraticCurveTo`, `bezierCurveTo`,
  `rect`, `arc`, `ellipse`, `closePath`
- paint: `fill`, `stroke`, `fillRect`, `clearRect`
- state: `save`, `restore`, `clip`, `scale`
- style fields: `fillStyle`, `strokeStyle`, `lineWidth`, `lineJoin`, `lineCap`,
  `globalAlpha`, `globalCompositeOperation`, `setLineDash`, `lineDashOffset`
- text: `font`, `textAlign`, `textBaseline`, `fillText`, `measureText`
- images: `drawImage`, `putImageData`
- gradients: `createLinearGradient`, `createRadialGradient`

A renderer driven by a Space should also expose a frame lifecycle like
[`SVGContext2D.beginFrame`](#svg-svgcontext2d-begin-frame) / [`SVGContext2D.commitFrame`](#svg-svgcontext2d-commit-frame), called around the
players' animate callbacks. The unit test "implements every context member that CanvasForm
uses" is the compatibility alarm: it fails when a new `CanvasForm` feature touches a
context member a renderer does not implement.

#### Constructors

<a id="svg-svgcontext2d-constructor"></a>
##### Constructor

```ts
new SVGContext2D(host: SVGElement): SVGContext2D
```

**Parameters**

- `host` (`SVGElement`)

#### Accessors

<a id="svg-svgcontext2d-draw-count"></a>
##### `drawCount`

```ts
get drawCount(): number
```

Number of paint calls since `beginFrame` — used to skip empty commits.

<a id="svg-svgcontext2d-group"></a>
##### `group`

```ts
get group(): SVGElement | null
```

The `<g>` element holding this context's rendered output.

<a id="svg-svgcontext2d-runs"></a>
##### `runs`

```ts
get runs(): SVGRun[]
```

The current frame's run list (used by expanded export).

#### Methods

<a id="svg-svgcontext2d-arc"></a>
##### `arc`

```ts
arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, ccw: boolean = false): void
```

**Parameters**

- `x` (`number`)
- `y` (`number`)
- `radius` (`number`)
- `startAngle` (`number`)
- `endAngle` (`number`)
- `ccw` (`boolean`; default `false`)

<a id="svg-svgcontext2d-begin-frame"></a>
##### `beginFrame`

```ts
beginFrame(): void
```

Start a new frame: subsequent draws build a fresh run list.

<a id="svg-svgcontext2d-begin-path"></a>
##### `beginPath`

```ts
beginPath(): void
```

<a id="svg-svgcontext2d-bezier-curve-to"></a>
##### `bezierCurveTo`

```ts
bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void
```

**Parameters**

- `cp1x` (`number`)
- `cp1y` (`number`)
- `cp2x` (`number`)
- `cp2y` (`number`)
- `x` (`number`)
- `y` (`number`)

<a id="svg-svgcontext2d-clear-rect"></a>
##### `clearRect`

```ts
clearRect(): void
```

<a id="svg-svgcontext2d-clip"></a>
##### `clip`

```ts
clip(): void
```

<a id="svg-svgcontext2d-close-path"></a>
##### `closePath`

```ts
closePath(): void
```

<a id="svg-svgcontext2d-commit-frame"></a>
##### `commitFrame`

```ts
commitFrame(): void
```

Commit the frame: reconcile the run list against the pooled elements, patching only
changed attributes, and truncate unused elements.

<a id="svg-svgcontext2d-create-linear-gradient"></a>
##### `createLinearGradient`

```ts
createLinearGradient(x1: number, y1: number, x2: number, y2: number): SVGGradient
```

**Parameters**

- `x1` (`number`)
- `y1` (`number`)
- `x2` (`number`)
- `y2` (`number`)

<a id="svg-svgcontext2d-create-radial-gradient"></a>
##### `createRadialGradient`

```ts
createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): SVGGradient
```

**Parameters**

- `x0` (`number`)
- `y0` (`number`)
- `r0` (`number`)
- `x1` (`number`)
- `y1` (`number`)
- `r1` (`number`)

<a id="svg-svgcontext2d-dispose-dom"></a>
##### `disposeDom`

```ts
disposeDom(): void
```

Remove this context's managed elements from the DOM and forget them. Used when a space
is disposed so that a re-mounted space on the same element starts clean.

<a id="svg-svgcontext2d-draw-image"></a>
##### `drawImage`

```ts
drawImage(img: CanvasImageSource, x: number, y: number, w: number, h: number, rest: number[]): void
```

**Parameters**

- `img` (`CanvasImageSource`)
- `x` (`number`)
- `y` (`number`)
- `w` (`number`)
- `h` (`number`)
- `rest` (`number[]`)

<a id="svg-svgcontext2d-ellipse"></a>
##### `ellipse`

```ts
ellipse(x: number, y: number, rx: number, ry: number, rotation: number, startAngle: number, endAngle: number, ccw: boolean = false): void
```

**Parameters**

- `x` (`number`)
- `y` (`number`)
- `rx` (`number`)
- `ry` (`number`)
- `rotation` (`number`)
- `startAngle` (`number`)
- `endAngle` (`number`)
- `ccw` (`boolean`; default `false`)

<a id="svg-svgcontext2d-fill"></a>
##### `fill`

```ts
fill(): void
```

<a id="svg-svgcontext2d-fill-rect"></a>
##### `fillRect`

```ts
fillRect(x: number, y: number, w: number, h: number): void
```

**Parameters**

- `x` (`number`)
- `y` (`number`)
- `w` (`number`)
- `h` (`number`)

<a id="svg-svgcontext2d-fill-text"></a>
##### `fillText`

```ts
fillText(txt: string, x: number, y: number, maxWidth: number): void
```

**Parameters**

- `txt` (`string`)
- `x` (`number`)
- `y` (`number`)
- `maxWidth` (`number`)

<a id="svg-svgcontext2d-get-line-dash"></a>
##### `getLineDash`

```ts
getLineDash(): number[]
```

<a id="svg-svgcontext2d-line-to"></a>
##### `lineTo`

```ts
lineTo(x: number, y: number): void
```

**Parameters**

- `x` (`number`)
- `y` (`number`)

<a id="svg-svgcontext2d-measure-text"></a>
##### `measureText`

```ts
measureText(txt: string): TextMetrics
```

**Parameters**

- `txt` (`string`)

<a id="svg-svgcontext2d-move-to"></a>
##### `moveTo`

```ts
moveTo(x: number, y: number): void
```

**Parameters**

- `x` (`number`)
- `y` (`number`)

<a id="svg-svgcontext2d-put-image-data"></a>
##### `putImageData`

```ts
putImageData(): void
```

<a id="svg-svgcontext2d-quadratic-curve-to"></a>
##### `quadraticCurveTo`

```ts
quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void
```

**Parameters**

- `cpx` (`number`)
- `cpy` (`number`)
- `x` (`number`)
- `y` (`number`)

<a id="svg-svgcontext2d-rect"></a>
##### `rect`

```ts
rect(x: number, y: number, w: number, h: number): void
```

**Parameters**

- `x` (`number`)
- `y` (`number`)
- `w` (`number`)
- `h` (`number`)

<a id="svg-svgcontext2d-reset-dom"></a>
##### `resetDom`

```ts
resetDom(): void
```

Forget cached DOM references, eg after the host's contents were removed externally.

<a id="svg-svgcontext2d-restore"></a>
##### `restore`

```ts
restore(): void
```

<a id="svg-svgcontext2d-save"></a>
##### `save`

```ts
save(): void
```

<a id="svg-svgcontext2d-scale"></a>
##### `scale`

```ts
scale(): void
```

<a id="svg-svgcontext2d-set-line-dash"></a>
##### `setLineDash`

```ts
setLineDash(segments: number[]): void
```

**Parameters**

- `segments` (`number[]`)

<a id="svg-svgcontext2d-stroke"></a>
##### `stroke`

```ts
stroke(): void
```

#### Properties

<a id="svg-svgcontext2d-class-name"></a>
##### `className`

```ts
className: string
```

Optional CSS class applied to emitted elements (see `SVGForm.cls`).

<a id="svg-svgcontext2d-fill-style"></a>
##### `fillStyle`

```ts
fillStyle: string | SVGGradient
```

<a id="svg-svgcontext2d-font"></a>
##### `font`

```ts
font: string
```

<a id="svg-svgcontext2d-global-alpha"></a>
##### `globalAlpha`

```ts
globalAlpha: number
```

<a id="svg-svgcontext2d-global-composite-operation"></a>
##### `globalCompositeOperation`

```ts
globalCompositeOperation: string
```

<a id="svg-svgcontext2d-line-cap"></a>
##### `lineCap`

```ts
lineCap: string
```

<a id="svg-svgcontext2d-line-dash-offset"></a>
##### `lineDashOffset`

```ts
lineDashOffset: number
```

<a id="svg-svgcontext2d-line-join"></a>
##### `lineJoin`

```ts
lineJoin: string
```

<a id="svg-svgcontext2d-line-width"></a>
##### `lineWidth`

```ts
lineWidth: number
```

<a id="svg-svgcontext2d-stroke-style"></a>
##### `strokeStyle`

```ts
strokeStyle: string | SVGGradient
```

<a id="svg-svgcontext2d-text-align"></a>
##### `textAlign`

```ts
textAlign: string
```

<a id="svg-svgcontext2d-text-baseline"></a>
##### `textBaseline`

```ts
textBaseline: string
```

<a id="svg-svgform"></a>
### `SVGForm`

**Kind:** Class · **Source:** [`src/Svg.ts:986`](https://github.com/williamngan/pts/blob/master/src/Svg.ts#L986)

**Extends:** `CanvasForm`

SVGForm is a [`CanvasForm`](#canvas-canvasform) rendered through a [`SVGContext2D`](#svg-svgcontext2d): it inherits
the canvas drawing API — shapes, gradients, dashes, images, `textBox` — with SVG
output, subject to the capability notes in `SVGContext2D`. Sketches using this subset
can swap between `CanvasSpace` and `SVGSpace`. The legacy per-element static helpers and `scope()` workflow are retained
for compatibility but are no longer needed.

#### Constructors

<a id="svg-svgform-constructor"></a>
##### Constructor

*overrides `CanvasForm.__constructor`*

```ts
new SVGForm(space: SVGSpace): SVGForm
```

Create a new SVGForm. You may also use [`SVGSpace.getForm`](#svg-svgspace-get-form) to get a default form directly.

**Parameters**

- `space` (`SVGSpace`) — an instance of SVGSpace

#### Accessors

<a id="svg-svgform-filled"></a>
##### `filled`

*overrides `CanvasForm.filled`*

```ts
get filled(): boolean
set filled(b: boolean): void
```

Check whether this form currently has fill style.

<a id="svg-svgform-space"></a>
##### `space`

*overrides `CanvasForm.space`*

```ts
get space(): SVGSpace
```

Get the [`SVGSpace`](#svg-svgspace) instance that this form is associated with.

<a id="svg-svgform-stroked"></a>
##### `stroked`

*overrides `CanvasForm.stroked`*

```ts
get stroked(): boolean
set stroked(b: boolean): void
```

Check whether this form currently has stroke style.

<a id="svg-svgform-svg-context"></a>
##### `svgContext`

```ts
get svgContext(): SVGContext2D
```

The underlying [`SVGContext2D`](#svg-svgcontext2d), for advanced use.

<a id="svg-svgform-static-dom-id"></a>
##### `domID`

*static*

```ts
get domID(): number
set domID(n: number): void
```

<a id="svg-svgform-static-group-id"></a>
##### `groupID`

*static*

```ts
get groupID(): number
set groupID(n: number): void
```

#### Methods

<a id="svg-svgform-cls"></a>
##### `cls`

```ts
cls(c: string | boolean): SVGForm
```

Add custom class to the created element(s). In batched rendering the class applies to
the current style run.

**Parameters**

- `c` (`string | boolean`) — custom class name or `false` to reset it

**Example**

```ts
form.fill("#f00").cls("myClass").rects(r)` `form.cls(false).circles(c)
```

<a id="svg-svgform-next-id"></a>
##### `nextID`

```ts
nextID(): string
```

**deprecated:** Part of the legacy scope workflow.

<a id="svg-svgform-render-offscreen"></a>
##### `renderOffscreen`

*overrides `CanvasForm.renderOffscreen`*

```ts
renderOffscreen(_offset: PtLike = ...): void
```

Offscreen buffers require Canvas output. In SVG this warns once and does nothing.

**Parameters**

- `_offset` (`PtLike`; default `...`)

<a id="svg-svgform-scope"></a>
##### `scope`

```ts
scope(item: IPlayer): DOMFormContext
```

**Parameters**

- `item` (`IPlayer`)

**deprecated:** No longer needed: elements are reconciled automatically each frame. Kept
for compatibility; returns the legacy context used by the static helpers.

<a id="svg-svgform-update-scope"></a>
##### `updateScope`

```ts
updateScope(group_id: string, group: Element): DOMFormContext
```

**Parameters**

- `group_id` (`string`)
- `group` (`Element`)

**deprecated:** No longer needed: elements are reconciled automatically each frame. Kept
for compatibility with code that pairs it with the legacy static helpers.

<a id="svg-svgform-use-offscreen"></a>
##### `useOffscreen`

*overrides `CanvasForm.useOffscreen`*

```ts
useOffscreen(_off: boolean = true, _clear: string | boolean = false): this
```

Offscreen buffers require Canvas output. In SVG this warns once and draws directly.

**Parameters**

- `_off` (`boolean`; default `true`)
- `_clear` (`string | boolean`; default `false`)

<a id="svg-svgform-static-arc"></a>
##### `arc`

*static · overrides `CanvasForm.arc`*

**Overload 1**

```ts
static arc(ctx: DOMFormContext, pt: PtLike, radius: number, startAngle: number, endAngle: number, cc: boolean): SVGElement
```

Draw through a rendering context, or use the legacy per-element DOM context.

**Parameters**

- `ctx` (`DOMFormContext`)
- `pt` (`PtLike`)
- `radius` (`number`)
- `startAngle` (`number`)
- `endAngle` (`number`)
- `cc` (`boolean`)

**Overload 2**

```ts
static arc(ctx: RenderingContext2D, pt: PtLike, radius: number, startAngle: number, endAngle: number, cc: boolean): void
```

Draw through a rendering context, or use the legacy per-element DOM context.

**Parameters**

- `ctx` (`RenderingContext2D`)
- `pt` (`PtLike`)
- `radius` (`number`)
- `startAngle` (`number`)
- `endAngle` (`number`)
- `cc` (`boolean`)

<a id="svg-svgform-static-arc-element"></a>
##### `arcElement`

*static*

```ts
static arcElement(ctx: DOMFormContext, pt: PtLike, radius: number, startAngle: number, endAngle: number, cc: boolean): SVGElement
```

A static function to draw an arc element.

**Parameters**

- `ctx` (`DOMFormContext`) — a context object of SVGForm
- `pt` (`PtLike`) — center position
- `radius` (`number`) — radius of the arc circle
- `startAngle` (`number`) — start angle of the arc
- `endAngle` (`number`) — end angle of the arc
- `cc` (`boolean`) — an optional boolean value to specify if it should be drawn clockwise (`false`) or counter-clockwise (`true`). Default is clockwise.

<a id="svg-svgform-static-bezier"></a>
##### `bezier`

*static · overrides `CanvasForm.bezier`*

**Overload 1**

```ts
static bezier(ctx: DOMFormContext, pts: PtLikeIterable): SVGElement | undefined
```

Draw through a rendering context, or use the legacy per-element DOM context.

**Parameters**

- `ctx` (`DOMFormContext`)
- `pts` (`PtLikeIterable`)

**Overload 2**

```ts
static bezier(ctx: RenderingContext2D, pts: PtLikeIterable): void
```

Draw through a rendering context, or use the legacy per-element DOM context.

**Parameters**

- `ctx` (`RenderingContext2D`)
- `pts` (`PtLikeIterable`)

<a id="svg-svgform-static-bezier-element"></a>
##### `bezierElement`

*static*

```ts
static bezierElement(ctx: DOMFormContext, pts: PtLikeIterable): SVGElement | undefined
```

A static function to draw a chain of cubic Bezier curves as one path element.

**Parameters**

- `ctx` (`DOMFormContext`) — a context object of SVGForm
- `pts` (`PtLikeIterable`) — a Group or an Iterable<PtLike> in the layout of [`Curve.bezier`](#op-curve-static-bezier); an incomplete trailing segment is ignored

<a id="svg-svgform-static-circle"></a>
##### `circle`

*static · overrides `CanvasForm.circle`*

**Overload 1**

```ts
static circle(ctx: DOMFormContext, pt: PtLike, radius: number): SVGElement
```

Draw through a rendering context, or use the legacy per-element DOM context.

**Parameters**

- `ctx` (`DOMFormContext`)
- `pt` (`PtLike`)
- `radius` (`number`)

**Overload 2**

```ts
static circle(ctx: RenderingContext2D, pt: PtLike, radius: number): void
```

Draw through a rendering context, or use the legacy per-element DOM context.

**Parameters**

- `ctx` (`RenderingContext2D`)
- `pt` (`PtLike`)
- `radius` (`number`)

<a id="svg-svgform-static-circle-element"></a>
##### `circleElement`

*static*

```ts
static circleElement(ctx: DOMFormContext, pt: PtLike, radius: number = 10): SVGElement
```

A static function to draw a circle element.

**Parameters**

- `ctx` (`DOMFormContext`) — a context object of SVGForm
- `pt` (`PtLike`) — center position of the circle
- `radius` (`number`; default `10`) — radius of the circle

<a id="svg-svgform-static-compound"></a>
##### `compound`

*static · overrides `CanvasForm.compound`*

**Overload 1**

```ts
static compound(ctx: DOMFormContext, rings: Iterable): SVGElement | undefined
```

Draw through a rendering context, or use the legacy per-element DOM context.

**Parameters**

- `ctx` (`DOMFormContext`)
- `rings` (`Iterable`)

**Overload 2**

```ts
static compound(ctx: RenderingContext2D, rings: Iterable): void
```

Draw through a rendering context, or use the legacy per-element DOM context.

**Parameters**

- `ctx` (`RenderingContext2D`)
- `rings` (`Iterable`)

<a id="svg-svgform-static-compound-element"></a>
##### `compoundElement`

*static*

```ts
static compoundElement(ctx: DOMFormContext, rings: Iterable): SVGElement | undefined
```

A static function to draw a compound polygon as one path element, so that a ring inside another with the opposite orientation becomes a hole.

**Parameters**

- `ctx` (`DOMFormContext`) — a context object of SVGForm
- `rings` (`Iterable`) — an Array/Iterable of rings, each a Group or an Iterable<PtLike>; rings with fewer than 2 points are skipped

<a id="svg-svgform-static-get-id"></a>
##### `getID`

*static*

```ts
static getID(ctx: DOMFormContext): string
```

A static function to generate an ID string based on a context object.

**Parameters**

- `ctx` (`DOMFormContext`) — a context object for an SVGForm

<a id="svg-svgform-static-line"></a>
##### `line`

*static · overrides `CanvasForm.line`*

**Overload 1**

```ts
static line(ctx: DOMFormContext, pts: PtLikeIterable): SVGElement | undefined
```

Draw through a rendering context, or use the legacy per-element DOM context.

**Parameters**

- `ctx` (`DOMFormContext`)
- `pts` (`PtLikeIterable`)

**Overload 2**

```ts
static line(ctx: RenderingContext2D, pts: PtLikeIterable): void
```

Draw through a rendering context, or use the legacy per-element DOM context.

**Parameters**

- `ctx` (`RenderingContext2D`)
- `pts` (`PtLikeIterable`)

<a id="svg-svgform-static-line-element"></a>
##### `lineElement`

*static*

```ts
static lineElement(ctx: DOMFormContext, pts: PtLikeIterable): SVGElement | undefined
```

A static function to draw a line or polyline element.

**Parameters**

- `ctx` (`DOMFormContext`) — a context object of SVGForm
- `pts` (`PtLikeIterable`) — a Group or an Iterable<PtLike>

<a id="svg-svgform-static-point"></a>
##### `point`

*static · overrides `CanvasForm.point`*

**Overload 1**

```ts
static point(ctx: DOMFormContext, pt: PtLike, radius: number, shape: string): SVGElement
```

Draw through a rendering context, or use the legacy per-element DOM context.

**Parameters**

- `ctx` (`DOMFormContext`)
- `pt` (`PtLike`)
- `radius` (`number`)
- `shape` (`string`)

**Overload 2**

```ts
static point(ctx: RenderingContext2D, pt: PtLike, radius: number, shape: string): void
```

Draw through a rendering context, or use the legacy per-element DOM context.

**Parameters**

- `ctx` (`RenderingContext2D`)
- `pt` (`PtLike`)
- `radius` (`number`)
- `shape` (`string`)

<a id="svg-svgform-static-point-element"></a>
##### `pointElement`

*static*

```ts
static pointElement(ctx: DOMFormContext, pt: PtLike, radius: number = 5, shape: string = "square"): SVGElement
```

A static function to draw a point as a circle or square element.

**Parameters**

- `ctx` (`DOMFormContext`) — a context object of SVGForm
- `pt` (`PtLike`) — a Pt object or numeric array
- `radius` (`number`; default `5`) — radius of the point. Default is 5.
- `shape` (`string`; default `"square"`) — The shape of the point. Defaults to "square", but it can be "circle" or a custom shape function in your own implementation.

**Example**

```ts
SVGForm.point( ctx, p )`, `SVGForm.point( ctx, p, 10, "circle" )
```

<a id="svg-svgform-static-points-string"></a>
##### `pointsString`

*protected, static*

```ts
static pointsString(pts: PtLikeIterable): { count:number, string:string }
```

Given a list of points, return a space-separated string

**Parameters**

- `pts` (`PtLikeIterable`) — a Group or an Iterable<PtLike>

**Returns:** an object of {string, count}

<a id="svg-svgform-static-polygon"></a>
##### `polygon`

*static · overrides `CanvasForm.polygon`*

**Overload 1**

```ts
static polygon(ctx: DOMFormContext, pts: PtLikeIterable): SVGElement
```

Draw through a rendering context, or use the legacy per-element DOM context.

**Parameters**

- `ctx` (`DOMFormContext`)
- `pts` (`PtLikeIterable`)

**Overload 2**

```ts
static polygon(ctx: RenderingContext2D, pts: PtLikeIterable): void
```

Draw through a rendering context, or use the legacy per-element DOM context.

**Parameters**

- `ctx` (`RenderingContext2D`)
- `pts` (`PtLikeIterable`)

<a id="svg-svgform-static-polygon-element"></a>
##### `polygonElement`

*static*

```ts
static polygonElement(ctx: DOMFormContext, pts: PtLikeIterable): SVGElement
```

A static function to draw a polygon element.

**Parameters**

- `ctx` (`DOMFormContext`) — a context object of SVGForm
- `pts` (`PtLikeIterable`) — a Group or an Iterable<PtLike> representing a polygon

<a id="svg-svgform-static-rect"></a>
##### `rect`

*static · overrides `CanvasForm.rect`*

**Overload 1**

```ts
static rect(ctx: DOMFormContext, pts: PtLikeIterable): SVGElement | undefined
```

Draw through a rendering context, or use the legacy per-element DOM context.

**Parameters**

- `ctx` (`DOMFormContext`)
- `pts` (`PtLikeIterable`)

**Overload 2**

```ts
static rect(ctx: RenderingContext2D, pts: PtLikeIterable): void
```

Draw through a rendering context, or use the legacy per-element DOM context.

**Parameters**

- `ctx` (`RenderingContext2D`)
- `pts` (`PtLikeIterable`)

<a id="svg-svgform-static-rect-element"></a>
##### `rectElement`

*static*

```ts
static rectElement(ctx: DOMFormContext, pts: PtLikeIterable): SVGElement | undefined
```

A static function to draw a rectangle element.

**Parameters**

- `ctx` (`DOMFormContext`) — a context object of SVGForm
- `pts` (`PtLikeIterable`) — a Group or an Iterable<PtLike> with 2 Pt specifying the top-left and bottom-right positions.

<a id="svg-svgform-static-scope-id"></a>
##### `scopeID`

*static*

```ts
static scopeID(item: IPlayer): string
```

A static function to generate an ID string for a scope, based on an [`IPlayer`](#types-iplayer) object in the Space.

**Parameters**

- `item` (`IPlayer`) — a [`IPlayer`](#types-iplayer) object that's added to space (see [`Space.add`](#space-space-add)) and has an `animateID` property

<a id="svg-svgform-static-square"></a>
##### `square`

*static · overrides `CanvasForm.square`*

**Overload 1**

```ts
static square(ctx: DOMFormContext, pt: PtLike, halfsize: number): SVGElement
```

Draw through a rendering context, or use the legacy per-element DOM context.

**Parameters**

- `ctx` (`DOMFormContext`)
- `pt` (`PtLike`)
- `halfsize` (`number`)

**Overload 2**

```ts
static square(ctx: RenderingContext2D, pt: PtLike, halfsize: number): void
```

Draw through a rendering context, or use the legacy per-element DOM context.

**Parameters**

- `ctx` (`RenderingContext2D`)
- `pt` (`PtLike`)
- `halfsize` (`number`)

<a id="svg-svgform-static-square-element"></a>
##### `squareElement`

*static*

```ts
static squareElement(ctx: DOMFormContext, pt: PtLike, halfsize: number): SVGElement
```

A static function to draw a square element.

**Parameters**

- `ctx` (`DOMFormContext`) — a context object of SVGForm
- `pt` (`PtLike`) — center position of the square
- `halfsize` (`number`) — half size of the square

<a id="svg-svgform-static-style"></a>
##### `style`

*static*

```ts
static style(elem: SVGElement, styles: Record): Element
```

A static function to help adding style object to an element.
Note that this put all styles into `style` attribute instead of individual svg attributes, so that the styles can be parsed by Adobe Illustrator.

**Parameters**

- `elem` (`SVGElement`) — A DOM element to add to
- `styles` (`Record`) — an object of style properties

**Returns:** this DOM element

**Example**

```ts
SVGForm.style(elem, {fill: "#f90", stroke: false})
```

<a id="svg-svgform-static-text"></a>
##### `text`

*static · overrides `CanvasForm.text`*

**Overload 1**

```ts
static text(ctx: DOMFormContext, pt: PtLike, txt: string): SVGElement
```

Draw through a rendering context, or use the legacy per-element DOM context.

**Parameters**

- `ctx` (`DOMFormContext`)
- `pt` (`PtLike`)
- `txt` (`string`)

**Overload 2**

```ts
static text(ctx: RenderingContext2D, pt: PtLike, txt: string, maxWidth: number): void
```

Draw through a rendering context, or use the legacy per-element DOM context.

**Parameters**

- `ctx` (`RenderingContext2D`)
- `pt` (`PtLike`)
- `txt` (`string`)
- `maxWidth` (`number`)

<a id="svg-svgform-static-text-element"></a>
##### `textElement`

*static*

```ts
static textElement(ctx: DOMFormContext, pt: PtLike, txt: string): SVGElement
```

A static function to draw a text element.

**Parameters**

- `ctx` (`DOMFormContext`) — a context object of SVGForm
- `pt` (`PtLike`) — a Point object to specify the anchor point
- `txt` (`string`) — a string of text to draw

#### Inherited API

- From [`CanvasForm`](#canvas-canvasform): [`ctx`](#canvas-canvasform-ctx), [`alignText`](#canvas-canvasform-align-text), [`alpha`](#canvas-canvasform-alpha), [`applyFillStroke`](#canvas-canvasform-apply-fill-stroke), [`arc`](#canvas-canvasform-arc), [`bezier`](#canvas-canvasform-bezier), [`circle`](#canvas-canvasform-circle), [`clip`](#canvas-canvasform-clip), [`composite`](#canvas-canvasform-composite), [`compound`](#canvas-canvasform-compound), [`dash`](#canvas-canvasform-dash), [`ellipse`](#canvas-canvasform-ellipse), [`fill`](#canvas-canvasform-fill), [`fillOnly`](#canvas-canvasform-fill-only), [`font`](#canvas-canvasform-font), [`fontWidthEstimate`](#canvas-canvasform-font-width-estimate), [`getTextWidth`](#canvas-canvasform-get-text-width), [`gradient`](#canvas-canvasform-gradient), [`image`](#canvas-canvasform-image), [`imageData`](#canvas-canvasform-image-data), [`line`](#canvas-canvasform-line), [`log`](#canvas-canvasform-log), [`paragraphBox`](#canvas-canvasform-paragraph-box), [`point`](#canvas-canvasform-point), [`polygon`](#canvas-canvasform-polygon), [`rect`](#canvas-canvasform-rect), [`reset`](#canvas-canvasform-reset), [`square`](#canvas-canvasform-square), [`stroke`](#canvas-canvasform-stroke), [`strokeOnly`](#canvas-canvasform-stroke-only), [`text`](#canvas-canvasform-text), [`textBox`](#canvas-canvasform-text-box), [`ellipse`](#canvas-canvasform-ellipse), [`image`](#canvas-canvasform-image), [`imageData`](#canvas-canvasform-image-data), [`resetStyleCache`](#canvas-canvasform-static-reset-style-cache).
- From [`VisualForm`](#form-visualform): [`currentFont`](#form-visualform-current-font), [`circles`](#form-visualform-circles), [`lines`](#form-visualform-lines), [`points`](#form-visualform-points), [`polygons`](#form-visualform-polygons), [`rects`](#form-visualform-rects), [`squares`](#form-visualform-squares).
- From [`Form`](#form-form): [`ready`](#form-form-ready).

<a id="svg-svgspace"></a>
### `SVGSpace`

**Kind:** Class · **Source:** [`src/Svg.ts:725`](https://github.com/williamngan/pts/blob/master/src/Svg.ts#L725)

**Extends:** `DOMSpace`

SVGSpace extends [`DOMSpace`](#dom-domspace) to support SVG elements. Use it with [`SVGForm`](#svg-svgform),
which shares its drawing API and semantics with [`CanvasForm`](#canvas-canvasform) — a sketch written for
canvas can run on SVG with the supported subset. Check out the [Space guide](https://ptsjs.org/guide/Space-0500.html) for details.

#### Constructors

<a id="svg-svgspace-constructor"></a>
##### Constructor

*overrides `DOMSpace.__constructor`*

```ts
new SVGSpace(elem: string | Element | null = "pt", callback:  Fn(bound:Bound, elem:Element)): SVGSpace
```

Create a SVGSpace which represents a Space for SVG elements.

**Parameters**

- `elem` (`string | Element | null`; default `"pt"`) — Specify an element by its "id" attribute as string, or by the element object itself. An element can be an existing `<svg>`, or a `<div>` container in which a new `<svg>` will be created. If left empty, a `<div id="pt_container"><svg id="pt" /></div>` will be added to DOM. Use css to customize its appearance if needed.
- `callback` (` Fn(bound:Bound, elem:Element)`) — an optional callback `function(boundingBox, spaceElement)` to be called when canvas is appended and ready. Alternatively, a "ready" event will also be fired from the `<svg>` element when it's appended, which can be traced with `spaceInstance.canvas.addEventListener("ready")`

**Example**

```ts
new SVGSpace( "#myElementID" )
```

#### Accessors

<a id="svg-svgspace-element"></a>
##### `element`

*overrides `DOMSpace.element`*

```ts
get element(): Element
```

Get the DOM element.

#### Methods

<a id="svg-svgspace-clear"></a>
##### `clear`

*overrides `DOMSpace.clear`*

```ts
clear(bg: string): this
```

Clear the drawing. In SVG this maintains a background rectangle rather than erasing
elements — the per-frame reconciliation removes stale shapes.

**Parameters**

- `bg` (`string`) — Optionally specify a custom background color in hex or rgba string, or "transparent"

<a id="svg-svgspace-dispose"></a>
##### `dispose`

*overrides `DOMSpace.dispose`*

```ts
dispose(): this
```

Dispose of browser resources held by this space: listeners, the animation loop, and the
elements this space manages inside the `<svg>`. Call this before unmounting, eg in a
framework component's cleanup callback. A new space can be mounted on the same element
afterwards (as happens under React's StrictMode).

<a id="svg-svgspace-get-form"></a>
##### `getForm`

*overrides `DOMSpace.getForm`*

```ts
getForm(): SVGForm
```

Get a new [`SVGForm`](#svg-svgform) for drawing. The form shares its API with
[`CanvasForm`](#canvas-canvasform), rendered through a [`SVGContext2D`](#svg-svgcontext2d).

**See also:** `SVGForm`

<a id="svg-svgspace-play-items"></a>
##### `playItems`

*protected · overrides `DOMSpace.playItems`*

```ts
playItems(time: number): void
```

The per-frame cycle: begin all registered contexts' frames, run the players, then
commit — reconciling the SVG DOM against what was drawn this frame.

**Parameters**

- `time` (`number`)

<a id="svg-svgspace-refresh"></a>
##### `refresh`

*overrides `DOMSpace.refresh`*

```ts
refresh(b: boolean): this
```

Set whether the rendering should be repainted on each frame.

**Parameters**

- `b` (`boolean`) — a boolean value to set whether to repaint each frame

<a id="svg-svgspace-register-context"></a>
##### `registerContext`

```ts
registerContext(ctx: SVGContext2D): void
```

Register a rendering context so its frame lifecycle follows this space's play cycle.

**Parameters**

- `ctx` (`SVGContext2D`)

<a id="svg-svgspace-remove"></a>
##### `remove`

*overrides `DOMSpace.remove`*

```ts
remove(player: IPlayer): this
```

Remove an item from this Space.

**Parameters**

- `player` (`IPlayer`) — a player item with an auto-assigned `animateID` property

<a id="svg-svgspace-remove-all"></a>
##### `removeAll`

*overrides `DOMSpace.removeAll`*

```ts
removeAll(): this
```

Remove all items from this Space. This clears the contents of the space's
`<svg>` element but never touches its container, so the space keeps
rendering after items are re-added.

<a id="svg-svgspace-resize"></a>
##### `resize`

*overrides `DOMSpace.resize`*

```ts
resize(b: Bound, evt: Event | null): this
```

This overrides Space's `resize` function. It's used as a callback function for window's resize event and not usually called directly.
You can keep track of resize events with `resize: (bound ,evt)` callback in your [`IPlayer`](#types-iplayer) objects (See [`Space.add`](#space-space-add)).

**Parameters**

- `b` (`Bound`) — a Bound object to resize to
- `evt` (`Event | null`) — Optionally pass a resize event

<a id="svg-svgspace-to-svg"></a>
##### `toSVG`

```ts
toSVG(expand: boolean = false): string
```

Serialize the current SVG output to a string.

**Parameters**

- `expand` (`boolean`; default `false`) — if `true`, split merged style runs into one element per shape — a semantic export suited for editing in vector tools. Default is `false`.

<a id="svg-svgspace-static-svg-element"></a>
##### `svgElement`

*static*

```ts
static svgElement(parent: Element | null | undefined, name: string, id: string): SVGElement
```

A static function to add a svg element inside a node. Usually you don't need to call this directly. See methods in [`SVGForm`](#svg-svgform) instead.

**Parameters**

- `parent` (`Element | null | undefined`) — the parent element, or `null` to use current `<svg>` as parent.
- `name` (`string`) — a string of element name,  such as `rect` or `circle`
- `id` (`string`) — id attribute of the new element

#### Inherited API

- From [`DOMSpace`](#dom-domspace): [`autoResize`](#dom-domspace-auto-resize), [`background`](#dom-domspace-background), [`parent`](#dom-domspace-parent), [`ready`](#dom-domspace-ready), [`setup`](#dom-domspace-setup), [`style`](#dom-domspace-style), [`styles`](#dom-domspace-styles), [`createElement`](#dom-domspace-static-create-element), [`getInlineStyles`](#dom-domspace-static-get-inline-styles), [`setAttr`](#dom-domspace-static-set-attr), [`id`](#dom-domspace-id).
- From [`Space`](#space-space): [`center`](#space-space-center), [`customRendering`](#space-space-custom-rendering), [`height`](#space-space-height), [`innerBound`](#space-space-inner-bound), [`isPlaying`](#space-space-is-playing), [`outerBound`](#space-space-outer-bound), [`size`](#space-space-size), [`width`](#space-space-width), [`add`](#space-space-add), [`minFrameTime`](#space-space-min-frame-time), [`pause`](#space-space-pause), [`play`](#space-space-play), [`playOnce`](#space-space-play-once), [`render`](#space-space-render), [`replay`](#space-space-replay), [`resume`](#space-space-resume), [`stop`](#space-space-stop), [`bound`](#space-space-bound), [`playerCount`](#space-space-player-count), [`players`](#space-space-players).
- From [`MultiTouchSpace`](#space-multitouchspace): [`pointer`](#space-multitouchspace-pointer), [`bindCanvas`](#space-multitouchspace-bind-canvas), [`bindDoc`](#space-multitouchspace-bind-doc), [`bindKeyboard`](#space-multitouchspace-bind-keyboard), [`bindMouse`](#space-multitouchspace-bind-mouse), [`bindTouch`](#space-multitouchspace-bind-touch), [`touchesToPoints`](#space-multitouchspace-touches-to-points), [`track`](#space-multitouchspace-track), [`unbindCanvas`](#space-multitouchspace-unbind-canvas), [`unbindDoc`](#space-multitouchspace-unbind-doc), [`untrack`](#space-multitouchspace-untrack).

<a id="module-typography"></a>
## Module: `Typography`

<a id="typography-typography"></a>
### `Typography`

**Kind:** Class · **Source:** [`src/Typography.ts:10`](https://github.com/williamngan/pts/blob/master/src/Typography.ts#L10)

Typography provides helper functions to support typographic layouts. For a concrete example, see [a demo here](https://ptsjs.org/demo/?name=canvasform.textBox) that uses the [`CanvasForm.textBox`](#canvas-canvasform-text-box) function.

#### Methods

<a id="typography-typography-static-char-width-cache"></a>
##### `charWidthCache`

*static*

```ts
static charWidthCache(fn: TextMeasure): TextMeasure
```

Create a memoizing text width function that measures each distinct character once and sums the cached widths. Nearly as accurate as the reference function for most texts (kerning and ligatures excepted) at close to estimator speed after warmup. The cache is keyed by character, so create a new instance whenever the font changes.

**Parameters**

- `fn` (`TextMeasure`) — a reference function that can measure text width accurately

**Returns:** a function that measures text width using per-character caching

<a id="typography-typography-static-font-size-to-box"></a>
##### `fontSizeToBox`

*static*

**Overload 1**

```ts
static fontSizeToBox(ratio: number, byHeight: boolean):  Fn(box:PtLikeIterable)
```

Get a function to scale font size proportionally to a box's size. (Deprecated form: passing an initial box as the first parameter is deprecated — it never affected the result — and will be removed in a future version.)

**Parameters**

- `ratio` (`number`) — font-size to box-size ratio. Default is 1.
- `byHeight` (`boolean`) — `true` to scale by the box's height, `false` to scale by its width. Default is `true`.

**Returns:** a function where input parameter is a box, and returns a font size value (`ratio` multiplied by the box's height or width)

**Overload 2**

```ts
static fontSizeToBox(box: PtLikeIterable, ratio: number, byHeight: boolean):  Fn(box:PtLikeIterable)
```

**Parameters**

- `box` (`PtLikeIterable`)
- `ratio` (`number`)
- `byHeight` (`boolean`)

**deprecated:** The initial box never affected the result. Use `fontSizeToBox(ratio, byHeight)` instead.

<a id="typography-typography-static-font-size-to-threshold"></a>
##### `fontSizeToThreshold`

*static*

```ts
static fontSizeToThreshold(threshold: number, direction: number = 0):  Fn(defaultSize:number, val:number)
```

Get a function to scale font size based on a threshold value.

**Parameters**

- `threshold` (`number`) — threshold value. Cannot be 0.
- `direction` (`number`; default `0`) — if negative, get a font size <= defaultSize; if positive, get a font size >= defaultSize; Default is 0 which will scale font without min or max limits.

**Returns:** a function whose input parameters are a default font size and a value to compare with threshold, and which returns a new font size value

<a id="typography-typography-static-text-width-estimator"></a>
##### `textWidthEstimator`

*static*

```ts
static textWidthEstimator(fn: TextMeasure, samples: string[] = ..., distribution: number[] = ...): TextMeasure
```

Create a heuristic text width estimate function. It will be less accurate but faster.

**Parameters**

- `fn` (`TextMeasure`) — a reference function that can measure text width accurately
- `samples` (`string[]`; default `...`) — a list of string samples. Default is ["M", "n", "."]
- `distribution` (`number[]`; default `...`) — a list of the samples' probability distribution, which should have the same length as `samples` and sum to 1. Default is [0.06, 0.8, 0.14]. (A distribution that sums to more or less than 1 will proportionally inflate or deflate every estimate.)

**Returns:** a function that can estimate text width

<a id="typography-typography-static-truncate"></a>
##### `truncate`

*static*

```ts
static truncate(fn: TextMeasure, str: string, width: number, tail: string = "", hint: number): string,number
```

Truncate text to fit width. The result is guaranteed to fit: the largest prefix (possibly empty) is kept such that the prefix plus the tail measures within `width`. The cut never splits a surrogate pair. If even the tail alone cannot fit, `["", 0]` is returned.

**Parameters**

- `fn` (`TextMeasure`) — a function that can measure text width
- `str` (`string`) — text to truncate
- `width` (`number`) — width to fit
- `tail` (`string`; default `""`) — text to indicate overflow such as "...". Default is empty "".
- `hint` (`number`) — optional expected number of characters to keep — a pure performance hint (any value yields the same result) that seeds the search, such as the previous line's length when wrapping. With an empty `tail`, a hint also avoids measuring the entire string.

**Returns:** a tuple of the truncated text (tail included) and the number of characters kept from `str`

<a id="module-ui"></a>
## Module: `UI`

<a id="ui-ui"></a>
### `UI`

**Kind:** Class · **Source:** [`src/UI.ts:110`](https://github.com/williamngan/pts/blob/master/src/UI.ts#L110)

**[Experimental]** An abstract class that represents an UI element. It wraps a [`Group`](#pt-group) and supports UI event handling.
Extend this class to create custom UI elements.

#### Constructors

<a id="ui-ui-constructor"></a>
##### Constructor

```ts
new UI(group: PtLikeIterable, shape: string, states:  = {}, id: string): UI
```

Create an UI element. You may also create a new UI using one of the static helper like [`UI.fromRectangle`](#ui-ui-static-from-rectangle) or [`UI.fromCircle`](#ui-ui-static-from-circle).

**Parameters**

- `group` (`PtLikeIterable`) — a Group or an Iterable<PtLike> that defines the UI's appearance
- `shape` (`string`) — specifies the shape of the Group
- `states` (``; default `{}`) — optional a state object keep track of custom states for this UI
- `id` (`string`) — optional id string

#### Accessors

<a id="ui-ui-group"></a>
##### `group`

```ts
get group(): Group
set group(d: Group): void
```

A group of Pts that defines this UI's shape.

<a id="ui-ui-id"></a>
##### `id`

```ts
get id(): string
set id(d: string): void
```

An unique id of the UI.

<a id="ui-ui-shape"></a>
##### `shape`

```ts
get shape(): string
set shape(d: string): void
```

A string that describes this UI's shape.

#### Methods

<a id="ui-ui-get-state"></a>
##### `getState`

```ts
getState(key: string): T
```

Get a specific UI state. Unlike [`UI.state`](#ui-ui-state), this is a plain typed getter.

**Parameters**

- `key` (`string`) — state's name

<a id="ui-ui-hold"></a>
##### `hold`

*protected*

```ts
hold(type: string): number
```

Continue to keep track of an actions even if it's not within this UI. Useful for hover-leave and drag-outside.

**Parameters**

- `type` (`string`) — a string defined in [`UIPointerActions`](#ui-uipointeractions)

<a id="ui-ui-listen"></a>
##### `listen`

```ts
listen(type: UIPointerAction | string & , p: PtLike, evt: UIActionEvent): boolean
```

Listen for UI events and trigger action handlers.

**Parameters**

- `type` (`UIPointerAction | string & `) — an action type. Can be one of UIPointerActions or a custom one.
- `p` (`PtLike`) — a point to check
- `evt` (`UIActionEvent`) — a MouseEvent emitted by the browser (See [MDN docs](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent))

<a id="ui-ui-off"></a>
##### `off`

```ts
off(type: UIPointerAction | string & , which: number): boolean
```

Remove an event handler.

**Parameters**

- `type` (`UIPointerAction | string & `) — event type
- `which` (`number`) — an ID number returned by [`UI.on`](#ui-ui-on). If this is not defined, all handlers in this type will be removed (built-in machinery like UIButton's click counting is unaffected). Note that after removal an id is stale — removing it twice may affect a handler that has since reused the slot.

<a id="ui-ui-on"></a>
##### `on`

```ts
on(type: UIPointerAction | string & , fn: UIHandler, options: { once:boolean, signal:AbortSignal }): number
```

Add an event handler. Remember this UI will also need to be tracked for events, via `UI.track` or [`MultiTouchSpace.track`](#space-multitouchspace-track).

**Parameters**

- `type` (`UIPointerAction | string & `) — event type, either one of [`UIPointerActions`](#ui-uipointeractions) or a custom type
- `fn` (`UIHandler`) — a [`UIHandler`](#types-uihandler) callback function: `fn( target:UI, pt:Pt, type:string, evt:MouseEvent )`
- `options` (`{ once:boolean, signal:AbortSignal }`) — optionally `{ once }` to remove the handler after its first call, and/or `{ signal }` with an [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) that removes it on abort (an already-aborted signal registers nothing)

**Returns:** an id number that reference to this handler, for use in [`UI.off`](#ui-ui-off), or -1 if nothing was registered

<a id="ui-ui-render"></a>
##### `render`

```ts
render(fn:  Fn(group:Group, states:)): void
```

Take a custom render function to render this UI.

**Parameters**

- `fn` (` Fn(group:Group, states:)`) — a render function

<a id="ui-ui-set-state"></a>
##### `setState`

```ts
setState(key: string, value: any): this
```

Set a specific UI state. Unlike [`UI.state`](#ui-ui-state), this can also store `undefined`.

**Parameters**

- `key` (`string`) — state's name
- `value` (`any`) — the value to set

<a id="ui-ui-state"></a>
##### `state`

```ts
state(key: string, value: any): any
```

Get and/or set a specific UI state.

**Parameters**

- `key` (`string`) — state's name
- `value` (`any`) — optionally set a new value for this state.key

**Returns:** If `value` is changed, return this instance. Otherwise, return the value of the specific key.

<a id="ui-ui-to-string"></a>
##### `toString`

```ts
toString(): string
```

Returns a string representation of this UI

<a id="ui-ui-unhold"></a>
##### `unhold`

*protected*

```ts
unhold(key: number): void
```

Stop keeping track of this action

**Parameters**

- `key` (`number`) — an id returned by the [`UI.hold`](#ui-ui-hold) function

<a id="ui-ui-static-from-circle"></a>
##### `fromCircle`

*static*

```ts
static fromCircle(group: PtLikeIterable, states: , id: string): UI
```

A static helper function to create a Circle UI.

**Parameters**

- `group` (`PtLikeIterable`) — a Group or an Iterable<PtLike> with 2 Pt representing a circle
- `states` (``) — optional a state object keep track of custom states for this UI
- `id` (`string`) — optional id string

<a id="ui-ui-static-from-polygon"></a>
##### `fromPolygon`

*static*

```ts
static fromPolygon(group: PtLikeIterable, states: , id: string): UI
```

A static helper function to create a Polygon UI.

**Parameters**

- `group` (`PtLikeIterable`) — a Group or an Iterable<PtLike> representing a polygon
- `states` (``) — optional a state object keep track of custom states for this UI
- `id` (`string`) — optional id string

<a id="ui-ui-static-from-rectangle"></a>
##### `fromRectangle`

*static*

```ts
static fromRectangle(group: PtLikeIterable, states: , id: string): UI
```

A static helper function to create a Rectangle UI.

**Parameters**

- `group` (`PtLikeIterable`) — a Group or an Iterable<PtLike> with 2 Pt representing a rectangle
- `states` (``) — optional a state object keep track of custom states for this UI
- `id` (`string`) — optional id string

<a id="ui-ui-static-from-ui"></a>
##### `fromUI`

*static*

```ts
static fromUI(ui: UI, states: object, id: string): UI
```

A static helper function to create a new UI based on another UI.

**Parameters**

- `ui` (`UI`) — base UI
- `states` (`object`) — optional a state object keep track of custom states for this UI
- `id` (`string`)

<a id="ui-ui-static-register-shape"></a>
##### `registerShape`

*static*

```ts
static registerShape(shape: string, fn: UIShapeTest): void
```

Register a custom shape hit test, or override a built-in one. The shape
name can then be used when constructing a UI.

**Parameters**

- `shape` (`string`) — shape name
- `fn` (`UIShapeTest`) — a function `(group, pt, states) => boolean` that returns whether the point hits the shape

<a id="ui-ui-static-track"></a>
##### `track`

*static*

```ts
static track(uis: UI[], type: string, p: PtLike, evt: UIActionEvent): void
```

A static function to listen for a list of UIs. See also [`UI.listen`](#ui-ui-listen).

**Parameters**

- `uis` (`UI[]`) — an array of UI
- `type` (`string`) — an action type. Can be one of `UIPointerActions` or a custom one.
- `p` (`PtLike`) — a point to check
- `evt` (`UIActionEvent`) — a MouseEvent emitted by the browser (See [MDN docs](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent))

<a id="ui-uibutton"></a>
### `UIButton`

**Kind:** Class · **Source:** [`src/UI.ts:504`](https://github.com/williamngan/pts/blob/master/src/UI.ts#L504)

**Extends:** `UI`

**[Experimental]** A simple button that extends [`UI`](#ui-ui) to track clicks and hovers.

#### Constructors

<a id="ui-uibutton-constructor"></a>
##### Constructor

*overrides `UI.__constructor`*

```ts
new UIButton(group: PtLikeIterable, shape: string, states:  = {}, id: string): UIButton
```

Create an UIButton. A button has 2 states, "clicks" (number) and "hover" (boolean), which you can access through [`UI.state`](#ui-ui-state) function. You may also create a new UIButton using one of the static helper like [`UI.fromRectangle`](#ui-ui-static-from-rectangle) or [`UI.fromCircle`](#ui-ui-static-from-circle).

**Parameters**

- `group` (`PtLikeIterable`) — a Group or an Iterable<PtLike> that defines the UI's appearance
- `shape` (`string`) — specifies the shape of the Group
- `states` (``; default `{}`) — Optional default state object
- `id` (`string`) — Optional id string

#### Methods

<a id="ui-uibutton-off-click"></a>
##### `offClick`

```ts
offClick(id: number): boolean
```

Remove an existing click handler

**Parameters**

- `id` (`number`) — an ID number returned by [`UIButton.onClick`](#ui-uibutton-on-click). If this is not defined, all handlers in this type will be removed.

**Returns:** a boolean indicating whether the handler was removed successfully

<a id="ui-uibutton-off-context-menu"></a>
##### `offContextMenu`

```ts
offContextMenu(id: number): boolean
```

Remove an existing contextmenu handler

**Parameters**

- `id` (`number`) — an ID number returned by [`UIButton.onContextMenu`](#ui-uibutton-on-context-menu). If this is not defined, all handlers in this type will be removed.

**Returns:** a boolean indicating whether the handler was removed successfully

<a id="ui-uibutton-off-hover"></a>
##### `offHover`

```ts
offHover(enterID: number, leaveID: number): boolean[]
```

Remove handlers for hover events.

**Parameters**

- `enterID` (`number`) — an ID number returned by [`UI.onClick`](#ui-uibutton-on-click), or -1 to skip. If this is not defined, all handlers in this type will be removed.
- `leaveID` (`number`) — an ID number returned by [`UI.onClick`](#ui-uibutton-on-click), or -1 to skip. If this is not defined, all handlers in this type will be removed.

**Returns:** an array of booleans indicating whether the handlers were removed successfully

<a id="ui-uibutton-on-click"></a>
##### `onClick`

```ts
onClick(fn: UIHandler): number
```

Add a new click handler. Remember this button will also need to be tracked for events via `UI.track`. If you want to track right clicks, you may also consider [`UIButton.onContextMenu`](#ui-uibutton-on-context-menu).

**Parameters**

- `fn` (`UIHandler`) — a [`UIHandler`](#types-uihandler) callback function: `fn( target:UI, pt:Pt, type:string, evt:MouseEvent )`

**Returns:** an id number that refers to this handler, for use in [`UIButton.offClick`](#ui-uibutton-off-click) or [`UI.off`](#ui-ui-off).

<a id="ui-uibutton-on-context-menu"></a>
##### `onContextMenu`

```ts
onContextMenu(fn: UIHandler): number
```

Add a new contextmenu handler. `contextmenu` is similar to right click, see the [MDN docs](https://developer.mozilla.org/en-US/docs/Web/API/Element/contextmenu_event). Remember this button will also need to be tracked for events via `UI.track`. Also note that you may need to use `event.preventDefault()` in the callback function to prevent other events from triggering.

**Parameters**

- `fn` (`UIHandler`) — a [`UIHandler`](#types-uihandler) callback function: `fn( target:UI, pt:Pt, type:string, evt:MouseEvent )`

**Returns:** an id number that refers to this handler, for use in [`UIButton.offContextMenu`](#ui-uibutton-off-context-menu) or [`UI.off`](#ui-ui-off).

<a id="ui-uibutton-on-hover"></a>
##### `onHover`

```ts
onHover(enter: UIHandler, leave: UIHandler): (number | undefined)[]
```

Add handlers for hover events. Remember this button will also need to be tracked for events via `UI.track`.

**Parameters**

- `enter` (`UIHandler`) — an optional [`UIHandler`](#types-uihandler) function to handle when pointer enters hover. Eg, `fn( target:UI, pt:Pt, type:string, evt:MouseEvent )`
- `leave` (`UIHandler`) — an optional [`UIHandler`](#types-uihandler) function to handle when pointer exits hover. Eg, `fn( target:UI, pt:Pt, type:string, evt:MouseEvent )`

**Returns:** id numbers that refer to enter/leave handlers, for use in [`UIButton.offHover`](#ui-uibutton-off-hover) or [`UI.off`](#ui-ui-off).

#### Inherited API

- From [`UI`](#ui-ui): [`group`](#ui-ui-group), [`id`](#ui-ui-id), [`shape`](#ui-ui-shape), [`getState`](#ui-ui-get-state), [`hold`](#ui-ui-hold), [`listen`](#ui-ui-listen), [`off`](#ui-ui-off), [`on`](#ui-ui-on), [`render`](#ui-ui-render), [`setState`](#ui-ui-set-state), [`state`](#ui-ui-state), [`toString`](#ui-ui-to-string), [`unhold`](#ui-ui-unhold), [`fromCircle`](#ui-ui-static-from-circle), [`fromPolygon`](#ui-ui-static-from-polygon), [`fromRectangle`](#ui-ui-static-from-rectangle), [`fromUI`](#ui-ui-static-from-ui), [`registerShape`](#ui-ui-static-register-shape), [`track`](#ui-ui-static-track).

<a id="ui-uidragger"></a>
### `UIDragger`

**Kind:** Class · **Source:** [`src/UI.ts:632`](https://github.com/williamngan/pts/blob/master/src/UI.ts#L632)

**Extends:** `UIButton`

[Experimental] A draggable UI that provides handler such as [`UIDragger.onDrag`](#ui-uidragger-on-drag) and [`UIDragger.onDrop`](#ui-uidragger-on-drop).

#### Constructors

<a id="ui-uidragger-constructor"></a>
##### Constructor

*overrides `UIButton.__constructor`*

```ts
new UIDragger(group: PtLikeIterable, shape: string, states:  = {}, id: string): UIDragger
```

Create a dragger which has all the states in UIButton, with additional "dragging" (a boolean indicating whether it's currently being dragged) and "offset" (a Pt representing the offset between this UI's position and the pointer's position when dragged) states. (See [`UI.state`](#ui-ui-state)) You may also create a new UIDragger using one of the static helper like [`UI.fromRectangle`](#ui-ui-static-from-rectangle) or [`UI.fromCircle`](#ui-ui-static-from-circle).

**Parameters**

- `group` (`PtLikeIterable`) — a Group or an Iterable<PtLike> that defines the UI's appearance
- `shape` (`string`) — specifies the shape of the Group
- `states` (``; default `{}`) — Optional default state object
- `id` (`string`) — Optional id string

#### Methods

<a id="ui-uidragger-off-drag"></a>
##### `offDrag`

```ts
offDrag(id: number): boolean
```

Remove an existing drag handler

**Parameters**

- `id` (`number`) — an ID number returned by [`UIDragger.onDrag`](#ui-uidragger-on-drag). If this is not defined, all handlers in this type will be removed.

**Returns:** a boolean indicating whether the handler was removed successfully

<a id="ui-uidragger-off-drop"></a>
##### `offDrop`

```ts
offDrop(id: number): boolean
```

Remove an existing drop handler

**Parameters**

- `id` (`number`) — an ID number returned by [`UIDragger.onDrag`](#ui-uidragger-on-drag). If this is not defined, all handlers in this type will be removed.

**Returns:** a boolean indicating whether the handler was removed successfully

<a id="ui-uidragger-on-drag"></a>
##### `onDrag`

```ts
onDrag(fn: UIHandler): number
```

Add a new drag handler. Remember this button will also need to be tracked for events via `UI.track`.

**Parameters**

- `fn` (`UIHandler`) — a [`UIHandler`](#types-uihandler) callback function: `fn( target:UI, pt:Pt, type:string, evt:MouseEvent )`. You can access the states "dragging" and "offset" (See [`UI.state`](#ui-ui-state)) in the callback.

**Returns:** an id number that refers to this handler, for use in [`UIDragger.offDrag`](#ui-uidragger-off-drag) or [`UI.off`](#ui-ui-off).

<a id="ui-uidragger-on-drop"></a>
##### `onDrop`

```ts
onDrop(fn: UIHandler): number
```

Add a new drop handler. Remember this button will also need to be tracked for events via `UI.track`.

**Parameters**

- `fn` (`UIHandler`) — a [`UIHandler`](#types-uihandler) callback function: `fn( target:UI, pt:Pt, type:string, evt:MouseEvent )`

**Returns:** an id number that refers to this handler, for use in [`UIDragger.offDrop`](#ui-uidragger-off-drop) or [`UI.off`](#ui-ui-off).

#### Inherited API

- From [`UI`](#ui-ui): [`group`](#ui-ui-group), [`id`](#ui-ui-id), [`shape`](#ui-ui-shape), [`getState`](#ui-ui-get-state), [`hold`](#ui-ui-hold), [`listen`](#ui-ui-listen), [`off`](#ui-ui-off), [`on`](#ui-ui-on), [`render`](#ui-ui-render), [`setState`](#ui-ui-set-state), [`state`](#ui-ui-state), [`toString`](#ui-ui-to-string), [`unhold`](#ui-ui-unhold), [`fromCircle`](#ui-ui-static-from-circle), [`fromPolygon`](#ui-ui-static-from-polygon), [`fromRectangle`](#ui-ui-static-from-rectangle), [`fromUI`](#ui-ui-static-from-ui), [`registerShape`](#ui-ui-static-register-shape), [`track`](#ui-ui-static-track).
- From [`UIButton`](#ui-uibutton): [`offClick`](#ui-uibutton-off-click), [`offContextMenu`](#ui-uibutton-off-context-menu), [`offHover`](#ui-uibutton-off-hover), [`onClick`](#ui-uibutton-on-click), [`onContextMenu`](#ui-uibutton-on-context-menu), [`onHover`](#ui-uibutton-on-hover).

<a id="ui-uipointeraction"></a>
### `UIPointerAction`

**Kind:** Typealias · **Source:** [`src/UI.ts:98`](https://github.com/williamngan/pts/blob/master/src/UI.ts#L98)

A known pointer, touch, or keyboard action dispatched by a Pts space.

```ts
type UIPointerAction = UIPointerActions[keyof UIPointerActions];
```

<a id="ui-uishapetest"></a>
### `UIShapeTest`

**Kind:** Typealias · **Source:** [`src/UI.ts:14`](https://github.com/williamngan/pts/blob/master/src/UI.ts#L14)

A hit-test function for a UI shape: given the UI's group, a point, and the UI's states, return whether the point is within the shape.

```ts
type UIShapeTest =  Fn(group:Group, pt:PtLike, states:);
```

<a id="ui-uipointeractions"></a>
### `UIPointerActions`

**Kind:** Objectliteral · **Source:** [`src/UI.ts:76`](https://github.com/williamngan/pts/blob/master/src/UI.ts#L76)

**[Experimental]** A set of string constants to represent different UI event types.

#### Values

<a id="ui-uipointeractions-all"></a>
##### `all`

*readonly*

```ts
readonly all: all
```

<a id="ui-uipointeractions-click"></a>
##### `click`

*readonly*

```ts
readonly click: click
```

<a id="ui-uipointeractions-contextmenu"></a>
##### `contextmenu`

*readonly*

```ts
readonly contextmenu: contextmenu
```

<a id="ui-uipointeractions-down"></a>
##### `down`

*readonly*

```ts
readonly down: down
```

<a id="ui-uipointeractions-drag"></a>
##### `drag`

*readonly*

```ts
readonly drag: drag
```

<a id="ui-uipointeractions-drop"></a>
##### `drop`

*readonly*

```ts
readonly drop: drop
```

<a id="ui-uipointeractions-enter"></a>
##### `enter`

*readonly*

```ts
readonly enter: enter
```

<a id="ui-uipointeractions-keydown"></a>
##### `keydown`

*readonly*

```ts
readonly keydown: keydown
```

<a id="ui-uipointeractions-keyup"></a>
##### `keyup`

*readonly*

```ts
readonly keyup: keyup
```

<a id="ui-uipointeractions-leave"></a>
##### `leave`

*readonly*

```ts
readonly leave: leave
```

<a id="ui-uipointeractions-move"></a>
##### `move`

*readonly*

```ts
readonly move: move
```

<a id="ui-uipointeractions-out"></a>
##### `out`

*readonly*

```ts
readonly out: out
```

<a id="ui-uipointeractions-over"></a>
##### `over`

*readonly*

```ts
readonly over: over
```

<a id="ui-uipointeractions-pointerdown"></a>
##### `pointerdown`

*readonly*

```ts
readonly pointerdown: pointerdown
```

<a id="ui-uipointeractions-pointerup"></a>
##### `pointerup`

*readonly*

```ts
readonly pointerup: pointerup
```

<a id="ui-uipointeractions-uidrag"></a>
##### `uidrag`

*readonly*

```ts
readonly uidrag: uidrag
```

<a id="ui-uipointeractions-uidrop"></a>
##### `uidrop`

*readonly*

```ts
readonly uidrop: uidrop
```

<a id="ui-uipointeractions-up"></a>
##### `up`

*readonly*

```ts
readonly up: up
```

<a id="ui-uishape"></a>
### `UIShape`

**Kind:** Objectliteral · **Source:** [`src/UI.ts:65`](https://github.com/williamngan/pts/blob/master/src/UI.ts#L65)

**[Experimental]** A set of string constatns to represent different UI types, for use in [`UI`](#ui-ui) instances.

#### Values

<a id="ui-uishape-circle"></a>
##### `circle`

```ts
circle: circle
```

<a id="ui-uishape-line"></a>
##### `line`

```ts
line: line
```

<a id="ui-uishape-polygon"></a>
##### `polygon`

```ts
polygon: polygon
```

<a id="ui-uishape-polyline"></a>
##### `polyline`

```ts
polyline: polyline
```

<a id="ui-uishape-rectangle"></a>
##### `rectangle`

```ts
rectangle: rectangle
```

<a id="module-util"></a>
## Module: `Util`

<a id="util-util"></a>
### `Util`

**Kind:** Class · **Source:** [`src/Util.ts:107`](https://github.com/williamngan/pts/blob/master/src/Util.ts#L107)

Util class provides static helper functions.

#### Methods

<a id="util-util-static-array-check"></a>
##### `arrayCheck`

*static*

```ts
static arrayCheck(pts: PtLikeIterable, minRequired: number = 2): boolean
```

Check number of items in a Group against a required number

**Parameters**

- `pts` (`PtLikeIterable`) — a Group or an Iterable<PtLike>
- `minRequired` (`number`; default `2`) — minimum number of items required

<a id="util-util-static-combine"></a>
##### `combine`

*static*

```ts
static combine(a: T[], b: T[], op:  Fn(a:T, b:T)): T[]
```

Given two arrays of objects, and a function that operate on two objects, return an array. Objects must be of same type.

**Parameters**

- `a` (`T[]`) — an array of object, eg `[Group, Group, ...]`
- `b` (`T[]`) — another array of object
- `op` (` Fn(a:T, b:T)`) — a function that takes two parameters (a, b) and returns an object.

<a id="util-util-static-download"></a>
##### `download`

*static*

```ts
static download(space: CanvasSpace, filename: string = "pts_canvas_image", filetype: jpeg | jpg | png | webp = "png", quality: number = 1): void
```

Download the current `CanvasSpace` as an image (jpg/png/webp). Calling this function will automatically trigger a download.

**Parameters**

- `space` (`CanvasSpace`) — an instance of `CanvasSpace`
- `filename` (`string`; default `"pts_canvas_image"`) — the name of the file, without the extension name.
- `filetype` (`jpeg | jpg | png | webp`; default `"png"`) — the image type (jpg/png/webp)
- `quality` (`number`; default `1`) — a value between 0 to 1, if filetype is either "jpg" or "png"

<a id="util-util-static-flatten"></a>
##### `flatten`

*static*

```ts
static flatten(pts: any[], flattenAsGroup: boolean = true): any
```

Flatten an array of arrays such as Group[] to a flat Array or Group.

**Parameters**

- `pts` (`any[]`) — an array, usually an array of Groups
- `flattenAsGroup` (`boolean`; default `true`) — a boolean to specify whether the return type should be a Group or Array. Default is `true` which returns a Group.

<a id="util-util-static-for-range"></a>
##### `forRange`

*static*

```ts
static forRange(fn:  Fn(index:number), range: number, start: number = 0, step: number = 1): any[]
```

A convenient way to step through a range. Same as `for (i=0; i<range; i++)`, except this also stores the resulting return values at each step and return them as an array.

**Parameters**

- `fn` (` Fn(index:number)`) — a callback function `fn(index)`. If this function returns a value, it will be stored at each step
- `range` (`number`) — a range to step through
- `start` (`number`; default `0`)
- `step` (`number`; default `1`)

**Returns:** an index-aligned array of returned values: entries sit at their step index, so with a non-zero `start` the positions below `start` are empty holes

<a id="util-util-static-get-args"></a>
##### `getArgs`

*static*

```ts
static getArgs(args: any[]): number[]
```

Convert different kinds of parameters (arguments, array, object) into an array of numbers.

**Parameters**

- `args` (`any[]`) — can be either a list of numbers, an array, a Pt, or an object with {x,y,z,w} properties

<a id="util-util-static-get-pt-like"></a>
##### `getPtLike`

*static*

```ts
static getPtLike(args: any[]): PtLike
```

Like [`Util.getArgs`](#util-util-static-get-args), but avoids copying when the arguments are already
a numeric array, a typed array (eg, a Pt), or a list of numbers. The result may be
the caller's own object, so it must be treated as read-only.

**Parameters**

- `args` (`any[]`) — can be either a list of numbers, an array, a Pt, or an object with {x,y,z,w} properties

<a id="util-util-static-is-mobile"></a>
##### `isMobile`

*static*

```ts
static isMobile(): boolean
```

Check if accessing from a mobile device. Can be useful since some experimental features may not be availble in mobile browsers.

<a id="util-util-static-iter-to-array"></a>
##### `iterToArray`

*static*

```ts
static iterToArray(it: Iterable): any[]
```

Convert an iterable into an array

**Parameters**

- `it` (`Iterable`) — an iterable

<a id="util-util-static-load"></a>
##### `load`

*static*

```ts
static load(url: string, callback:  Fn(response:string, success:boolean)): void
```

A helper function to load data from a url via XMLHttpRequest GET. Since the response passed into callback is a string, if you're loading json data, you may use standard `JSON.parse(response)` to get a JSON object. For csv, try using a javascript csv library like papaparse or vega/datalib.

**Parameters**

- `url` (`string`) — the request url
- `callback` (` Fn(response:string, success:boolean)`) — a function to capture the data. It receives two parameters: a `response` as string, and a `success` status as boolean.

<a id="util-util-static-performance"></a>
##### `performance`

*static*

```ts
static performance(avgFrames: number = 10):  ()
```

Estimate performance by checking how long it takes to render a frame

**Parameters**

- `avgFrames` (`number`; default `10`) — The number of frames used calculate to average

**Returns:** milliseconds per frame

**Example**

```ts
let perf = Util.performance(); perf();
```

<a id="util-util-static-random-int"></a>
##### `randomInt`

*static*

```ts
static randomInt(range: number, start: number = 0): number
```

Get a random integer. This can be useful for selecting a random index in an array.

**Parameters**

- `range` (`number`) — value range
- `start` (`number`; default `0`) — Optional starting value

**deprecated:** Use [`Num.randomRange`](#num-num-static-random-range) instead, for example `Math.floor( Num.randomRange( start, start + range ) )`.

<a id="util-util-static-split"></a>
##### `split`

*static*

```ts
static split(pts: any[], size: number, stride: number, loopBack: boolean = false, matchSize: boolean = true): any[][]
```

Split an array into chunks of sub-array.

**Parameters**

- `pts` (`any[]`) — an array
- `size` (`number`) — chunk size, ie, number of items in a chunk
- `stride` (`number`) — optional parameter to "walk through" the array in steps
- `loopBack` (`boolean`; default `false`) — if `true`, always go through the array till the end and loop back to the beginning to complete the segments if needed.
- `matchSize` (`boolean`; default `true`) — if `true`, all chunks's length must match `size`.

<a id="util-util-static-stepper"></a>
##### `stepper`

*static*

```ts
static stepper(max: number, min: number = 0, stride: number = 1, callback:  Fn(n:number)):  ()
```

Create a convenient stepper. This returns a function which you can call repeatedly to step a counter.

**Parameters**

- `max` (`number`) — Maximum of the stepper range. The resulting stepper will return values within [min, max). Note that the first call returns `min + stride`, not `min`.
- `min` (`number`; default `0`) — Minimum of the stepper range. Default is 0.
- `stride` (`number`; default `1`) — Stride of the step. Default is 1.
- `callback` (` Fn(n:number)`) — An optional callback function `fn( step )`, which will be called each time when stepper function is called.

**Returns:** a function which will increment the stepper and return its value at each call.

**Example**

```ts
let counter = stepper(100); let c = counter(); c = counter(); ...
```

<a id="util-util-static-to-numeric-array"></a>
##### `toNumericArray`

*static*

```ts
static toNumericArray(a: ArrayLike): number[]
```

Copy an array or typed array of numbers into a fresh plain array.

**Parameters**

- `a` (`ArrayLike`) — an array or typed array

<a id="util-util-static-unique-id"></a>
##### `uniqueId`

*static*

```ts
static uniqueId(useCrypto: boolean = false): string
```

Generate a time-based unique ID or a crypto-based ID.

**Parameters**

- `useCrypto` (`boolean`; default `false`)

<a id="util-util-static-warn"></a>
##### `warn`

*static*

```ts
static warn(message: string = "error", defaultReturn: any = undefined): any
```

Send a warning message based on [`Util.warnLevel`](#util-util-static-warn-level) global setting. This allows you to dynamically set whether minor errors should be thrown or printed in console or muted.

**Parameters**

- `message` (`string`; default `"error"`) — any error or warning message
- `defaultReturn` (`any`; default `undefined`) — optional return value

<a id="util-util-static-warn-level"></a>
##### `warnLevel`

*static*

```ts
static warnLevel(lv: WarningType): WarningType
```

Set a global warning level setting. If no parameter is passed, this will return the current warn-level. See [`Util.warn`](#util-util-static-warn).

**Parameters**

- `lv` (`WarningType`) — a [`WarningType`](#types-warningtype) option, where "error" will throw an error, "warn" will log in console, and "mute" will ignore the error.

<a id="util-util-static-zip"></a>
##### `zip`

*static*

```ts
static zip(arrays: any[][]): any[][]
```

Zip arrays. eg, `[[1,2],[3,4],[5,6]] => [[1,3,5],[2,4,6]]`.

**Parameters**

- `arrays` (`any[][]`) — an array of arrays

<a id="util-const"></a>
### `Const`

**Kind:** Objectliteral · **Source:** [`src/Util.ts:11`](https://github.com/williamngan/pts/blob/master/src/Util.ts#L11)

Various constant values for enumerations and calculations.

#### Values

<a id="util-const-bottom"></a>
##### `bottom`

```ts
bottom: bottom
```

Represents bottom position or direction

<a id="util-const-bottom-left"></a>
##### `bottom_left`

```ts
bottom_left: bottom_left
```

Represents bottom left position or direction

<a id="util-const-bottom-right"></a>
##### `bottom_right`

```ts
bottom_right: bottom_right
```

Represents bottom right position or direction

<a id="util-const-deg-to-rad"></a>
##### `deg_to_rad`

```ts
deg_to_rad: deg_to_rad
```

Multiply this constant with a degree to get a radian

<a id="util-const-epsilon"></a>
##### `epsilon`

```ts
epsilon: epsilon
```

Represents an arbitrary very small number. It is set as 0.0001 here.

<a id="util-const-gaussian"></a>
##### `gaussian`

```ts
gaussian: gaussian
```

Gaussian constant (1 / Math.sqrt(2 * Math.PI))

<a id="util-const-gravity"></a>
##### `gravity`

```ts
gravity: gravity
```

Gravity acceleration (unit: m/s^2) and gravity force (unit: Newton) on 1kg of mass.

<a id="util-const-half-pi"></a>
##### `half_pi`

```ts
half_pi: half_pi
```

Half π radian (90deg)

<a id="util-const-horizontal"></a>
##### `horizontal`

```ts
horizontal: horizontal
```

Represents horizontal direction.

<a id="util-const-identical"></a>
##### `identical`

```ts
identical: identical
```

Represents identical point or value

<a id="util-const-left"></a>
##### `left`

```ts
left: left
```

Represents left position or direction

<a id="util-const-max"></a>
##### `max`

```ts
max: max
```

Represents Number.MAX_VALUE. Note: as a Float32 Pt value this overflows to Infinity.

<a id="util-const-min"></a>
##### `min`

```ts
min: min
```

Represents Number.MIN_VALUE, the smallest *positive* number (5e-324) — not the most negative number. Do not use it to initialize a running maximum; use -Infinity instead. As a Float32 Pt value this flushes to 0.

<a id="util-const-newton"></a>
##### `newton`

```ts
newton: newton
```

1 Newton: 0.10197 Kilogram-force

<a id="util-const-one-degree"></a>
##### `one_degree`

```ts
one_degree: one_degree
```

π/180 or 1 degree in radian

<a id="util-const-pi"></a>
##### `pi`

```ts
pi: pi
```

π radian (180 deg)

<a id="util-const-quarter-pi"></a>
##### `quarter_pi`

```ts
quarter_pi: quarter_pi
```

π/4 radian (45deg)

<a id="util-const-rad-to-deg"></a>
##### `rad_to_deg`

```ts
rad_to_deg: rad_to_deg
```

Multiply this constant with a radian to get a degree

<a id="util-const-right"></a>
##### `right`

```ts
right: right
```

Represents right position or direction

<a id="util-const-top"></a>
##### `top`

```ts
top: top
```

Represents top position or direction

<a id="util-const-top-left"></a>
##### `top_left`

```ts
top_left: top_left
```

Represents top left position or direction

<a id="util-const-top-right"></a>
##### `top_right`

```ts
top_right: top_right
```

Represents top right position or direction

<a id="util-const-two-pi"></a>
##### `two_pi`

```ts
two_pi: two_pi
```

Two π radian (360deg)

<a id="util-const-vertical"></a>
##### `vertical`

```ts
vertical: vertical
```

Represents vertical direction.

<a id="util-const-xy"></a>
##### `xy`

```ts
xy: xy
```

A string to indicate xy plane.

<a id="util-const-xyz"></a>
##### `xyz`

```ts
xyz: xyz
```

A string to indicate xyz space.

<a id="util-const-xz"></a>
##### `xz`

```ts
xz: xz
```

A string to indicate xz plane.

<a id="util-const-yz"></a>
##### `yz`

```ts
yz: yz
```

A string to indicate yz plane.

<a id="module-uheprng"></a>
## Module: `uheprng`

<a id="uheprng-default"></a>
### `default`

**Kind:** Function · **Source:** [`src/uheprng.ts:93`](https://github.com/williamngan/pts/blob/master/src/uheprng.ts#L93)

<a id="module-types"></a>
## Module: `Types`

<a id="types-iplayer"></a>
### `IPlayer`

**Kind:** Interface · **Source:** [`src/Types.ts:74`](https://github.com/williamngan/pts/blob/master/src/Types.ts#L74)

Typescript interface: IPlayer is an interface that represents a "player" object that can be added into a Space.

#### Methods

<a id="types-iplayer-action"></a>
##### `action`

*optional*

```ts
action?(type: string, px: number, py: number, evt: UIActionEvent): void
```

**Parameters**

- `type` (`string`)
- `px` (`number`)
- `py` (`number`)
- `evt` (`UIActionEvent`)

<a id="types-iplayer-resize"></a>
##### `resize`

*optional*

```ts
resize?(bound: Bound, evt: Event | null): void
```

**Parameters**

- `bound` (`Bound`)
- `evt` (`Event | null`)

<a id="types-iplayer-start"></a>
##### `start`

*optional*

```ts
start?(bound: Bound, space: Space): void
```

**Parameters**

- `bound` (`Bound`)
- `space` (`Space`)

#### Properties

<a id="types-iplayer-animate"></a>
##### `animate`

*optional*

```ts
animate?: AnimateCallbackFn
```

<a id="types-iplayer-animate-id"></a>
##### `animateID`

*optional*

```ts
animateID?: string
```

<a id="types-ipt"></a>
### `IPt`

**Kind:** Interface · **Source:** [`src/Types.ts:10`](https://github.com/williamngan/pts/blob/master/src/Types.ts#L10)

Typescript interface: IPt is an interface that represents an object with x, y, z, w properties.

#### Properties

<a id="types-ipt-w"></a>
##### `w`

*optional*

```ts
w?: number
```

<a id="types-ipt-x"></a>
##### `x`

*optional*

```ts
x?: number
```

<a id="types-ipt-y"></a>
##### `y`

*optional*

```ts
y?: number
```

<a id="types-ipt-z"></a>
##### `z`

*optional*

```ts
z?: number
```

<a id="types-ispaceplayers"></a>
### `ISpacePlayers`

**Kind:** Interface · **Source:** [`src/Types.ts:85`](https://github.com/williamngan/pts/blob/master/src/Types.ts#L85)

Typescript interface: ISpacePlayers represents a map of IPlayer instances.

<a id="types-itimer"></a>
### `ITimer`

**Kind:** Interface · **Source:** [`src/Types.ts:92`](https://github.com/williamngan/pts/blob/master/src/Types.ts#L92)

Typescript interface: ITimer represents a time-recording object.

#### Properties

<a id="types-itimer-diff"></a>
##### `diff`

```ts
diff: number
```

<a id="types-itimer-end"></a>
##### `end`

```ts
end: number
```

<a id="types-itimer-min"></a>
##### `min`

```ts
min: number
```

<a id="types-itimer-prev"></a>
##### `prev`

```ts
prev: number
```

<a id="types-multitouchelement"></a>
### `MultiTouchElement`

**Kind:** Interface · **Source:** [`src/Types.ts:107`](https://github.com/williamngan/pts/blob/master/src/Types.ts#L107)

Typescript interface: MultiTouchElement represents an element that can handle touch events.

#### Methods

<a id="types-multitouchelement-add-event-listener"></a>
##### `addEventListener`

```ts
addEventListener(evt: string, callback: EventListenerOrEventListenerObject): void
```

**Parameters**

- `evt` (`string`)
- `callback` (`EventListenerOrEventListenerObject`)

<a id="types-multitouchelement-remove-event-listener"></a>
##### `removeEventListener`

```ts
removeEventListener(evt: string, callback: EventListenerOrEventListenerObject): void
```

**Parameters**

- `evt` (`string`)
- `callback` (`EventListenerOrEventListenerObject`)

<a id="types-animatecallbackfn"></a>
### `AnimateCallbackFn`

**Kind:** Typealias · **Source:** [`src/Types.ts:59`](https://github.com/williamngan/pts/blob/master/src/Types.ts#L59)

Typescript type: AnimateCallbackFn represents a callback function for animation. It accepts parameters to keep track of current time, current frame-time, and current space instance.

```ts
type AnimateCallbackFn =  Fn(time:number, frameTime:number, currentSpace:Space);
```

<a id="types-canvaspatternrepetition"></a>
### `CanvasPatternRepetition`

**Kind:** Typealias · **Source:** [`src/Types.ts:314`](https://github.com/williamngan/pts/blob/master/src/Types.ts#L314)

Typescript type: CanvasPatternRepetition represents the string options to specify pattern repetition

```ts
type CanvasPatternRepetition = repeat | repeat-x | repeat-y | no-repeat;
```

<a id="types-canvasspaceoptions"></a>
### `CanvasSpaceOptions`

**Kind:** Typealias · **Source:** [`src/Types.ts:121`](https://github.com/williamngan/pts/blob/master/src/Types.ts#L121)

Typescript type: Setup options for CanvasSpace. See [`CanvasSpace.setup()`](#canvas-canvasspace-setup) function.

```ts
type CanvasSpaceOptions = { bgcolor:string, offscreen:boolean, pixelDensity:number, resize:boolean, retina:boolean };
```

<a id="types-colortype"></a>
### `ColorType`

**Kind:** Typealias · **Source:** [`src/Types.ts:132`](https://github.com/williamngan/pts/blob/master/src/Types.ts#L132)

Typescript type: ColorType represents a defined set of string values such as "rgb" and "lab".

```ts
type ColorType = rgb | hsl | hsb | lab | lch | luv | xyz | oklab | oklch;
```

<a id="types-defaultformstyle"></a>
### `DefaultFormStyle`

**Kind:** Typealias · **Source:** [`src/Types.ts:302`](https://github.com/williamngan/pts/blob/master/src/Types.ts#L302)

Typescript type: DefaultFormStyle represents a default object for visual styles such as fill, stroke, line width, and others.

```ts
type DefaultFormStyle = { fillStyle:string | CanvasGradient | CanvasPattern, globalAlpha:number, lineCap:CanvasLineCap, lineJoin:CanvasLineJoin, lineWidth:number, strokeStyle:string | CanvasGradient | CanvasPattern };
```

<a id="types-delaunaymesh"></a>
### `DelaunayMesh`

**Kind:** Typealias · **Source:** [`src/Types.ts:150`](https://github.com/williamngan/pts/blob/master/src/Types.ts#L150)

Typescript type: DelaunayMesh represents an object type that has an array of {key: shape} items, where each shape represents a DelaunayShape.
Note the unusual shape: it is an array indexed by point index, where each entry is a dictionary keyed by `"min-max"` neighbor-pair strings. This mirrors the mesh cache built by [`Delaunay.mesh`](#create-delaunay-mesh) and is kept as-is for compatibility.

```ts
type DelaunayMesh = [];
```

<a id="types-delaunayshape"></a>
### `DelaunayShape`

**Kind:** Typealias · **Source:** [`src/Types.ts:138`](https://github.com/williamngan/pts/blob/master/src/Types.ts#L138)

Typescript type: DelaunayShape represents an object type that can store a Delaunay element. It has 3 indices (i, j, k) and two groups that represent a triangle and a circle.

```ts
type DelaunayShape = { circle:Group, i:number, j:number, k:number, triangle:GroupLike };
```

<a id="types-domformcontext"></a>
### `DOMFormContext`

**Kind:** Typealias · **Source:** [`src/Types.ts:207`](https://github.com/williamngan/pts/blob/master/src/Types.ts#L207)

Typescript type: DOMFormContext represents the current context for an DOMForm.

```ts
type DOMFormContext = { currentClass:string, currentID:string, group:Element | null | undefined, groupCount:number, groupID:string, style:Record };
```

<a id="types-flockboundary"></a>
### `FlockBoundary`

**Kind:** Typealias · **Source:** [`src/Types.ts:157`](https://github.com/williamngan/pts/blob/master/src/Types.ts#L157)

Typescript type: FlockBoundary is how a [`Flock`](#create-flock) treats the edges of its bound:
`"steer"` turns agents back within a margin, `"wrap"` moves them to the opposite edge,
`"bounce"` reflects them, and `"none"` lets them leave.

```ts
type FlockBoundary = steer | wrap | bounce | none;
```

<a id="types-flockoptions"></a>
### `FlockOptions`

**Kind:** Typealias · **Source:** [`src/Types.ts:164`](https://github.com/williamngan/pts/blob/master/src/Types.ts#L164)

Typescript type: FlockOptions are the settings accepted by [`Create.flock`](#create-create-static-flock) and
[`Flock.setup`](#create-flock-setup). Every field is optional; see the matching [`Flock`](#create-flock) accessor
for its meaning and default.

```ts
type FlockOptions = { alignWeight:number, bound:GroupLike, boundary:FlockBoundary, cohesionWeight:number, initialSpeed:number, margin:number, maxForce:number, maxSpeed:number, maxTimeStep:number, minSpeed:number, perception:number, separateWeight:number, separation:number };
```

<a id="types-grouplike"></a>
### `GroupLike`

**Kind:** Typealias · **Source:** [`src/Types.ts:25`](https://github.com/williamngan/pts/blob/master/src/Types.ts#L25)

Typescript type: GroupLike represents an array of Pt instances. It be a Group instance or an array of Pt. Unlike `PtIterable`, this type only allows arrays but not iterables.

```ts
type GroupLike = Group | Pt[];
```

<a id="types-intersectcontext"></a>
### `IntersectContext`

**Kind:** Typealias · **Source:** [`src/Types.ts:219`](https://github.com/williamngan/pts/blob/master/src/Types.ts#L219)

Typescript type: IntersectContext represents a type of an object that store the intersection info.

```ts
type IntersectContext = { dist:number, edge:Group, normal:Pt, other:unknown, vertex:Pt, which:number };
```

<a id="types-isoundanalyzer"></a>
### `ISoundAnalyzer`

**Kind:** Typealias · **Source:** [`src/Types.ts:288`](https://github.com/williamngan/pts/blob/master/src/Types.ts#L288)

Typescript type: ISoundAnalyzer represents an object that stores the AnalyzerNode properties

```ts
type ISoundAnalyzer = { data:Uint8Array, node:AnalyserNode, size:number };
```

<a id="types-itempolistener"></a>
### `ITempoListener`

**Kind:** Typealias · **Source:** [`src/Types.ts:261`](https://github.com/williamngan/pts/blob/master/src/Types.ts#L261)

Typescript type: ITempoListener represents a listener created by Tempo class

```ts
type ITempoListener = { beats:number | number[], continuous:boolean, count:number, duration:number, fn:ITempoStartFn | ITempoProgressFn, index:number, name:string, offset:number, period:number };
```

<a id="types-itempoprogressfn"></a>
### `ITempoProgressFn`

**Kind:** Typealias · **Source:** [`src/Types.ts:251`](https://github.com/williamngan/pts/blob/master/src/Types.ts#L251)

Typescript type: a callback function type used in `tempo.every(...).progress( fn )`

```ts
type ITempoProgressFn =  Fn(count:number, t:number, ms:number, start:boolean);
```

<a id="types-itemporesponses"></a>
### `ITempoResponses`

**Kind:** Typealias · **Source:** [`src/Types.ts:276`](https://github.com/williamngan/pts/blob/master/src/Types.ts#L276)

Typescript type: the return type of `tempo.every(...)`

```ts
type ITempoResponses = { progress: Fn(fn:ITempoProgressFn, offset:number, name:string), start: Fn(fn:ITempoStartFn, offset:number, name:string) };
```

<a id="types-itempostartfn"></a>
### `ITempoStartFn`

**Kind:** Typealias · **Source:** [`src/Types.ts:246`](https://github.com/williamngan/pts/blob/master/src/Types.ts#L246)

Typescript type: a callback function type used in `tempo.every(...).start( fn )`

```ts
type ITempoStartFn =  Fn(count:number);
```

<a id="types-poissondiskoptions"></a>
### `PoissonDiskOptions`

**Kind:** Typealias · **Source:** [`src/Types.ts:197`](https://github.com/williamngan/pts/blob/master/src/Types.ts#L197)

Typescript type: PoissonDiskOptions are the settings accepted by [`Create.sampling`](#create-create-static-sampling)
and [`PoissonDisk.setup`](#create-poissondisk-setup). Every field is optional.

```ts
type PoissonDiskOptions = { candidates:number, start:PtLike };
```

<a id="types-polygonlike"></a>
### `PolygonLike`

**Kind:** Typealias · **Source:** [`src/Types.ts:43`](https://github.com/williamngan/pts/blob/master/src/Types.ts#L43)

Typescript type: PolygonLike represents a polygon for [`Path`](#op-path): either one ring of points (any `PtLikeIterable`),
or a list of rings combined by the nonzero winding rule, such as the `Group[]` a Path function returns (an outer ring followed by its holes).

```ts
type PolygonLike = PtLikeIterable | Iterable;
```

<a id="types-ptiterable"></a>
### `PtIterable`

**Kind:** Typealias · **Source:** [`src/Types.ts:31`](https://github.com/williamngan/pts/blob/master/src/Types.ts#L31)

Typescript type: PtIterable represents an iterable list of Pt instances. Unlike `PtLikeIterable`, this type only allows Pt instances but not numbers' arrays.
If you aren't sure what this type means, treat this as a [`Group`](#pt-group) instance.

```ts
type PtIterable = GroupLike | Pt[] | Iterable;
```

<a id="types-ptlike"></a>
### `PtLike`

**Kind:** Typealias · **Source:** [`src/Types.ts:20`](https://github.com/williamngan/pts/blob/master/src/Types.ts#L20)

Typescript type: PtLike represents the data of a point. It can be either a Pt instance or an array of numbers.

```ts
type PtLike = Pt | Float32Array | number[];
```

<a id="types-ptlikeiterable"></a>
### `PtLikeIterable`

**Kind:** Typealias · **Source:** [`src/Types.ts:37`](https://github.com/williamngan/pts/blob/master/src/Types.ts#L37)

Typescript type: PtLikeIterable is the most flexible way to represent an iterable list of point data. For example, it can be a Group, an iterable of Pt instances, or an array of numbers' arrays.
If you aren't sure what this type means, treat this as a [`Group`](#pt-group) instance.

```ts
type PtLikeIterable = GroupLike | PtLike[] | Iterable;
```

<a id="types-renderingcontext2d"></a>
### `RenderingContext2D`

**Kind:** Typealias · **Source:** [`src/Types.ts:317`](https://github.com/williamngan/pts/blob/master/src/Types.ts#L317)

```ts
type RenderingContext2D = CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;
```

<a id="types-soundtype"></a>
### `SoundType`

**Kind:** Typealias · **Source:** [`src/Types.ts:297`](https://github.com/williamngan/pts/blob/master/src/Types.ts#L297)

Typescript type: SoundType represents a type of sound input. It corresponds to Sound.type property.

```ts
type SoundType = file | gen | input;
```

<a id="types-textmeasure"></a>
### `TextMeasure`

**Kind:** Typealias · **Source:** [`src/Types.ts:48`](https://github.com/williamngan/pts/blob/master/src/Types.ts#L48)

Typescript type: TextMeasure represents a function that returns the rendered width of a string of text, such as canvas context's `measureText` or an estimator created via [`Typography.textWidthEstimator`](#typography-typography-static-text-width-estimator).

```ts
type TextMeasure =  Fn(text:string);
```

<a id="types-textverticalalign"></a>
### `TextVerticalAlign`

**Kind:** Typealias · **Source:** [`src/Types.ts:53`](https://github.com/williamngan/pts/blob/master/src/Types.ts#L53)

Typescript type: TextVerticalAlign represents the vertical alignment options accepted by [`CanvasForm.textBox`](#canvas-canvasform-text-box) and [`CanvasForm.paragraphBox`](#canvas-canvasform-paragraph-box).

```ts
type TextVerticalAlign = top | start | middle | center | bottom | end;
```

<a id="types-touchpointskey"></a>
### `TouchPointsKey`

**Kind:** Typealias · **Source:** [`src/Types.ts:102`](https://github.com/williamngan/pts/blob/master/src/Types.ts#L102)

Typescript type: TouchPointsKey represents a set of acceptable string keys for defining touch action.

```ts
type TouchPointsKey = touches | changedTouches | targetTouches;
```

<a id="types-uiactionevent"></a>
### `UIActionEvent`

**Kind:** Typealias · **Source:** [`src/Types.ts:68`](https://github.com/williamngan/pts/blob/master/src/Types.ts#L68)

Typescript type: UIActionEvent represents the DOM events a Space dispatches to players and UI handlers — pointer, mouse, touch, and keyboard.

```ts
type UIActionEvent = MouseEvent | TouchEvent | PointerEvent | KeyboardEvent;
```

<a id="types-uihandler"></a>
### `UIHandler`

**Kind:** Typealias · **Source:** [`src/Types.ts:231`](https://github.com/williamngan/pts/blob/master/src/Types.ts#L231)

Typescript type: UIHandler represents a callback function to handle UI actions.

```ts
type UIHandler =  Fn(target:UI, pt:PtLike, type:UIPointerAction | string & , evt:UIActionEvent);
```

<a id="types-warningtype"></a>
### `WarningType`

**Kind:** Typealias · **Source:** [`src/Types.ts:241`](https://github.com/williamngan/pts/blob/master/src/Types.ts#L241)

Typescript type: WarningType specifies a level of warning for [`Util.warnLevel`](#util-util-static-warn-level).

```ts
type WarningType = error | warn | mute;
```
