This commit is contained in:
Akko
2025-08-04 18:57:35 +02:00
parent 8cf6e78a79
commit 9495868c2e
5030 changed files with 518594 additions and 17609 deletions

View File

@@ -0,0 +1,311 @@
import { Point } from '../../../../maths/point/Point';
import { ShapePath } from './ShapePath';
import type { Matrix } from '../../../../maths/matrix/Matrix';
import type { PointData } from '../../../../maths/point/PointData';
import type { Bounds } from '../../../container/bounds/Bounds';
import type { RoundedPoint } from './roundShape';
export interface PathInstruction {
action: 'moveTo' | 'lineTo' | 'quadraticCurveTo' | 'bezierCurveTo' | 'arc' | 'closePath' | 'addPath' | 'arcTo' | 'ellipse' | 'rect' | 'roundRect' | 'arcToSvg' | 'poly' | 'circle' | 'regularPoly' | 'roundPoly' | 'roundShape' | 'filletRect' | 'chamferRect';
data: any[];
}
/**
* The `GraphicsPath` class is designed to represent a graphical path consisting of multiple drawing instructions.
* This class serves as a collection of drawing commands that can be executed to render shapes and paths on a canvas or
* similar graphical context. It supports high-level drawing operations like lines, arcs, curves, and more, enabling
* complex graphic constructions with relative ease.
*/
export declare class GraphicsPath {
instructions: PathInstruction[];
/** unique id for this graphics path */
readonly uid: number;
private _dirty;
private _shapePath;
/**
* Provides access to the internal shape path, ensuring it is up-to-date with the current instructions.
* @returns The `ShapePath` instance associated with this `GraphicsPath`.
*/
get shapePath(): ShapePath;
/**
* Creates a `GraphicsPath` instance optionally from an SVG path string or an array of `PathInstruction`.
* @param instructions - An SVG path string or an array of `PathInstruction` objects.
*/
constructor(instructions?: string | PathInstruction[]);
/**
* Adds another `GraphicsPath` to this path, optionally applying a transformation.
* @param path - The `GraphicsPath` to add.
* @param transform - An optional transformation to apply to the added path.
* @returns The instance of the current object for chaining.
*/
addPath(path: GraphicsPath, transform?: Matrix): this;
/**
* Adds an arc to the path. The arc is centered at (x, y)
* position with radius `radius` starting at `startAngle` and ending at `endAngle`.
* @param x - The x-coordinate of the arc's center.
* @param y - The y-coordinate of the arc's center.
* @param radius - The radius of the arc.
* @param startAngle - The starting angle of the arc, in radians.
* @param endAngle - The ending angle of the arc, in radians.
* @param counterclockwise - Specifies whether the arc should be drawn in the anticlockwise direction. False by default.
* @returns The instance of the current object for chaining.
*/
arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, counterclockwise?: boolean): this;
/**
* Adds an arc to the path with the arc tangent to the line joining two specified points.
* The arc radius is specified by `radius`.
* @param x1 - The x-coordinate of the first point.
* @param y1 - The y-coordinate of the first point.
* @param x2 - The x-coordinate of the second point.
* @param y2 - The y-coordinate of the second point.
* @param radius - The radius of the arc.
* @returns The instance of the current object for chaining.
*/
arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): this;
/**
* Adds an SVG-style arc to the path, allowing for elliptical arcs based on the SVG spec.
* @param rx - The x-radius of the ellipse.
* @param ry - The y-radius of the ellipse.
* @param xAxisRotation - The rotation of the ellipse's x-axis relative
* to the x-axis of the coordinate system, in degrees.
* @param largeArcFlag - Determines if the arc should be greater than or less than 180 degrees.
* @param sweepFlag - Determines if the arc should be swept in a positive angle direction.
* @param x - The x-coordinate of the arc's end point.
* @param y - The y-coordinate of the arc's end point.
* @returns The instance of the current object for chaining.
*/
arcToSvg(rx: number, ry: number, xAxisRotation: number, largeArcFlag: number, sweepFlag: number, x: number, y: number): this;
/**
* Adds a cubic Bezier curve to the path.
* It requires three points: the first two are control points and the third one is the end point.
* The starting point is the last point in the current path.
* @param cp1x - The x-coordinate of the first control point.
* @param cp1y - The y-coordinate of the first control point.
* @param cp2x - The x-coordinate of the second control point.
* @param cp2y - The y-coordinate of the second control point.
* @param x - The x-coordinate of the end point.
* @param y - The y-coordinate of the end point.
* @param smoothness - Optional parameter to adjust the smoothness of the curve.
* @returns The instance of the current object for chaining.
*/
bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number, smoothness?: number): this;
/**
* Adds a cubic Bezier curve to the path.
* It requires two points: the second control point and the end point. The first control point is assumed to be
* The starting point is the last point in the current path.
* @param cp2x - The x-coordinate of the second control point.
* @param cp2y - The y-coordinate of the second control point.
* @param x - The x-coordinate of the end point.
* @param y - The y-coordinate of the end point.
* @param smoothness - Optional parameter to adjust the smoothness of the curve.
* @returns The instance of the current object for chaining.
*/
bezierCurveToShort(cp2x: number, cp2y: number, x: number, y: number, smoothness?: number): this;
/**
* Closes the current path by drawing a straight line back to the start.
* If the shape is already closed or there are no points in the path, this method does nothing.
* @returns The instance of the current object for chaining.
*/
closePath(): this;
/**
* Draws an ellipse at the specified location and with the given x and y radii.
* An optional transformation can be applied, allowing for rotation, scaling, and translation.
* @param x - The x-coordinate of the center of the ellipse.
* @param y - The y-coordinate of the center of the ellipse.
* @param radiusX - The horizontal radius of the ellipse.
* @param radiusY - The vertical radius of the ellipse.
* @param transform - An optional `Matrix` object to apply a transformation to the ellipse. This can include rotations.
* @returns The instance of the current object for chaining.
*/
ellipse(x: number, y: number, radiusX: number, radiusY: number, matrix?: Matrix): this;
/**
* Connects the current point to a new point with a straight line. This method updates the current path.
* @param x - The x-coordinate of the new point to connect to.
* @param y - The y-coordinate of the new point to connect to.
* @returns The instance of the current object for chaining.
*/
lineTo(x: number, y: number): this;
/**
* Sets the starting point for a new sub-path. Any subsequent drawing commands are considered part of this path.
* @param x - The x-coordinate for the starting point.
* @param y - The y-coordinate for the starting point.
* @returns The instance of the current object for chaining.
*/
moveTo(x: number, y: number): this;
/**
* Adds a quadratic curve to the path. It requires two points: the control point and the end point.
* The starting point is the last point in the current path.
* @param cp1x - The x-coordinate of the control point.
* @param cp1y - The y-coordinate of the control point.
* @param x - The x-coordinate of the end point.
* @param y - The y-coordinate of the end point.
* @param smoothness - Optional parameter to adjust the smoothness of the curve.
* @returns The instance of the current object for chaining.
*/
quadraticCurveTo(cpx: number, cpy: number, x: number, y: number, smoothness?: number): this;
/**
* Adds a quadratic curve to the path. It uses the previous point as the control point.
* @param x - The x-coordinate of the end point.
* @param y - The y-coordinate of the end point.
* @param smoothness - Optional parameter to adjust the smoothness of the curve.
* @returns The instance of the current object for chaining.
*/
quadraticCurveToShort(x: number, y: number, smoothness?: number): this;
/**
* Draws a rectangle shape. This method adds a new rectangle path to the current drawing.
* @param x - The x-coordinate of the top-left corner of the rectangle.
* @param y - The y-coordinate of the top-left corner of the rectangle.
* @param w - The width of the rectangle.
* @param h - The height of the rectangle.
* @param transform - An optional `Matrix` object to apply a transformation to the rectangle.
* @returns The instance of the current object for chaining.
*/
rect(x: number, y: number, w: number, h: number, transform?: Matrix): this;
/**
* Draws a circle shape. This method adds a new circle path to the current drawing.
* @param x - The x-coordinate of the center of the circle.
* @param y - The y-coordinate of the center of the circle.
* @param radius - The radius of the circle.
* @param transform - An optional `Matrix` object to apply a transformation to the circle.
* @returns The instance of the current object for chaining.
*/
circle(x: number, y: number, radius: number, transform?: Matrix): this;
/**
* Draws a rectangle with rounded corners.
* The corner radius can be specified to determine how rounded the corners should be.
* An optional transformation can be applied, which allows for rotation, scaling, and translation of the rectangle.
* @param x - The x-coordinate of the top-left corner of the rectangle.
* @param y - The y-coordinate of the top-left corner of the rectangle.
* @param w - The width of the rectangle.
* @param h - The height of the rectangle.
* @param radius - The radius of the rectangle's corners. If not specified, corners will be sharp.
* @param transform - An optional `Matrix` object to apply a transformation to the rectangle.
* @returns The instance of the current object for chaining.
*/
roundRect(x: number, y: number, w: number, h: number, radius?: number, transform?: Matrix): this;
/**
* Draws a polygon shape by specifying a sequence of points. This method allows for the creation of complex polygons,
* which can be both open and closed. An optional transformation can be applied, enabling the polygon to be scaled,
* rotated, or translated as needed.
* @param points - An array of numbers representing the x and y coordinates of the polygon's vertices, in sequence.
* @param close - A boolean indicating whether to close the polygon path. True by default.
* @param transform - An optional `Matrix` object to apply a transformation to the polygon.
* @returns The instance of the current object for chaining further drawing commands.
*/
poly(points: number[] | PointData[], close?: boolean, transform?: Matrix): this;
/**
* Draws a regular polygon with a specified number of sides. All sides and angles are equal.
* @param x - The x-coordinate of the center of the polygon.
* @param y - The y-coordinate of the center of the polygon.
* @param radius - The radius of the circumscribed circle of the polygon.
* @param sides - The number of sides of the polygon. Must be 3 or more.
* @param rotation - The rotation angle of the polygon, in radians. Zero by default.
* @param transform - An optional `Matrix` object to apply a transformation to the polygon.
* @returns The instance of the current object for chaining.
*/
regularPoly(x: number, y: number, radius: number, sides: number, rotation?: number, transform?: Matrix): this;
/**
* Draws a polygon with rounded corners.
* Similar to `regularPoly` but with the ability to round the corners of the polygon.
* @param x - The x-coordinate of the center of the polygon.
* @param y - The y-coordinate of the center of the polygon.
* @param radius - The radius of the circumscribed circle of the polygon.
* @param sides - The number of sides of the polygon. Must be 3 or more.
* @param corner - The radius of the rounding of the corners.
* @param rotation - The rotation angle of the polygon, in radians. Zero by default.
* @returns The instance of the current object for chaining.
*/
roundPoly(x: number, y: number, radius: number, sides: number, corner: number, rotation?: number): this;
/**
* Draws a shape with rounded corners. This function supports custom radius for each corner of the shape.
* Optionally, corners can be rounded using a quadratic curve instead of an arc, providing a different aesthetic.
* @param points - An array of `RoundedPoint` representing the corners of the shape to draw.
* A minimum of 3 points is required.
* @param radius - The default radius for the corners.
* This radius is applied to all corners unless overridden in `points`.
* @param useQuadratic - If set to true, rounded corners are drawn using a quadraticCurve
* method instead of an arc method. Defaults to false.
* @param smoothness - Specifies the smoothness of the curve when `useQuadratic` is true.
* Higher values make the curve smoother.
* @returns The instance of the current object for chaining.
*/
roundShape(points: RoundedPoint[], radius: number, useQuadratic?: boolean, smoothness?: number): this;
/**
* Draw Rectangle with fillet corners. This is much like rounded rectangle
* however it support negative numbers as well for the corner radius.
* @param x - Upper left corner of rect
* @param y - Upper right corner of rect
* @param width - Width of rect
* @param height - Height of rect
* @param fillet - accept negative or positive values
*/
filletRect(x: number, y: number, width: number, height: number, fillet: number): this;
/**
* Draw Rectangle with chamfer corners. These are angled corners.
* @param x - Upper left corner of rect
* @param y - Upper right corner of rect
* @param width - Width of rect
* @param height - Height of rect
* @param chamfer - non-zero real number, size of corner cutout
* @param transform
*/
chamferRect(x: number, y: number, width: number, height: number, chamfer: number, transform?: Matrix): this;
/**
* Draws a star shape centered at a specified location. This method allows for the creation
* of stars with a variable number of points, outer radius, optional inner radius, and rotation.
* The star is drawn as a closed polygon with alternating outer and inner vertices to create the star's points.
* An optional transformation can be applied to scale, rotate, or translate the star as needed.
* @param x - The x-coordinate of the center of the star.
* @param y - The y-coordinate of the center of the star.
* @param points - The number of points of the star.
* @param radius - The outer radius of the star (distance from the center to the outer points).
* @param innerRadius - Optional. The inner radius of the star
* (distance from the center to the inner points between the outer points).
* If not provided, defaults to half of the `radius`.
* @param rotation - Optional. The rotation of the star in radians, where 0 is aligned with the y-axis.
* Defaults to 0, meaning one point is directly upward.
* @param transform - An optional `Matrix` object to apply a transformation to the star.
* This can include rotations, scaling, and translations.
* @returns The instance of the current object for chaining further drawing commands.
*/
star(x: number, y: number, points: number, radius: number, innerRadius?: number, rotation?: number, transform?: Matrix): this;
/**
* Creates a copy of the current `GraphicsPath` instance. This method supports both shallow and deep cloning.
* A shallow clone copies the reference of the instructions array, while a deep clone creates a new array and
* copies each instruction individually, ensuring that modifications to the instructions of the cloned `GraphicsPath`
* do not affect the original `GraphicsPath` and vice versa.
* @param deep - A boolean flag indicating whether the clone should be deep.
* @returns A new `GraphicsPath` instance that is a clone of the current instance.
*/
clone(deep?: boolean): GraphicsPath;
clear(): this;
/**
* Applies a transformation matrix to all drawing instructions within the `GraphicsPath`.
* This method enables the modification of the path's geometry according to the provided
* transformation matrix, which can include translations, rotations, scaling, and skewing.
*
* Each drawing instruction in the path is updated to reflect the transformation,
* ensuring the visual representation of the path is consistent with the applied matrix.
*
* Note: The transformation is applied directly to the coordinates and control points of the drawing instructions,
* not to the path as a whole. This means the transformation's effects are baked into the individual instructions,
* allowing for fine-grained control over the path's appearance.
* @param matrix - A `Matrix` object representing the transformation to apply.
* @returns The instance of the current object for chaining further operations.
*/
transform(matrix: Matrix): this;
get bounds(): Bounds;
/**
* Retrieves the last point from the current drawing instructions in the `GraphicsPath`.
* This method is useful for operations that depend on the path's current endpoint,
* such as connecting subsequent shapes or paths. It supports various drawing instructions,
* ensuring the last point's position is accurately determined regardless of the path's complexity.
*
* If the last instruction is a `closePath`, the method iterates backward through the instructions
* until it finds an actionable instruction that defines a point (e.g., `moveTo`, `lineTo`,
* `quadraticCurveTo`, etc.). For compound paths added via `addPath`, it recursively retrieves
* the last point from the nested path.
* @param out - A `Point` object where the last point's coordinates will be stored.
* This object is modified directly to contain the result.
* @returns The `Point` object containing the last point's coordinates.
*/
getLastPoint(out: Point): Point;
}

View File

@@ -0,0 +1,452 @@
'use strict';
var Point = require('../../../../maths/point/Point.js');
var uid = require('../../../../utils/data/uid.js');
var warn = require('../../../../utils/logging/warn.js');
var SVGToGraphicsPath = require('../svg/SVGToGraphicsPath.js');
var ShapePath = require('./ShapePath.js');
"use strict";
class GraphicsPath {
/**
* Creates a `GraphicsPath` instance optionally from an SVG path string or an array of `PathInstruction`.
* @param instructions - An SVG path string or an array of `PathInstruction` objects.
*/
constructor(instructions) {
this.instructions = [];
/** unique id for this graphics path */
this.uid = uid.uid("graphicsPath");
this._dirty = true;
if (typeof instructions === "string") {
SVGToGraphicsPath.SVGToGraphicsPath(instructions, this);
} else {
this.instructions = instructions?.slice() ?? [];
}
}
/**
* Provides access to the internal shape path, ensuring it is up-to-date with the current instructions.
* @returns The `ShapePath` instance associated with this `GraphicsPath`.
*/
get shapePath() {
if (!this._shapePath) {
this._shapePath = new ShapePath.ShapePath(this);
}
if (this._dirty) {
this._dirty = false;
this._shapePath.buildPath();
}
return this._shapePath;
}
/**
* Adds another `GraphicsPath` to this path, optionally applying a transformation.
* @param path - The `GraphicsPath` to add.
* @param transform - An optional transformation to apply to the added path.
* @returns The instance of the current object for chaining.
*/
addPath(path, transform) {
path = path.clone();
this.instructions.push({ action: "addPath", data: [path, transform] });
this._dirty = true;
return this;
}
arc(...args) {
this.instructions.push({ action: "arc", data: args });
this._dirty = true;
return this;
}
arcTo(...args) {
this.instructions.push({ action: "arcTo", data: args });
this._dirty = true;
return this;
}
arcToSvg(...args) {
this.instructions.push({ action: "arcToSvg", data: args });
this._dirty = true;
return this;
}
bezierCurveTo(...args) {
this.instructions.push({ action: "bezierCurveTo", data: args });
this._dirty = true;
return this;
}
/**
* Adds a cubic Bezier curve to the path.
* It requires two points: the second control point and the end point. The first control point is assumed to be
* The starting point is the last point in the current path.
* @param cp2x - The x-coordinate of the second control point.
* @param cp2y - The y-coordinate of the second control point.
* @param x - The x-coordinate of the end point.
* @param y - The y-coordinate of the end point.
* @param smoothness - Optional parameter to adjust the smoothness of the curve.
* @returns The instance of the current object for chaining.
*/
bezierCurveToShort(cp2x, cp2y, x, y, smoothness) {
const last = this.instructions[this.instructions.length - 1];
const lastPoint = this.getLastPoint(Point.Point.shared);
let cp1x = 0;
let cp1y = 0;
if (!last || last.action !== "bezierCurveTo") {
cp1x = lastPoint.x;
cp1y = lastPoint.y;
} else {
cp1x = last.data[2];
cp1y = last.data[3];
const currentX = lastPoint.x;
const currentY = lastPoint.y;
cp1x = currentX + (currentX - cp1x);
cp1y = currentY + (currentY - cp1y);
}
this.instructions.push({ action: "bezierCurveTo", data: [cp1x, cp1y, cp2x, cp2y, x, y, smoothness] });
this._dirty = true;
return this;
}
/**
* Closes the current path by drawing a straight line back to the start.
* If the shape is already closed or there are no points in the path, this method does nothing.
* @returns The instance of the current object for chaining.
*/
closePath() {
this.instructions.push({ action: "closePath", data: [] });
this._dirty = true;
return this;
}
ellipse(...args) {
this.instructions.push({ action: "ellipse", data: args });
this._dirty = true;
return this;
}
lineTo(...args) {
this.instructions.push({ action: "lineTo", data: args });
this._dirty = true;
return this;
}
moveTo(...args) {
this.instructions.push({ action: "moveTo", data: args });
return this;
}
quadraticCurveTo(...args) {
this.instructions.push({ action: "quadraticCurveTo", data: args });
this._dirty = true;
return this;
}
/**
* Adds a quadratic curve to the path. It uses the previous point as the control point.
* @param x - The x-coordinate of the end point.
* @param y - The y-coordinate of the end point.
* @param smoothness - Optional parameter to adjust the smoothness of the curve.
* @returns The instance of the current object for chaining.
*/
quadraticCurveToShort(x, y, smoothness) {
const last = this.instructions[this.instructions.length - 1];
const lastPoint = this.getLastPoint(Point.Point.shared);
let cpx1 = 0;
let cpy1 = 0;
if (!last || last.action !== "quadraticCurveTo") {
cpx1 = lastPoint.x;
cpy1 = lastPoint.y;
} else {
cpx1 = last.data[0];
cpy1 = last.data[1];
const currentX = lastPoint.x;
const currentY = lastPoint.y;
cpx1 = currentX + (currentX - cpx1);
cpy1 = currentY + (currentY - cpy1);
}
this.instructions.push({ action: "quadraticCurveTo", data: [cpx1, cpy1, x, y, smoothness] });
this._dirty = true;
return this;
}
/**
* Draws a rectangle shape. This method adds a new rectangle path to the current drawing.
* @param x - The x-coordinate of the top-left corner of the rectangle.
* @param y - The y-coordinate of the top-left corner of the rectangle.
* @param w - The width of the rectangle.
* @param h - The height of the rectangle.
* @param transform - An optional `Matrix` object to apply a transformation to the rectangle.
* @returns The instance of the current object for chaining.
*/
rect(x, y, w, h, transform) {
this.instructions.push({ action: "rect", data: [x, y, w, h, transform] });
this._dirty = true;
return this;
}
/**
* Draws a circle shape. This method adds a new circle path to the current drawing.
* @param x - The x-coordinate of the center of the circle.
* @param y - The y-coordinate of the center of the circle.
* @param radius - The radius of the circle.
* @param transform - An optional `Matrix` object to apply a transformation to the circle.
* @returns The instance of the current object for chaining.
*/
circle(x, y, radius, transform) {
this.instructions.push({ action: "circle", data: [x, y, radius, transform] });
this._dirty = true;
return this;
}
roundRect(...args) {
this.instructions.push({ action: "roundRect", data: args });
this._dirty = true;
return this;
}
poly(...args) {
this.instructions.push({ action: "poly", data: args });
this._dirty = true;
return this;
}
regularPoly(...args) {
this.instructions.push({ action: "regularPoly", data: args });
this._dirty = true;
return this;
}
roundPoly(...args) {
this.instructions.push({ action: "roundPoly", data: args });
this._dirty = true;
return this;
}
roundShape(...args) {
this.instructions.push({ action: "roundShape", data: args });
this._dirty = true;
return this;
}
filletRect(...args) {
this.instructions.push({ action: "filletRect", data: args });
this._dirty = true;
return this;
}
chamferRect(...args) {
this.instructions.push({ action: "chamferRect", data: args });
this._dirty = true;
return this;
}
/**
* Draws a star shape centered at a specified location. This method allows for the creation
* of stars with a variable number of points, outer radius, optional inner radius, and rotation.
* The star is drawn as a closed polygon with alternating outer and inner vertices to create the star's points.
* An optional transformation can be applied to scale, rotate, or translate the star as needed.
* @param x - The x-coordinate of the center of the star.
* @param y - The y-coordinate of the center of the star.
* @param points - The number of points of the star.
* @param radius - The outer radius of the star (distance from the center to the outer points).
* @param innerRadius - Optional. The inner radius of the star
* (distance from the center to the inner points between the outer points).
* If not provided, defaults to half of the `radius`.
* @param rotation - Optional. The rotation of the star in radians, where 0 is aligned with the y-axis.
* Defaults to 0, meaning one point is directly upward.
* @param transform - An optional `Matrix` object to apply a transformation to the star.
* This can include rotations, scaling, and translations.
* @returns The instance of the current object for chaining further drawing commands.
*/
// eslint-disable-next-line max-len
star(x, y, points, radius, innerRadius, rotation, transform) {
innerRadius = innerRadius || radius / 2;
const startAngle = -1 * Math.PI / 2 + rotation;
const len = points * 2;
const delta = Math.PI * 2 / len;
const polygon = [];
for (let i = 0; i < len; i++) {
const r = i % 2 ? innerRadius : radius;
const angle = i * delta + startAngle;
polygon.push(
x + r * Math.cos(angle),
y + r * Math.sin(angle)
);
}
this.poly(polygon, true, transform);
return this;
}
/**
* Creates a copy of the current `GraphicsPath` instance. This method supports both shallow and deep cloning.
* A shallow clone copies the reference of the instructions array, while a deep clone creates a new array and
* copies each instruction individually, ensuring that modifications to the instructions of the cloned `GraphicsPath`
* do not affect the original `GraphicsPath` and vice versa.
* @param deep - A boolean flag indicating whether the clone should be deep.
* @returns A new `GraphicsPath` instance that is a clone of the current instance.
*/
clone(deep = false) {
const newGraphicsPath2D = new GraphicsPath();
if (!deep) {
newGraphicsPath2D.instructions = this.instructions.slice();
} else {
for (let i = 0; i < this.instructions.length; i++) {
const instruction = this.instructions[i];
newGraphicsPath2D.instructions.push({ action: instruction.action, data: instruction.data.slice() });
}
}
return newGraphicsPath2D;
}
clear() {
this.instructions.length = 0;
this._dirty = true;
return this;
}
/**
* Applies a transformation matrix to all drawing instructions within the `GraphicsPath`.
* This method enables the modification of the path's geometry according to the provided
* transformation matrix, which can include translations, rotations, scaling, and skewing.
*
* Each drawing instruction in the path is updated to reflect the transformation,
* ensuring the visual representation of the path is consistent with the applied matrix.
*
* Note: The transformation is applied directly to the coordinates and control points of the drawing instructions,
* not to the path as a whole. This means the transformation's effects are baked into the individual instructions,
* allowing for fine-grained control over the path's appearance.
* @param matrix - A `Matrix` object representing the transformation to apply.
* @returns The instance of the current object for chaining further operations.
*/
transform(matrix) {
if (matrix.isIdentity())
return this;
const a = matrix.a;
const b = matrix.b;
const c = matrix.c;
const d = matrix.d;
const tx = matrix.tx;
const ty = matrix.ty;
let x = 0;
let y = 0;
let cpx1 = 0;
let cpy1 = 0;
let cpx2 = 0;
let cpy2 = 0;
let rx = 0;
let ry = 0;
for (let i = 0; i < this.instructions.length; i++) {
const instruction = this.instructions[i];
const data = instruction.data;
switch (instruction.action) {
case "moveTo":
case "lineTo":
x = data[0];
y = data[1];
data[0] = a * x + c * y + tx;
data[1] = b * x + d * y + ty;
break;
case "bezierCurveTo":
cpx1 = data[0];
cpy1 = data[1];
cpx2 = data[2];
cpy2 = data[3];
x = data[4];
y = data[5];
data[0] = a * cpx1 + c * cpy1 + tx;
data[1] = b * cpx1 + d * cpy1 + ty;
data[2] = a * cpx2 + c * cpy2 + tx;
data[3] = b * cpx2 + d * cpy2 + ty;
data[4] = a * x + c * y + tx;
data[5] = b * x + d * y + ty;
break;
case "quadraticCurveTo":
cpx1 = data[0];
cpy1 = data[1];
x = data[2];
y = data[3];
data[0] = a * cpx1 + c * cpy1 + tx;
data[1] = b * cpx1 + d * cpy1 + ty;
data[2] = a * x + c * y + tx;
data[3] = b * x + d * y + ty;
break;
case "arcToSvg":
x = data[5];
y = data[6];
rx = data[0];
ry = data[1];
data[0] = a * rx + c * ry;
data[1] = b * rx + d * ry;
data[5] = a * x + c * y + tx;
data[6] = b * x + d * y + ty;
break;
case "circle":
data[4] = adjustTransform(data[3], matrix);
break;
case "rect":
data[4] = adjustTransform(data[4], matrix);
break;
case "ellipse":
data[8] = adjustTransform(data[8], matrix);
break;
case "roundRect":
data[5] = adjustTransform(data[5], matrix);
break;
case "addPath":
data[0].transform(matrix);
break;
case "poly":
data[2] = adjustTransform(data[2], matrix);
break;
default:
warn.warn("unknown transform action", instruction.action);
break;
}
}
this._dirty = true;
return this;
}
get bounds() {
return this.shapePath.bounds;
}
/**
* Retrieves the last point from the current drawing instructions in the `GraphicsPath`.
* This method is useful for operations that depend on the path's current endpoint,
* such as connecting subsequent shapes or paths. It supports various drawing instructions,
* ensuring the last point's position is accurately determined regardless of the path's complexity.
*
* If the last instruction is a `closePath`, the method iterates backward through the instructions
* until it finds an actionable instruction that defines a point (e.g., `moveTo`, `lineTo`,
* `quadraticCurveTo`, etc.). For compound paths added via `addPath`, it recursively retrieves
* the last point from the nested path.
* @param out - A `Point` object where the last point's coordinates will be stored.
* This object is modified directly to contain the result.
* @returns The `Point` object containing the last point's coordinates.
*/
getLastPoint(out) {
let index = this.instructions.length - 1;
let lastInstruction = this.instructions[index];
if (!lastInstruction) {
out.x = 0;
out.y = 0;
return out;
}
while (lastInstruction.action === "closePath") {
index--;
if (index < 0) {
out.x = 0;
out.y = 0;
return out;
}
lastInstruction = this.instructions[index];
}
switch (lastInstruction.action) {
case "moveTo":
case "lineTo":
out.x = lastInstruction.data[0];
out.y = lastInstruction.data[1];
break;
case "quadraticCurveTo":
out.x = lastInstruction.data[2];
out.y = lastInstruction.data[3];
break;
case "bezierCurveTo":
out.x = lastInstruction.data[4];
out.y = lastInstruction.data[5];
break;
case "arc":
case "arcToSvg":
out.x = lastInstruction.data[5];
out.y = lastInstruction.data[6];
break;
case "addPath":
lastInstruction.data[0].getLastPoint(out);
break;
}
return out;
}
}
function adjustTransform(currentMatrix, transform) {
if (currentMatrix) {
return currentMatrix.prepend(transform);
}
return transform.clone();
}
exports.GraphicsPath = GraphicsPath;
//# sourceMappingURL=GraphicsPath.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,450 @@
import { Point } from '../../../../maths/point/Point.mjs';
import { uid } from '../../../../utils/data/uid.mjs';
import { warn } from '../../../../utils/logging/warn.mjs';
import { SVGToGraphicsPath } from '../svg/SVGToGraphicsPath.mjs';
import { ShapePath } from './ShapePath.mjs';
"use strict";
class GraphicsPath {
/**
* Creates a `GraphicsPath` instance optionally from an SVG path string or an array of `PathInstruction`.
* @param instructions - An SVG path string or an array of `PathInstruction` objects.
*/
constructor(instructions) {
this.instructions = [];
/** unique id for this graphics path */
this.uid = uid("graphicsPath");
this._dirty = true;
if (typeof instructions === "string") {
SVGToGraphicsPath(instructions, this);
} else {
this.instructions = instructions?.slice() ?? [];
}
}
/**
* Provides access to the internal shape path, ensuring it is up-to-date with the current instructions.
* @returns The `ShapePath` instance associated with this `GraphicsPath`.
*/
get shapePath() {
if (!this._shapePath) {
this._shapePath = new ShapePath(this);
}
if (this._dirty) {
this._dirty = false;
this._shapePath.buildPath();
}
return this._shapePath;
}
/**
* Adds another `GraphicsPath` to this path, optionally applying a transformation.
* @param path - The `GraphicsPath` to add.
* @param transform - An optional transformation to apply to the added path.
* @returns The instance of the current object for chaining.
*/
addPath(path, transform) {
path = path.clone();
this.instructions.push({ action: "addPath", data: [path, transform] });
this._dirty = true;
return this;
}
arc(...args) {
this.instructions.push({ action: "arc", data: args });
this._dirty = true;
return this;
}
arcTo(...args) {
this.instructions.push({ action: "arcTo", data: args });
this._dirty = true;
return this;
}
arcToSvg(...args) {
this.instructions.push({ action: "arcToSvg", data: args });
this._dirty = true;
return this;
}
bezierCurveTo(...args) {
this.instructions.push({ action: "bezierCurveTo", data: args });
this._dirty = true;
return this;
}
/**
* Adds a cubic Bezier curve to the path.
* It requires two points: the second control point and the end point. The first control point is assumed to be
* The starting point is the last point in the current path.
* @param cp2x - The x-coordinate of the second control point.
* @param cp2y - The y-coordinate of the second control point.
* @param x - The x-coordinate of the end point.
* @param y - The y-coordinate of the end point.
* @param smoothness - Optional parameter to adjust the smoothness of the curve.
* @returns The instance of the current object for chaining.
*/
bezierCurveToShort(cp2x, cp2y, x, y, smoothness) {
const last = this.instructions[this.instructions.length - 1];
const lastPoint = this.getLastPoint(Point.shared);
let cp1x = 0;
let cp1y = 0;
if (!last || last.action !== "bezierCurveTo") {
cp1x = lastPoint.x;
cp1y = lastPoint.y;
} else {
cp1x = last.data[2];
cp1y = last.data[3];
const currentX = lastPoint.x;
const currentY = lastPoint.y;
cp1x = currentX + (currentX - cp1x);
cp1y = currentY + (currentY - cp1y);
}
this.instructions.push({ action: "bezierCurveTo", data: [cp1x, cp1y, cp2x, cp2y, x, y, smoothness] });
this._dirty = true;
return this;
}
/**
* Closes the current path by drawing a straight line back to the start.
* If the shape is already closed or there are no points in the path, this method does nothing.
* @returns The instance of the current object for chaining.
*/
closePath() {
this.instructions.push({ action: "closePath", data: [] });
this._dirty = true;
return this;
}
ellipse(...args) {
this.instructions.push({ action: "ellipse", data: args });
this._dirty = true;
return this;
}
lineTo(...args) {
this.instructions.push({ action: "lineTo", data: args });
this._dirty = true;
return this;
}
moveTo(...args) {
this.instructions.push({ action: "moveTo", data: args });
return this;
}
quadraticCurveTo(...args) {
this.instructions.push({ action: "quadraticCurveTo", data: args });
this._dirty = true;
return this;
}
/**
* Adds a quadratic curve to the path. It uses the previous point as the control point.
* @param x - The x-coordinate of the end point.
* @param y - The y-coordinate of the end point.
* @param smoothness - Optional parameter to adjust the smoothness of the curve.
* @returns The instance of the current object for chaining.
*/
quadraticCurveToShort(x, y, smoothness) {
const last = this.instructions[this.instructions.length - 1];
const lastPoint = this.getLastPoint(Point.shared);
let cpx1 = 0;
let cpy1 = 0;
if (!last || last.action !== "quadraticCurveTo") {
cpx1 = lastPoint.x;
cpy1 = lastPoint.y;
} else {
cpx1 = last.data[0];
cpy1 = last.data[1];
const currentX = lastPoint.x;
const currentY = lastPoint.y;
cpx1 = currentX + (currentX - cpx1);
cpy1 = currentY + (currentY - cpy1);
}
this.instructions.push({ action: "quadraticCurveTo", data: [cpx1, cpy1, x, y, smoothness] });
this._dirty = true;
return this;
}
/**
* Draws a rectangle shape. This method adds a new rectangle path to the current drawing.
* @param x - The x-coordinate of the top-left corner of the rectangle.
* @param y - The y-coordinate of the top-left corner of the rectangle.
* @param w - The width of the rectangle.
* @param h - The height of the rectangle.
* @param transform - An optional `Matrix` object to apply a transformation to the rectangle.
* @returns The instance of the current object for chaining.
*/
rect(x, y, w, h, transform) {
this.instructions.push({ action: "rect", data: [x, y, w, h, transform] });
this._dirty = true;
return this;
}
/**
* Draws a circle shape. This method adds a new circle path to the current drawing.
* @param x - The x-coordinate of the center of the circle.
* @param y - The y-coordinate of the center of the circle.
* @param radius - The radius of the circle.
* @param transform - An optional `Matrix` object to apply a transformation to the circle.
* @returns The instance of the current object for chaining.
*/
circle(x, y, radius, transform) {
this.instructions.push({ action: "circle", data: [x, y, radius, transform] });
this._dirty = true;
return this;
}
roundRect(...args) {
this.instructions.push({ action: "roundRect", data: args });
this._dirty = true;
return this;
}
poly(...args) {
this.instructions.push({ action: "poly", data: args });
this._dirty = true;
return this;
}
regularPoly(...args) {
this.instructions.push({ action: "regularPoly", data: args });
this._dirty = true;
return this;
}
roundPoly(...args) {
this.instructions.push({ action: "roundPoly", data: args });
this._dirty = true;
return this;
}
roundShape(...args) {
this.instructions.push({ action: "roundShape", data: args });
this._dirty = true;
return this;
}
filletRect(...args) {
this.instructions.push({ action: "filletRect", data: args });
this._dirty = true;
return this;
}
chamferRect(...args) {
this.instructions.push({ action: "chamferRect", data: args });
this._dirty = true;
return this;
}
/**
* Draws a star shape centered at a specified location. This method allows for the creation
* of stars with a variable number of points, outer radius, optional inner radius, and rotation.
* The star is drawn as a closed polygon with alternating outer and inner vertices to create the star's points.
* An optional transformation can be applied to scale, rotate, or translate the star as needed.
* @param x - The x-coordinate of the center of the star.
* @param y - The y-coordinate of the center of the star.
* @param points - The number of points of the star.
* @param radius - The outer radius of the star (distance from the center to the outer points).
* @param innerRadius - Optional. The inner radius of the star
* (distance from the center to the inner points between the outer points).
* If not provided, defaults to half of the `radius`.
* @param rotation - Optional. The rotation of the star in radians, where 0 is aligned with the y-axis.
* Defaults to 0, meaning one point is directly upward.
* @param transform - An optional `Matrix` object to apply a transformation to the star.
* This can include rotations, scaling, and translations.
* @returns The instance of the current object for chaining further drawing commands.
*/
// eslint-disable-next-line max-len
star(x, y, points, radius, innerRadius, rotation, transform) {
innerRadius = innerRadius || radius / 2;
const startAngle = -1 * Math.PI / 2 + rotation;
const len = points * 2;
const delta = Math.PI * 2 / len;
const polygon = [];
for (let i = 0; i < len; i++) {
const r = i % 2 ? innerRadius : radius;
const angle = i * delta + startAngle;
polygon.push(
x + r * Math.cos(angle),
y + r * Math.sin(angle)
);
}
this.poly(polygon, true, transform);
return this;
}
/**
* Creates a copy of the current `GraphicsPath` instance. This method supports both shallow and deep cloning.
* A shallow clone copies the reference of the instructions array, while a deep clone creates a new array and
* copies each instruction individually, ensuring that modifications to the instructions of the cloned `GraphicsPath`
* do not affect the original `GraphicsPath` and vice versa.
* @param deep - A boolean flag indicating whether the clone should be deep.
* @returns A new `GraphicsPath` instance that is a clone of the current instance.
*/
clone(deep = false) {
const newGraphicsPath2D = new GraphicsPath();
if (!deep) {
newGraphicsPath2D.instructions = this.instructions.slice();
} else {
for (let i = 0; i < this.instructions.length; i++) {
const instruction = this.instructions[i];
newGraphicsPath2D.instructions.push({ action: instruction.action, data: instruction.data.slice() });
}
}
return newGraphicsPath2D;
}
clear() {
this.instructions.length = 0;
this._dirty = true;
return this;
}
/**
* Applies a transformation matrix to all drawing instructions within the `GraphicsPath`.
* This method enables the modification of the path's geometry according to the provided
* transformation matrix, which can include translations, rotations, scaling, and skewing.
*
* Each drawing instruction in the path is updated to reflect the transformation,
* ensuring the visual representation of the path is consistent with the applied matrix.
*
* Note: The transformation is applied directly to the coordinates and control points of the drawing instructions,
* not to the path as a whole. This means the transformation's effects are baked into the individual instructions,
* allowing for fine-grained control over the path's appearance.
* @param matrix - A `Matrix` object representing the transformation to apply.
* @returns The instance of the current object for chaining further operations.
*/
transform(matrix) {
if (matrix.isIdentity())
return this;
const a = matrix.a;
const b = matrix.b;
const c = matrix.c;
const d = matrix.d;
const tx = matrix.tx;
const ty = matrix.ty;
let x = 0;
let y = 0;
let cpx1 = 0;
let cpy1 = 0;
let cpx2 = 0;
let cpy2 = 0;
let rx = 0;
let ry = 0;
for (let i = 0; i < this.instructions.length; i++) {
const instruction = this.instructions[i];
const data = instruction.data;
switch (instruction.action) {
case "moveTo":
case "lineTo":
x = data[0];
y = data[1];
data[0] = a * x + c * y + tx;
data[1] = b * x + d * y + ty;
break;
case "bezierCurveTo":
cpx1 = data[0];
cpy1 = data[1];
cpx2 = data[2];
cpy2 = data[3];
x = data[4];
y = data[5];
data[0] = a * cpx1 + c * cpy1 + tx;
data[1] = b * cpx1 + d * cpy1 + ty;
data[2] = a * cpx2 + c * cpy2 + tx;
data[3] = b * cpx2 + d * cpy2 + ty;
data[4] = a * x + c * y + tx;
data[5] = b * x + d * y + ty;
break;
case "quadraticCurveTo":
cpx1 = data[0];
cpy1 = data[1];
x = data[2];
y = data[3];
data[0] = a * cpx1 + c * cpy1 + tx;
data[1] = b * cpx1 + d * cpy1 + ty;
data[2] = a * x + c * y + tx;
data[3] = b * x + d * y + ty;
break;
case "arcToSvg":
x = data[5];
y = data[6];
rx = data[0];
ry = data[1];
data[0] = a * rx + c * ry;
data[1] = b * rx + d * ry;
data[5] = a * x + c * y + tx;
data[6] = b * x + d * y + ty;
break;
case "circle":
data[4] = adjustTransform(data[3], matrix);
break;
case "rect":
data[4] = adjustTransform(data[4], matrix);
break;
case "ellipse":
data[8] = adjustTransform(data[8], matrix);
break;
case "roundRect":
data[5] = adjustTransform(data[5], matrix);
break;
case "addPath":
data[0].transform(matrix);
break;
case "poly":
data[2] = adjustTransform(data[2], matrix);
break;
default:
warn("unknown transform action", instruction.action);
break;
}
}
this._dirty = true;
return this;
}
get bounds() {
return this.shapePath.bounds;
}
/**
* Retrieves the last point from the current drawing instructions in the `GraphicsPath`.
* This method is useful for operations that depend on the path's current endpoint,
* such as connecting subsequent shapes or paths. It supports various drawing instructions,
* ensuring the last point's position is accurately determined regardless of the path's complexity.
*
* If the last instruction is a `closePath`, the method iterates backward through the instructions
* until it finds an actionable instruction that defines a point (e.g., `moveTo`, `lineTo`,
* `quadraticCurveTo`, etc.). For compound paths added via `addPath`, it recursively retrieves
* the last point from the nested path.
* @param out - A `Point` object where the last point's coordinates will be stored.
* This object is modified directly to contain the result.
* @returns The `Point` object containing the last point's coordinates.
*/
getLastPoint(out) {
let index = this.instructions.length - 1;
let lastInstruction = this.instructions[index];
if (!lastInstruction) {
out.x = 0;
out.y = 0;
return out;
}
while (lastInstruction.action === "closePath") {
index--;
if (index < 0) {
out.x = 0;
out.y = 0;
return out;
}
lastInstruction = this.instructions[index];
}
switch (lastInstruction.action) {
case "moveTo":
case "lineTo":
out.x = lastInstruction.data[0];
out.y = lastInstruction.data[1];
break;
case "quadraticCurveTo":
out.x = lastInstruction.data[2];
out.y = lastInstruction.data[3];
break;
case "bezierCurveTo":
out.x = lastInstruction.data[4];
out.y = lastInstruction.data[5];
break;
case "arc":
case "arcToSvg":
out.x = lastInstruction.data[5];
out.y = lastInstruction.data[6];
break;
case "addPath":
lastInstruction.data[0].getLastPoint(out);
break;
}
return out;
}
}
function adjustTransform(currentMatrix, transform) {
if (currentMatrix) {
return currentMatrix.prepend(transform);
}
return transform.clone();
}
export { GraphicsPath };
//# sourceMappingURL=GraphicsPath.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,262 @@
import { Bounds } from '../../../container/bounds/Bounds';
import type { Matrix } from '../../../../maths/matrix/Matrix';
import type { PointData } from '../../../../maths/point/PointData';
import type { ShapePrimitive } from '../../../../maths/shapes/ShapePrimitive';
import type { GraphicsPath } from './GraphicsPath';
import type { RoundedPoint } from './roundShape';
/**
* The `ShapePath` class acts as a bridge between high-level drawing commands
* and the lower-level `GraphicsContext` rendering engine.
* It translates drawing commands, such as those for creating lines, arcs, ellipses, rectangles, and complex polygons, into a
* format that can be efficiently processed by a `GraphicsContext`. This includes handling path starts,
* ends, and transformations for shapes.
*
* It is used internally by `GraphicsPath` to build up the path.
* @memberof scene
*/
export declare class ShapePath {
/** The list of shape primitives that make up the path. */
shapePrimitives: {
shape: ShapePrimitive;
transform?: Matrix;
}[];
private _currentPoly;
private readonly _graphicsPath2D;
private readonly _bounds;
constructor(graphicsPath2D: GraphicsPath);
/**
* Sets the starting point for a new sub-path. Any subsequent drawing commands are considered part of this path.
* @param x - The x-coordinate for the starting point.
* @param y - The y-coordinate for the starting point.
* @returns The instance of the current object for chaining.
*/
moveTo(x: number, y: number): this;
/**
* Connects the current point to a new point with a straight line. This method updates the current path.
* @param x - The x-coordinate of the new point to connect to.
* @param y - The y-coordinate of the new point to connect to.
* @returns The instance of the current object for chaining.
*/
lineTo(x: number, y: number): this;
/**
* Adds an arc to the path. The arc is centered at (x, y)
* position with radius `radius` starting at `startAngle` and ending at `endAngle`.
* @param x - The x-coordinate of the arc's center.
* @param y - The y-coordinate of the arc's center.
* @param radius - The radius of the arc.
* @param startAngle - The starting angle of the arc, in radians.
* @param endAngle - The ending angle of the arc, in radians.
* @param counterclockwise - Specifies whether the arc should be drawn in the anticlockwise direction. False by default.
* @returns The instance of the current object for chaining.
*/
arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, counterclockwise: boolean): this;
/**
* Adds an arc to the path with the arc tangent to the line joining two specified points.
* The arc radius is specified by `radius`.
* @param x1 - The x-coordinate of the first point.
* @param y1 - The y-coordinate of the first point.
* @param x2 - The x-coordinate of the second point.
* @param y2 - The y-coordinate of the second point.
* @param radius - The radius of the arc.
* @returns The instance of the current object for chaining.
*/
arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): this;
/**
* Adds an SVG-style arc to the path, allowing for elliptical arcs based on the SVG spec.
* @param rx - The x-radius of the ellipse.
* @param ry - The y-radius of the ellipse.
* @param xAxisRotation - The rotation of the ellipse's x-axis relative
* to the x-axis of the coordinate system, in degrees.
* @param largeArcFlag - Determines if the arc should be greater than or less than 180 degrees.
* @param sweepFlag - Determines if the arc should be swept in a positive angle direction.
* @param x - The x-coordinate of the arc's end point.
* @param y - The y-coordinate of the arc's end point.
* @returns The instance of the current object for chaining.
*/
arcToSvg(rx: number, ry: number, xAxisRotation: number, largeArcFlag: number, sweepFlag: number, x: number, y: number): this;
/**
* Adds a cubic Bezier curve to the path.
* It requires three points: the first two are control points and the third one is the end point.
* The starting point is the last point in the current path.
* @param cp1x - The x-coordinate of the first control point.
* @param cp1y - The y-coordinate of the first control point.
* @param cp2x - The x-coordinate of the second control point.
* @param cp2y - The y-coordinate of the second control point.
* @param x - The x-coordinate of the end point.
* @param y - The y-coordinate of the end point.
* @param smoothness - Optional parameter to adjust the smoothness of the curve.
* @returns The instance of the current object for chaining.
*/
bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number, smoothness?: number): this;
/**
* Adds a quadratic curve to the path. It requires two points: the control point and the end point.
* The starting point is the last point in the current path.
* @param cp1x - The x-coordinate of the control point.
* @param cp1y - The y-coordinate of the control point.
* @param x - The x-coordinate of the end point.
* @param y - The y-coordinate of the end point.
* @param smoothing - Optional parameter to adjust the smoothness of the curve.
* @returns The instance of the current object for chaining.
*/
quadraticCurveTo(cp1x: number, cp1y: number, x: number, y: number, smoothing?: number): this;
/**
* Closes the current path by drawing a straight line back to the start.
* If the shape is already closed or there are no points in the path, this method does nothing.
* @returns The instance of the current object for chaining.
*/
closePath(): this;
/**
* Adds another path to the current path. This method allows for the combination of multiple paths into one.
* @param path - The `GraphicsPath` object representing the path to add.
* @param transform - An optional `Matrix` object to apply a transformation to the path before adding it.
* @returns The instance of the current object for chaining.
*/
addPath(path: GraphicsPath, transform?: Matrix): this;
/**
* Finalizes the drawing of the current path. Optionally, it can close the path.
* @param closePath - A boolean indicating whether to close the path after finishing. False by default.
*/
finish(closePath?: boolean): void;
/**
* Draws a rectangle shape. This method adds a new rectangle path to the current drawing.
* @param x - The x-coordinate of the top-left corner of the rectangle.
* @param y - The y-coordinate of the top-left corner of the rectangle.
* @param w - The width of the rectangle.
* @param h - The height of the rectangle.
* @param transform - An optional `Matrix` object to apply a transformation to the rectangle.
* @returns The instance of the current object for chaining.
*/
rect(x: number, y: number, w: number, h: number, transform?: Matrix): this;
/**
* Draws a circle shape. This method adds a new circle path to the current drawing.
* @param x - The x-coordinate of the center of the circle.
* @param y - The y-coordinate of the center of the circle.
* @param radius - The radius of the circle.
* @param transform - An optional `Matrix` object to apply a transformation to the circle.
* @returns The instance of the current object for chaining.
*/
circle(x: number, y: number, radius: number, transform?: Matrix): this;
/**
* Draws a polygon shape. This method allows for the creation of complex polygons by specifying a sequence of points.
* @param points - An array of numbers, or or an array of PointData objects eg [{x,y}, {x,y}, {x,y}]
* representing the x and y coordinates of the polygon's vertices, in sequence.
* @param close - A boolean indicating whether to close the polygon path. True by default.
* @param transform - An optional `Matrix` object to apply a transformation to the polygon.
* @returns The instance of the current object for chaining.
*/
poly(points: number[] | PointData[], close?: boolean, transform?: Matrix): this;
/**
* Draws a regular polygon with a specified number of sides. All sides and angles are equal.
* @param x - The x-coordinate of the center of the polygon.
* @param y - The y-coordinate of the center of the polygon.
* @param radius - The radius of the circumscribed circle of the polygon.
* @param sides - The number of sides of the polygon. Must be 3 or more.
* @param rotation - The rotation angle of the polygon, in radians. Zero by default.
* @param transform - An optional `Matrix` object to apply a transformation to the polygon.
* @returns The instance of the current object for chaining.
*/
regularPoly(x: number, y: number, radius: number, sides: number, rotation?: number, transform?: Matrix): this;
/**
* Draws a polygon with rounded corners.
* Similar to `regularPoly` but with the ability to round the corners of the polygon.
* @param x - The x-coordinate of the center of the polygon.
* @param y - The y-coordinate of the center of the polygon.
* @param radius - The radius of the circumscribed circle of the polygon.
* @param sides - The number of sides of the polygon. Must be 3 or more.
* @param corner - The radius of the rounding of the corners.
* @param rotation - The rotation angle of the polygon, in radians. Zero by default.
* @param smoothness - Optional parameter to adjust the smoothness of the rounding.
* @returns The instance of the current object for chaining.
*/
roundPoly(x: number, y: number, radius: number, sides: number, corner: number, rotation?: number, smoothness?: number): this;
/**
* Draws a shape with rounded corners. This function supports custom radius for each corner of the shape.
* Optionally, corners can be rounded using a quadratic curve instead of an arc, providing a different aesthetic.
* @param points - An array of `RoundedPoint` representing the corners of the shape to draw.
* A minimum of 3 points is required.
* @param radius - The default radius for the corners.
* This radius is applied to all corners unless overridden in `points`.
* @param useQuadratic - If set to true, rounded corners are drawn using a quadraticCurve
* method instead of an arc method. Defaults to false.
* @param smoothness - Specifies the smoothness of the curve when `useQuadratic` is true.
* Higher values make the curve smoother.
* @returns The instance of the current object for chaining.
*/
roundShape(points: RoundedPoint[], radius: number, useQuadratic?: boolean, smoothness?: number): this;
/**
* Draw Rectangle with fillet corners. This is much like rounded rectangle
* however it support negative numbers as well for the corner radius.
* @param x - Upper left corner of rect
* @param y - Upper right corner of rect
* @param width - Width of rect
* @param height - Height of rect
* @param fillet - accept negative or positive values
*/
filletRect(x: number, y: number, width: number, height: number, fillet: number): this;
/**
* Draw Rectangle with chamfer corners. These are angled corners.
* @param x - Upper left corner of rect
* @param y - Upper right corner of rect
* @param width - Width of rect
* @param height - Height of rect
* @param chamfer - non-zero real number, size of corner cutout
* @param transform
*/
chamferRect(x: number, y: number, width: number, height: number, chamfer: number, transform?: Matrix): this;
/**
* Draws an ellipse at the specified location and with the given x and y radii.
* An optional transformation can be applied, allowing for rotation, scaling, and translation.
* @param x - The x-coordinate of the center of the ellipse.
* @param y - The y-coordinate of the center of the ellipse.
* @param radiusX - The horizontal radius of the ellipse.
* @param radiusY - The vertical radius of the ellipse.
* @param transform - An optional `Matrix` object to apply a transformation to the ellipse. This can include rotations.
* @returns The instance of the current object for chaining.
*/
ellipse(x: number, y: number, radiusX: number, radiusY: number, transform?: Matrix): this;
/**
* Draws a rectangle with rounded corners.
* The corner radius can be specified to determine how rounded the corners should be.
* An optional transformation can be applied, which allows for rotation, scaling, and translation of the rectangle.
* @param x - The x-coordinate of the top-left corner of the rectangle.
* @param y - The y-coordinate of the top-left corner of the rectangle.
* @param w - The width of the rectangle.
* @param h - The height of the rectangle.
* @param radius - The radius of the rectangle's corners. If not specified, corners will be sharp.
* @param transform - An optional `Matrix` object to apply a transformation to the rectangle.
* @returns The instance of the current object for chaining.
*/
roundRect(x: number, y: number, w: number, h: number, radius?: number, transform?: Matrix): this;
/**
* Draws a given shape on the canvas.
* This is a generic method that can draw any type of shape specified by the `ShapePrimitive` parameter.
* An optional transformation matrix can be applied to the shape, allowing for complex transformations.
* @param shape - The shape to draw, defined as a `ShapePrimitive` object.
* @param matrix - An optional `Matrix` for transforming the shape. This can include rotations,
* scaling, and translations.
* @returns The instance of the current object for chaining.
*/
drawShape(shape: ShapePrimitive, matrix?: Matrix): this;
/**
* Starts a new polygon path from the specified starting point.
* This method initializes a new polygon or ends the current one if it exists.
* @param x - The x-coordinate of the starting point of the new polygon.
* @param y - The y-coordinate of the starting point of the new polygon.
* @returns The instance of the current object for chaining.
*/
startPoly(x: number, y: number): this;
/**
* Ends the current polygon path. If `closePath` is set to true,
* the path is closed by connecting the last point to the first one.
* This method finalizes the current polygon and prepares it for drawing or adding to the shape primitives.
* @param closePath - A boolean indicating whether to close the polygon by connecting the last point
* back to the starting point. False by default.
* @returns The instance of the current object for chaining.
*/
endPoly(closePath?: boolean): this;
private _ensurePoly;
/** Builds the path. */
buildPath(): void;
/** Gets the bounds of the path. */
get bounds(): Bounds;
}

View File

@@ -0,0 +1,522 @@
'use strict';
var Circle = require('../../../../maths/shapes/Circle.js');
var Ellipse = require('../../../../maths/shapes/Ellipse.js');
var Polygon = require('../../../../maths/shapes/Polygon.js');
var Rectangle = require('../../../../maths/shapes/Rectangle.js');
var RoundedRectangle = require('../../../../maths/shapes/RoundedRectangle.js');
var Bounds = require('../../../container/bounds/Bounds.js');
var buildAdaptiveBezier = require('../buildCommands/buildAdaptiveBezier.js');
var buildAdaptiveQuadratic = require('../buildCommands/buildAdaptiveQuadratic.js');
var buildArc = require('../buildCommands/buildArc.js');
var buildArcTo = require('../buildCommands/buildArcTo.js');
var buildArcToSvg = require('../buildCommands/buildArcToSvg.js');
var roundShape = require('./roundShape.js');
"use strict";
const tempRectangle = new Rectangle.Rectangle();
class ShapePath {
constructor(graphicsPath2D) {
/** The list of shape primitives that make up the path. */
this.shapePrimitives = [];
this._currentPoly = null;
this._bounds = new Bounds.Bounds();
this._graphicsPath2D = graphicsPath2D;
}
/**
* Sets the starting point for a new sub-path. Any subsequent drawing commands are considered part of this path.
* @param x - The x-coordinate for the starting point.
* @param y - The y-coordinate for the starting point.
* @returns The instance of the current object for chaining.
*/
moveTo(x, y) {
this.startPoly(x, y);
return this;
}
/**
* Connects the current point to a new point with a straight line. This method updates the current path.
* @param x - The x-coordinate of the new point to connect to.
* @param y - The y-coordinate of the new point to connect to.
* @returns The instance of the current object for chaining.
*/
lineTo(x, y) {
this._ensurePoly();
const points = this._currentPoly.points;
const fromX = points[points.length - 2];
const fromY = points[points.length - 1];
if (fromX !== x || fromY !== y) {
points.push(x, y);
}
return this;
}
/**
* Adds an arc to the path. The arc is centered at (x, y)
* position with radius `radius` starting at `startAngle` and ending at `endAngle`.
* @param x - The x-coordinate of the arc's center.
* @param y - The y-coordinate of the arc's center.
* @param radius - The radius of the arc.
* @param startAngle - The starting angle of the arc, in radians.
* @param endAngle - The ending angle of the arc, in radians.
* @param counterclockwise - Specifies whether the arc should be drawn in the anticlockwise direction. False by default.
* @returns The instance of the current object for chaining.
*/
arc(x, y, radius, startAngle, endAngle, counterclockwise) {
this._ensurePoly(false);
const points = this._currentPoly.points;
buildArc.buildArc(points, x, y, radius, startAngle, endAngle, counterclockwise);
return this;
}
/**
* Adds an arc to the path with the arc tangent to the line joining two specified points.
* The arc radius is specified by `radius`.
* @param x1 - The x-coordinate of the first point.
* @param y1 - The y-coordinate of the first point.
* @param x2 - The x-coordinate of the second point.
* @param y2 - The y-coordinate of the second point.
* @param radius - The radius of the arc.
* @returns The instance of the current object for chaining.
*/
arcTo(x1, y1, x2, y2, radius) {
this._ensurePoly();
const points = this._currentPoly.points;
buildArcTo.buildArcTo(points, x1, y1, x2, y2, radius);
return this;
}
/**
* Adds an SVG-style arc to the path, allowing for elliptical arcs based on the SVG spec.
* @param rx - The x-radius of the ellipse.
* @param ry - The y-radius of the ellipse.
* @param xAxisRotation - The rotation of the ellipse's x-axis relative
* to the x-axis of the coordinate system, in degrees.
* @param largeArcFlag - Determines if the arc should be greater than or less than 180 degrees.
* @param sweepFlag - Determines if the arc should be swept in a positive angle direction.
* @param x - The x-coordinate of the arc's end point.
* @param y - The y-coordinate of the arc's end point.
* @returns The instance of the current object for chaining.
*/
arcToSvg(rx, ry, xAxisRotation, largeArcFlag, sweepFlag, x, y) {
const points = this._currentPoly.points;
buildArcToSvg.buildArcToSvg(
points,
this._currentPoly.lastX,
this._currentPoly.lastY,
x,
y,
rx,
ry,
xAxisRotation,
largeArcFlag,
sweepFlag
);
return this;
}
/**
* Adds a cubic Bezier curve to the path.
* It requires three points: the first two are control points and the third one is the end point.
* The starting point is the last point in the current path.
* @param cp1x - The x-coordinate of the first control point.
* @param cp1y - The y-coordinate of the first control point.
* @param cp2x - The x-coordinate of the second control point.
* @param cp2y - The y-coordinate of the second control point.
* @param x - The x-coordinate of the end point.
* @param y - The y-coordinate of the end point.
* @param smoothness - Optional parameter to adjust the smoothness of the curve.
* @returns The instance of the current object for chaining.
*/
bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y, smoothness) {
this._ensurePoly();
const currentPoly = this._currentPoly;
buildAdaptiveBezier.buildAdaptiveBezier(
this._currentPoly.points,
currentPoly.lastX,
currentPoly.lastY,
cp1x,
cp1y,
cp2x,
cp2y,
x,
y,
smoothness
);
return this;
}
/**
* Adds a quadratic curve to the path. It requires two points: the control point and the end point.
* The starting point is the last point in the current path.
* @param cp1x - The x-coordinate of the control point.
* @param cp1y - The y-coordinate of the control point.
* @param x - The x-coordinate of the end point.
* @param y - The y-coordinate of the end point.
* @param smoothing - Optional parameter to adjust the smoothness of the curve.
* @returns The instance of the current object for chaining.
*/
quadraticCurveTo(cp1x, cp1y, x, y, smoothing) {
this._ensurePoly();
const currentPoly = this._currentPoly;
buildAdaptiveQuadratic.buildAdaptiveQuadratic(
this._currentPoly.points,
currentPoly.lastX,
currentPoly.lastY,
cp1x,
cp1y,
x,
y,
smoothing
);
return this;
}
/**
* Closes the current path by drawing a straight line back to the start.
* If the shape is already closed or there are no points in the path, this method does nothing.
* @returns The instance of the current object for chaining.
*/
closePath() {
this.endPoly(true);
return this;
}
/**
* Adds another path to the current path. This method allows for the combination of multiple paths into one.
* @param path - The `GraphicsPath` object representing the path to add.
* @param transform - An optional `Matrix` object to apply a transformation to the path before adding it.
* @returns The instance of the current object for chaining.
*/
addPath(path, transform) {
this.endPoly();
if (transform && !transform.isIdentity()) {
path = path.clone(true);
path.transform(transform);
}
for (let i = 0; i < path.instructions.length; i++) {
const instruction = path.instructions[i];
this[instruction.action](...instruction.data);
}
return this;
}
/**
* Finalizes the drawing of the current path. Optionally, it can close the path.
* @param closePath - A boolean indicating whether to close the path after finishing. False by default.
*/
finish(closePath = false) {
this.endPoly(closePath);
}
/**
* Draws a rectangle shape. This method adds a new rectangle path to the current drawing.
* @param x - The x-coordinate of the top-left corner of the rectangle.
* @param y - The y-coordinate of the top-left corner of the rectangle.
* @param w - The width of the rectangle.
* @param h - The height of the rectangle.
* @param transform - An optional `Matrix` object to apply a transformation to the rectangle.
* @returns The instance of the current object for chaining.
*/
rect(x, y, w, h, transform) {
this.drawShape(new Rectangle.Rectangle(x, y, w, h), transform);
return this;
}
/**
* Draws a circle shape. This method adds a new circle path to the current drawing.
* @param x - The x-coordinate of the center of the circle.
* @param y - The y-coordinate of the center of the circle.
* @param radius - The radius of the circle.
* @param transform - An optional `Matrix` object to apply a transformation to the circle.
* @returns The instance of the current object for chaining.
*/
circle(x, y, radius, transform) {
this.drawShape(new Circle.Circle(x, y, radius), transform);
return this;
}
/**
* Draws a polygon shape. This method allows for the creation of complex polygons by specifying a sequence of points.
* @param points - An array of numbers, or or an array of PointData objects eg [{x,y}, {x,y}, {x,y}]
* representing the x and y coordinates of the polygon's vertices, in sequence.
* @param close - A boolean indicating whether to close the polygon path. True by default.
* @param transform - An optional `Matrix` object to apply a transformation to the polygon.
* @returns The instance of the current object for chaining.
*/
poly(points, close, transform) {
const polygon = new Polygon.Polygon(points);
polygon.closePath = close;
this.drawShape(polygon, transform);
return this;
}
/**
* Draws a regular polygon with a specified number of sides. All sides and angles are equal.
* @param x - The x-coordinate of the center of the polygon.
* @param y - The y-coordinate of the center of the polygon.
* @param radius - The radius of the circumscribed circle of the polygon.
* @param sides - The number of sides of the polygon. Must be 3 or more.
* @param rotation - The rotation angle of the polygon, in radians. Zero by default.
* @param transform - An optional `Matrix` object to apply a transformation to the polygon.
* @returns The instance of the current object for chaining.
*/
regularPoly(x, y, radius, sides, rotation = 0, transform) {
sides = Math.max(sides | 0, 3);
const startAngle = -1 * Math.PI / 2 + rotation;
const delta = Math.PI * 2 / sides;
const polygon = [];
for (let i = 0; i < sides; i++) {
const angle = i * delta + startAngle;
polygon.push(
x + radius * Math.cos(angle),
y + radius * Math.sin(angle)
);
}
this.poly(polygon, true, transform);
return this;
}
/**
* Draws a polygon with rounded corners.
* Similar to `regularPoly` but with the ability to round the corners of the polygon.
* @param x - The x-coordinate of the center of the polygon.
* @param y - The y-coordinate of the center of the polygon.
* @param radius - The radius of the circumscribed circle of the polygon.
* @param sides - The number of sides of the polygon. Must be 3 or more.
* @param corner - The radius of the rounding of the corners.
* @param rotation - The rotation angle of the polygon, in radians. Zero by default.
* @param smoothness - Optional parameter to adjust the smoothness of the rounding.
* @returns The instance of the current object for chaining.
*/
roundPoly(x, y, radius, sides, corner, rotation = 0, smoothness) {
sides = Math.max(sides | 0, 3);
if (corner <= 0) {
return this.regularPoly(x, y, radius, sides, rotation);
}
const sideLength = radius * Math.sin(Math.PI / sides) - 1e-3;
corner = Math.min(corner, sideLength);
const startAngle = -1 * Math.PI / 2 + rotation;
const delta = Math.PI * 2 / sides;
const internalAngle = (sides - 2) * Math.PI / sides / 2;
for (let i = 0; i < sides; i++) {
const angle = i * delta + startAngle;
const x0 = x + radius * Math.cos(angle);
const y0 = y + radius * Math.sin(angle);
const a1 = angle + Math.PI + internalAngle;
const a2 = angle - Math.PI - internalAngle;
const x1 = x0 + corner * Math.cos(a1);
const y1 = y0 + corner * Math.sin(a1);
const x3 = x0 + corner * Math.cos(a2);
const y3 = y0 + corner * Math.sin(a2);
if (i === 0) {
this.moveTo(x1, y1);
} else {
this.lineTo(x1, y1);
}
this.quadraticCurveTo(x0, y0, x3, y3, smoothness);
}
return this.closePath();
}
/**
* Draws a shape with rounded corners. This function supports custom radius for each corner of the shape.
* Optionally, corners can be rounded using a quadratic curve instead of an arc, providing a different aesthetic.
* @param points - An array of `RoundedPoint` representing the corners of the shape to draw.
* A minimum of 3 points is required.
* @param radius - The default radius for the corners.
* This radius is applied to all corners unless overridden in `points`.
* @param useQuadratic - If set to true, rounded corners are drawn using a quadraticCurve
* method instead of an arc method. Defaults to false.
* @param smoothness - Specifies the smoothness of the curve when `useQuadratic` is true.
* Higher values make the curve smoother.
* @returns The instance of the current object for chaining.
*/
roundShape(points, radius, useQuadratic = false, smoothness) {
if (points.length < 3) {
return this;
}
if (useQuadratic) {
roundShape.roundedShapeQuadraticCurve(this, points, radius, smoothness);
} else {
roundShape.roundedShapeArc(this, points, radius);
}
return this.closePath();
}
/**
* Draw Rectangle with fillet corners. This is much like rounded rectangle
* however it support negative numbers as well for the corner radius.
* @param x - Upper left corner of rect
* @param y - Upper right corner of rect
* @param width - Width of rect
* @param height - Height of rect
* @param fillet - accept negative or positive values
*/
filletRect(x, y, width, height, fillet) {
if (fillet === 0) {
return this.rect(x, y, width, height);
}
const maxFillet = Math.min(width, height) / 2;
const inset = Math.min(maxFillet, Math.max(-maxFillet, fillet));
const right = x + width;
const bottom = y + height;
const dir = inset < 0 ? -inset : 0;
const size = Math.abs(inset);
return this.moveTo(x, y + size).arcTo(x + dir, y + dir, x + size, y, size).lineTo(right - size, y).arcTo(right - dir, y + dir, right, y + size, size).lineTo(right, bottom - size).arcTo(right - dir, bottom - dir, x + width - size, bottom, size).lineTo(x + size, bottom).arcTo(x + dir, bottom - dir, x, bottom - size, size).closePath();
}
/**
* Draw Rectangle with chamfer corners. These are angled corners.
* @param x - Upper left corner of rect
* @param y - Upper right corner of rect
* @param width - Width of rect
* @param height - Height of rect
* @param chamfer - non-zero real number, size of corner cutout
* @param transform
*/
chamferRect(x, y, width, height, chamfer, transform) {
if (chamfer <= 0) {
return this.rect(x, y, width, height);
}
const inset = Math.min(chamfer, Math.min(width, height) / 2);
const right = x + width;
const bottom = y + height;
const points = [
x + inset,
y,
right - inset,
y,
right,
y + inset,
right,
bottom - inset,
right - inset,
bottom,
x + inset,
bottom,
x,
bottom - inset,
x,
y + inset
];
for (let i = points.length - 1; i >= 2; i -= 2) {
if (points[i] === points[i - 2] && points[i - 1] === points[i - 3]) {
points.splice(i - 1, 2);
}
}
return this.poly(points, true, transform);
}
/**
* Draws an ellipse at the specified location and with the given x and y radii.
* An optional transformation can be applied, allowing for rotation, scaling, and translation.
* @param x - The x-coordinate of the center of the ellipse.
* @param y - The y-coordinate of the center of the ellipse.
* @param radiusX - The horizontal radius of the ellipse.
* @param radiusY - The vertical radius of the ellipse.
* @param transform - An optional `Matrix` object to apply a transformation to the ellipse. This can include rotations.
* @returns The instance of the current object for chaining.
*/
ellipse(x, y, radiusX, radiusY, transform) {
this.drawShape(new Ellipse.Ellipse(x, y, radiusX, radiusY), transform);
return this;
}
/**
* Draws a rectangle with rounded corners.
* The corner radius can be specified to determine how rounded the corners should be.
* An optional transformation can be applied, which allows for rotation, scaling, and translation of the rectangle.
* @param x - The x-coordinate of the top-left corner of the rectangle.
* @param y - The y-coordinate of the top-left corner of the rectangle.
* @param w - The width of the rectangle.
* @param h - The height of the rectangle.
* @param radius - The radius of the rectangle's corners. If not specified, corners will be sharp.
* @param transform - An optional `Matrix` object to apply a transformation to the rectangle.
* @returns The instance of the current object for chaining.
*/
roundRect(x, y, w, h, radius, transform) {
this.drawShape(new RoundedRectangle.RoundedRectangle(x, y, w, h, radius), transform);
return this;
}
/**
* Draws a given shape on the canvas.
* This is a generic method that can draw any type of shape specified by the `ShapePrimitive` parameter.
* An optional transformation matrix can be applied to the shape, allowing for complex transformations.
* @param shape - The shape to draw, defined as a `ShapePrimitive` object.
* @param matrix - An optional `Matrix` for transforming the shape. This can include rotations,
* scaling, and translations.
* @returns The instance of the current object for chaining.
*/
drawShape(shape, matrix) {
this.endPoly();
this.shapePrimitives.push({ shape, transform: matrix });
return this;
}
/**
* Starts a new polygon path from the specified starting point.
* This method initializes a new polygon or ends the current one if it exists.
* @param x - The x-coordinate of the starting point of the new polygon.
* @param y - The y-coordinate of the starting point of the new polygon.
* @returns The instance of the current object for chaining.
*/
startPoly(x, y) {
let currentPoly = this._currentPoly;
if (currentPoly) {
this.endPoly();
}
currentPoly = new Polygon.Polygon();
currentPoly.points.push(x, y);
this._currentPoly = currentPoly;
return this;
}
/**
* Ends the current polygon path. If `closePath` is set to true,
* the path is closed by connecting the last point to the first one.
* This method finalizes the current polygon and prepares it for drawing or adding to the shape primitives.
* @param closePath - A boolean indicating whether to close the polygon by connecting the last point
* back to the starting point. False by default.
* @returns The instance of the current object for chaining.
*/
endPoly(closePath = false) {
const shape = this._currentPoly;
if (shape && shape.points.length > 2) {
shape.closePath = closePath;
this.shapePrimitives.push({ shape });
}
this._currentPoly = null;
return this;
}
_ensurePoly(start = true) {
if (this._currentPoly)
return;
this._currentPoly = new Polygon.Polygon();
if (start) {
const lastShape = this.shapePrimitives[this.shapePrimitives.length - 1];
if (lastShape) {
let lx = lastShape.shape.x;
let ly = lastShape.shape.y;
if (lastShape.transform && !lastShape.transform.isIdentity()) {
const t = lastShape.transform;
const tempX = lx;
lx = t.a * lx + t.c * ly + t.tx;
ly = t.b * tempX + t.d * ly + t.ty;
}
this._currentPoly.points.push(lx, ly);
} else {
this._currentPoly.points.push(0, 0);
}
}
}
/** Builds the path. */
buildPath() {
const path = this._graphicsPath2D;
this.shapePrimitives.length = 0;
this._currentPoly = null;
for (let i = 0; i < path.instructions.length; i++) {
const instruction = path.instructions[i];
this[instruction.action](...instruction.data);
}
this.finish();
}
/** Gets the bounds of the path. */
get bounds() {
const bounds = this._bounds;
bounds.clear();
const shapePrimitives = this.shapePrimitives;
for (let i = 0; i < shapePrimitives.length; i++) {
const shapePrimitive = shapePrimitives[i];
const boundsRect = shapePrimitive.shape.getBounds(tempRectangle);
if (shapePrimitive.transform) {
bounds.addRect(boundsRect, shapePrimitive.transform);
} else {
bounds.addRect(boundsRect);
}
}
return bounds;
}
}
exports.ShapePath = ShapePath;
//# sourceMappingURL=ShapePath.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,520 @@
import { Circle } from '../../../../maths/shapes/Circle.mjs';
import { Ellipse } from '../../../../maths/shapes/Ellipse.mjs';
import { Polygon } from '../../../../maths/shapes/Polygon.mjs';
import { Rectangle } from '../../../../maths/shapes/Rectangle.mjs';
import { RoundedRectangle } from '../../../../maths/shapes/RoundedRectangle.mjs';
import { Bounds } from '../../../container/bounds/Bounds.mjs';
import { buildAdaptiveBezier } from '../buildCommands/buildAdaptiveBezier.mjs';
import { buildAdaptiveQuadratic } from '../buildCommands/buildAdaptiveQuadratic.mjs';
import { buildArc } from '../buildCommands/buildArc.mjs';
import { buildArcTo } from '../buildCommands/buildArcTo.mjs';
import { buildArcToSvg } from '../buildCommands/buildArcToSvg.mjs';
import { roundedShapeQuadraticCurve, roundedShapeArc } from './roundShape.mjs';
"use strict";
const tempRectangle = new Rectangle();
class ShapePath {
constructor(graphicsPath2D) {
/** The list of shape primitives that make up the path. */
this.shapePrimitives = [];
this._currentPoly = null;
this._bounds = new Bounds();
this._graphicsPath2D = graphicsPath2D;
}
/**
* Sets the starting point for a new sub-path. Any subsequent drawing commands are considered part of this path.
* @param x - The x-coordinate for the starting point.
* @param y - The y-coordinate for the starting point.
* @returns The instance of the current object for chaining.
*/
moveTo(x, y) {
this.startPoly(x, y);
return this;
}
/**
* Connects the current point to a new point with a straight line. This method updates the current path.
* @param x - The x-coordinate of the new point to connect to.
* @param y - The y-coordinate of the new point to connect to.
* @returns The instance of the current object for chaining.
*/
lineTo(x, y) {
this._ensurePoly();
const points = this._currentPoly.points;
const fromX = points[points.length - 2];
const fromY = points[points.length - 1];
if (fromX !== x || fromY !== y) {
points.push(x, y);
}
return this;
}
/**
* Adds an arc to the path. The arc is centered at (x, y)
* position with radius `radius` starting at `startAngle` and ending at `endAngle`.
* @param x - The x-coordinate of the arc's center.
* @param y - The y-coordinate of the arc's center.
* @param radius - The radius of the arc.
* @param startAngle - The starting angle of the arc, in radians.
* @param endAngle - The ending angle of the arc, in radians.
* @param counterclockwise - Specifies whether the arc should be drawn in the anticlockwise direction. False by default.
* @returns The instance of the current object for chaining.
*/
arc(x, y, radius, startAngle, endAngle, counterclockwise) {
this._ensurePoly(false);
const points = this._currentPoly.points;
buildArc(points, x, y, radius, startAngle, endAngle, counterclockwise);
return this;
}
/**
* Adds an arc to the path with the arc tangent to the line joining two specified points.
* The arc radius is specified by `radius`.
* @param x1 - The x-coordinate of the first point.
* @param y1 - The y-coordinate of the first point.
* @param x2 - The x-coordinate of the second point.
* @param y2 - The y-coordinate of the second point.
* @param radius - The radius of the arc.
* @returns The instance of the current object for chaining.
*/
arcTo(x1, y1, x2, y2, radius) {
this._ensurePoly();
const points = this._currentPoly.points;
buildArcTo(points, x1, y1, x2, y2, radius);
return this;
}
/**
* Adds an SVG-style arc to the path, allowing for elliptical arcs based on the SVG spec.
* @param rx - The x-radius of the ellipse.
* @param ry - The y-radius of the ellipse.
* @param xAxisRotation - The rotation of the ellipse's x-axis relative
* to the x-axis of the coordinate system, in degrees.
* @param largeArcFlag - Determines if the arc should be greater than or less than 180 degrees.
* @param sweepFlag - Determines if the arc should be swept in a positive angle direction.
* @param x - The x-coordinate of the arc's end point.
* @param y - The y-coordinate of the arc's end point.
* @returns The instance of the current object for chaining.
*/
arcToSvg(rx, ry, xAxisRotation, largeArcFlag, sweepFlag, x, y) {
const points = this._currentPoly.points;
buildArcToSvg(
points,
this._currentPoly.lastX,
this._currentPoly.lastY,
x,
y,
rx,
ry,
xAxisRotation,
largeArcFlag,
sweepFlag
);
return this;
}
/**
* Adds a cubic Bezier curve to the path.
* It requires three points: the first two are control points and the third one is the end point.
* The starting point is the last point in the current path.
* @param cp1x - The x-coordinate of the first control point.
* @param cp1y - The y-coordinate of the first control point.
* @param cp2x - The x-coordinate of the second control point.
* @param cp2y - The y-coordinate of the second control point.
* @param x - The x-coordinate of the end point.
* @param y - The y-coordinate of the end point.
* @param smoothness - Optional parameter to adjust the smoothness of the curve.
* @returns The instance of the current object for chaining.
*/
bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y, smoothness) {
this._ensurePoly();
const currentPoly = this._currentPoly;
buildAdaptiveBezier(
this._currentPoly.points,
currentPoly.lastX,
currentPoly.lastY,
cp1x,
cp1y,
cp2x,
cp2y,
x,
y,
smoothness
);
return this;
}
/**
* Adds a quadratic curve to the path. It requires two points: the control point and the end point.
* The starting point is the last point in the current path.
* @param cp1x - The x-coordinate of the control point.
* @param cp1y - The y-coordinate of the control point.
* @param x - The x-coordinate of the end point.
* @param y - The y-coordinate of the end point.
* @param smoothing - Optional parameter to adjust the smoothness of the curve.
* @returns The instance of the current object for chaining.
*/
quadraticCurveTo(cp1x, cp1y, x, y, smoothing) {
this._ensurePoly();
const currentPoly = this._currentPoly;
buildAdaptiveQuadratic(
this._currentPoly.points,
currentPoly.lastX,
currentPoly.lastY,
cp1x,
cp1y,
x,
y,
smoothing
);
return this;
}
/**
* Closes the current path by drawing a straight line back to the start.
* If the shape is already closed or there are no points in the path, this method does nothing.
* @returns The instance of the current object for chaining.
*/
closePath() {
this.endPoly(true);
return this;
}
/**
* Adds another path to the current path. This method allows for the combination of multiple paths into one.
* @param path - The `GraphicsPath` object representing the path to add.
* @param transform - An optional `Matrix` object to apply a transformation to the path before adding it.
* @returns The instance of the current object for chaining.
*/
addPath(path, transform) {
this.endPoly();
if (transform && !transform.isIdentity()) {
path = path.clone(true);
path.transform(transform);
}
for (let i = 0; i < path.instructions.length; i++) {
const instruction = path.instructions[i];
this[instruction.action](...instruction.data);
}
return this;
}
/**
* Finalizes the drawing of the current path. Optionally, it can close the path.
* @param closePath - A boolean indicating whether to close the path after finishing. False by default.
*/
finish(closePath = false) {
this.endPoly(closePath);
}
/**
* Draws a rectangle shape. This method adds a new rectangle path to the current drawing.
* @param x - The x-coordinate of the top-left corner of the rectangle.
* @param y - The y-coordinate of the top-left corner of the rectangle.
* @param w - The width of the rectangle.
* @param h - The height of the rectangle.
* @param transform - An optional `Matrix` object to apply a transformation to the rectangle.
* @returns The instance of the current object for chaining.
*/
rect(x, y, w, h, transform) {
this.drawShape(new Rectangle(x, y, w, h), transform);
return this;
}
/**
* Draws a circle shape. This method adds a new circle path to the current drawing.
* @param x - The x-coordinate of the center of the circle.
* @param y - The y-coordinate of the center of the circle.
* @param radius - The radius of the circle.
* @param transform - An optional `Matrix` object to apply a transformation to the circle.
* @returns The instance of the current object for chaining.
*/
circle(x, y, radius, transform) {
this.drawShape(new Circle(x, y, radius), transform);
return this;
}
/**
* Draws a polygon shape. This method allows for the creation of complex polygons by specifying a sequence of points.
* @param points - An array of numbers, or or an array of PointData objects eg [{x,y}, {x,y}, {x,y}]
* representing the x and y coordinates of the polygon's vertices, in sequence.
* @param close - A boolean indicating whether to close the polygon path. True by default.
* @param transform - An optional `Matrix` object to apply a transformation to the polygon.
* @returns The instance of the current object for chaining.
*/
poly(points, close, transform) {
const polygon = new Polygon(points);
polygon.closePath = close;
this.drawShape(polygon, transform);
return this;
}
/**
* Draws a regular polygon with a specified number of sides. All sides and angles are equal.
* @param x - The x-coordinate of the center of the polygon.
* @param y - The y-coordinate of the center of the polygon.
* @param radius - The radius of the circumscribed circle of the polygon.
* @param sides - The number of sides of the polygon. Must be 3 or more.
* @param rotation - The rotation angle of the polygon, in radians. Zero by default.
* @param transform - An optional `Matrix` object to apply a transformation to the polygon.
* @returns The instance of the current object for chaining.
*/
regularPoly(x, y, radius, sides, rotation = 0, transform) {
sides = Math.max(sides | 0, 3);
const startAngle = -1 * Math.PI / 2 + rotation;
const delta = Math.PI * 2 / sides;
const polygon = [];
for (let i = 0; i < sides; i++) {
const angle = i * delta + startAngle;
polygon.push(
x + radius * Math.cos(angle),
y + radius * Math.sin(angle)
);
}
this.poly(polygon, true, transform);
return this;
}
/**
* Draws a polygon with rounded corners.
* Similar to `regularPoly` but with the ability to round the corners of the polygon.
* @param x - The x-coordinate of the center of the polygon.
* @param y - The y-coordinate of the center of the polygon.
* @param radius - The radius of the circumscribed circle of the polygon.
* @param sides - The number of sides of the polygon. Must be 3 or more.
* @param corner - The radius of the rounding of the corners.
* @param rotation - The rotation angle of the polygon, in radians. Zero by default.
* @param smoothness - Optional parameter to adjust the smoothness of the rounding.
* @returns The instance of the current object for chaining.
*/
roundPoly(x, y, radius, sides, corner, rotation = 0, smoothness) {
sides = Math.max(sides | 0, 3);
if (corner <= 0) {
return this.regularPoly(x, y, radius, sides, rotation);
}
const sideLength = radius * Math.sin(Math.PI / sides) - 1e-3;
corner = Math.min(corner, sideLength);
const startAngle = -1 * Math.PI / 2 + rotation;
const delta = Math.PI * 2 / sides;
const internalAngle = (sides - 2) * Math.PI / sides / 2;
for (let i = 0; i < sides; i++) {
const angle = i * delta + startAngle;
const x0 = x + radius * Math.cos(angle);
const y0 = y + radius * Math.sin(angle);
const a1 = angle + Math.PI + internalAngle;
const a2 = angle - Math.PI - internalAngle;
const x1 = x0 + corner * Math.cos(a1);
const y1 = y0 + corner * Math.sin(a1);
const x3 = x0 + corner * Math.cos(a2);
const y3 = y0 + corner * Math.sin(a2);
if (i === 0) {
this.moveTo(x1, y1);
} else {
this.lineTo(x1, y1);
}
this.quadraticCurveTo(x0, y0, x3, y3, smoothness);
}
return this.closePath();
}
/**
* Draws a shape with rounded corners. This function supports custom radius for each corner of the shape.
* Optionally, corners can be rounded using a quadratic curve instead of an arc, providing a different aesthetic.
* @param points - An array of `RoundedPoint` representing the corners of the shape to draw.
* A minimum of 3 points is required.
* @param radius - The default radius for the corners.
* This radius is applied to all corners unless overridden in `points`.
* @param useQuadratic - If set to true, rounded corners are drawn using a quadraticCurve
* method instead of an arc method. Defaults to false.
* @param smoothness - Specifies the smoothness of the curve when `useQuadratic` is true.
* Higher values make the curve smoother.
* @returns The instance of the current object for chaining.
*/
roundShape(points, radius, useQuadratic = false, smoothness) {
if (points.length < 3) {
return this;
}
if (useQuadratic) {
roundedShapeQuadraticCurve(this, points, radius, smoothness);
} else {
roundedShapeArc(this, points, radius);
}
return this.closePath();
}
/**
* Draw Rectangle with fillet corners. This is much like rounded rectangle
* however it support negative numbers as well for the corner radius.
* @param x - Upper left corner of rect
* @param y - Upper right corner of rect
* @param width - Width of rect
* @param height - Height of rect
* @param fillet - accept negative or positive values
*/
filletRect(x, y, width, height, fillet) {
if (fillet === 0) {
return this.rect(x, y, width, height);
}
const maxFillet = Math.min(width, height) / 2;
const inset = Math.min(maxFillet, Math.max(-maxFillet, fillet));
const right = x + width;
const bottom = y + height;
const dir = inset < 0 ? -inset : 0;
const size = Math.abs(inset);
return this.moveTo(x, y + size).arcTo(x + dir, y + dir, x + size, y, size).lineTo(right - size, y).arcTo(right - dir, y + dir, right, y + size, size).lineTo(right, bottom - size).arcTo(right - dir, bottom - dir, x + width - size, bottom, size).lineTo(x + size, bottom).arcTo(x + dir, bottom - dir, x, bottom - size, size).closePath();
}
/**
* Draw Rectangle with chamfer corners. These are angled corners.
* @param x - Upper left corner of rect
* @param y - Upper right corner of rect
* @param width - Width of rect
* @param height - Height of rect
* @param chamfer - non-zero real number, size of corner cutout
* @param transform
*/
chamferRect(x, y, width, height, chamfer, transform) {
if (chamfer <= 0) {
return this.rect(x, y, width, height);
}
const inset = Math.min(chamfer, Math.min(width, height) / 2);
const right = x + width;
const bottom = y + height;
const points = [
x + inset,
y,
right - inset,
y,
right,
y + inset,
right,
bottom - inset,
right - inset,
bottom,
x + inset,
bottom,
x,
bottom - inset,
x,
y + inset
];
for (let i = points.length - 1; i >= 2; i -= 2) {
if (points[i] === points[i - 2] && points[i - 1] === points[i - 3]) {
points.splice(i - 1, 2);
}
}
return this.poly(points, true, transform);
}
/**
* Draws an ellipse at the specified location and with the given x and y radii.
* An optional transformation can be applied, allowing for rotation, scaling, and translation.
* @param x - The x-coordinate of the center of the ellipse.
* @param y - The y-coordinate of the center of the ellipse.
* @param radiusX - The horizontal radius of the ellipse.
* @param radiusY - The vertical radius of the ellipse.
* @param transform - An optional `Matrix` object to apply a transformation to the ellipse. This can include rotations.
* @returns The instance of the current object for chaining.
*/
ellipse(x, y, radiusX, radiusY, transform) {
this.drawShape(new Ellipse(x, y, radiusX, radiusY), transform);
return this;
}
/**
* Draws a rectangle with rounded corners.
* The corner radius can be specified to determine how rounded the corners should be.
* An optional transformation can be applied, which allows for rotation, scaling, and translation of the rectangle.
* @param x - The x-coordinate of the top-left corner of the rectangle.
* @param y - The y-coordinate of the top-left corner of the rectangle.
* @param w - The width of the rectangle.
* @param h - The height of the rectangle.
* @param radius - The radius of the rectangle's corners. If not specified, corners will be sharp.
* @param transform - An optional `Matrix` object to apply a transformation to the rectangle.
* @returns The instance of the current object for chaining.
*/
roundRect(x, y, w, h, radius, transform) {
this.drawShape(new RoundedRectangle(x, y, w, h, radius), transform);
return this;
}
/**
* Draws a given shape on the canvas.
* This is a generic method that can draw any type of shape specified by the `ShapePrimitive` parameter.
* An optional transformation matrix can be applied to the shape, allowing for complex transformations.
* @param shape - The shape to draw, defined as a `ShapePrimitive` object.
* @param matrix - An optional `Matrix` for transforming the shape. This can include rotations,
* scaling, and translations.
* @returns The instance of the current object for chaining.
*/
drawShape(shape, matrix) {
this.endPoly();
this.shapePrimitives.push({ shape, transform: matrix });
return this;
}
/**
* Starts a new polygon path from the specified starting point.
* This method initializes a new polygon or ends the current one if it exists.
* @param x - The x-coordinate of the starting point of the new polygon.
* @param y - The y-coordinate of the starting point of the new polygon.
* @returns The instance of the current object for chaining.
*/
startPoly(x, y) {
let currentPoly = this._currentPoly;
if (currentPoly) {
this.endPoly();
}
currentPoly = new Polygon();
currentPoly.points.push(x, y);
this._currentPoly = currentPoly;
return this;
}
/**
* Ends the current polygon path. If `closePath` is set to true,
* the path is closed by connecting the last point to the first one.
* This method finalizes the current polygon and prepares it for drawing or adding to the shape primitives.
* @param closePath - A boolean indicating whether to close the polygon by connecting the last point
* back to the starting point. False by default.
* @returns The instance of the current object for chaining.
*/
endPoly(closePath = false) {
const shape = this._currentPoly;
if (shape && shape.points.length > 2) {
shape.closePath = closePath;
this.shapePrimitives.push({ shape });
}
this._currentPoly = null;
return this;
}
_ensurePoly(start = true) {
if (this._currentPoly)
return;
this._currentPoly = new Polygon();
if (start) {
const lastShape = this.shapePrimitives[this.shapePrimitives.length - 1];
if (lastShape) {
let lx = lastShape.shape.x;
let ly = lastShape.shape.y;
if (lastShape.transform && !lastShape.transform.isIdentity()) {
const t = lastShape.transform;
const tempX = lx;
lx = t.a * lx + t.c * ly + t.tx;
ly = t.b * tempX + t.d * ly + t.ty;
}
this._currentPoly.points.push(lx, ly);
} else {
this._currentPoly.points.push(0, 0);
}
}
}
/** Builds the path. */
buildPath() {
const path = this._graphicsPath2D;
this.shapePrimitives.length = 0;
this._currentPoly = null;
for (let i = 0; i < path.instructions.length; i++) {
const instruction = path.instructions[i];
this[instruction.action](...instruction.data);
}
this.finish();
}
/** Gets the bounds of the path. */
get bounds() {
const bounds = this._bounds;
bounds.clear();
const shapePrimitives = this.shapePrimitives;
for (let i = 0; i < shapePrimitives.length; i++) {
const shapePrimitive = shapePrimitives[i];
const boundsRect = shapePrimitive.shape.getBounds(tempRectangle);
if (shapePrimitive.transform) {
bounds.addRect(boundsRect, shapePrimitive.transform);
} else {
bounds.addRect(boundsRect);
}
}
return bounds;
}
}
export { ShapePath };
//# sourceMappingURL=ShapePath.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,23 @@
import type { PointData } from '../../../../maths/point/PointData';
import type { ShapePath } from './ShapePath';
/**
* Typed and cleaned up version of:
* https://stackoverflow.com/questions/44855794/html5-canvas-triangle-with-rounded-corners/44856925#44856925
* @param g - Graphics to be drawn on.
* @param points - Corners of the shape to draw. Minimum length is 3.
* @param radius - Corners default radius.
* @ignore
*/
export declare function roundedShapeArc(g: ShapePath, points: RoundedPoint[], radius: number): void;
export type RoundedPoint = PointData & {
radius?: number;
};
/**
* Typed and cleaned up version of:
* https://stackoverflow.com/questions/44855794/html5-canvas-triangle-with-rounded-corners/56214413#56214413
* @param g - Graphics to be drawn on.
* @param points - Corners of the shape to draw. Minimum length is 3.
* @param radius - Corners default radius.
* @ignore
*/
export declare function roundedShapeQuadraticCurve(g: ShapePath, points: RoundedPoint[], radius: number, smoothness?: number): void;

View File

@@ -0,0 +1,132 @@
'use strict';
"use strict";
function roundedShapeArc(g, points, radius) {
const vecFrom = (p, pp) => {
const x = pp.x - p.x;
const y = pp.y - p.y;
const len = Math.sqrt(x * x + y * y);
const nx = x / len;
const ny = y / len;
return { len, nx, ny };
};
const sharpCorner = (i, p) => {
if (i === 0) {
g.moveTo(p.x, p.y);
} else {
g.lineTo(p.x, p.y);
}
};
let p1 = points[points.length - 1];
for (let i = 0; i < points.length; i++) {
const p2 = points[i % points.length];
const pRadius = p2.radius ?? radius;
if (pRadius <= 0) {
sharpCorner(i, p2);
p1 = p2;
continue;
}
const p3 = points[(i + 1) % points.length];
const v1 = vecFrom(p2, p1);
const v2 = vecFrom(p2, p3);
if (v1.len < 1e-4 || v2.len < 1e-4) {
sharpCorner(i, p2);
p1 = p2;
continue;
}
let angle = Math.asin(v1.nx * v2.ny - v1.ny * v2.nx);
let radDirection = 1;
let drawDirection = false;
if (v1.nx * v2.nx - v1.ny * -v2.ny < 0) {
if (angle < 0) {
angle = Math.PI + angle;
} else {
angle = Math.PI - angle;
radDirection = -1;
drawDirection = true;
}
} else if (angle > 0) {
radDirection = -1;
drawDirection = true;
}
const halfAngle = angle / 2;
let cRadius;
let lenOut = Math.abs(
Math.cos(halfAngle) * pRadius / Math.sin(halfAngle)
);
if (lenOut > Math.min(v1.len / 2, v2.len / 2)) {
lenOut = Math.min(v1.len / 2, v2.len / 2);
cRadius = Math.abs(lenOut * Math.sin(halfAngle) / Math.cos(halfAngle));
} else {
cRadius = pRadius;
}
const cX = p2.x + v2.nx * lenOut + -v2.ny * cRadius * radDirection;
const cY = p2.y + v2.ny * lenOut + v2.nx * cRadius * radDirection;
const startAngle = Math.atan2(v1.ny, v1.nx) + Math.PI / 2 * radDirection;
const endAngle = Math.atan2(v2.ny, v2.nx) - Math.PI / 2 * radDirection;
if (i === 0) {
g.moveTo(
cX + Math.cos(startAngle) * cRadius,
cY + Math.sin(startAngle) * cRadius
);
}
g.arc(cX, cY, cRadius, startAngle, endAngle, drawDirection);
p1 = p2;
}
}
function roundedShapeQuadraticCurve(g, points, radius, smoothness) {
const distance = (p1, p2) => Math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2);
const pointLerp = (p1, p2, t) => ({
x: p1.x + (p2.x - p1.x) * t,
y: p1.y + (p2.y - p1.y) * t
});
const numPoints = points.length;
for (let i = 0; i < numPoints; i++) {
const thisPoint = points[(i + 1) % numPoints];
const pRadius = thisPoint.radius ?? radius;
if (pRadius <= 0) {
if (i === 0) {
g.moveTo(thisPoint.x, thisPoint.y);
} else {
g.lineTo(thisPoint.x, thisPoint.y);
}
continue;
}
const lastPoint = points[i];
const nextPoint = points[(i + 2) % numPoints];
const lastEdgeLength = distance(lastPoint, thisPoint);
let start;
if (lastEdgeLength < 1e-4) {
start = thisPoint;
} else {
const lastOffsetDistance = Math.min(lastEdgeLength / 2, pRadius);
start = pointLerp(
thisPoint,
lastPoint,
lastOffsetDistance / lastEdgeLength
);
}
const nextEdgeLength = distance(nextPoint, thisPoint);
let end;
if (nextEdgeLength < 1e-4) {
end = thisPoint;
} else {
const nextOffsetDistance = Math.min(nextEdgeLength / 2, pRadius);
end = pointLerp(
thisPoint,
nextPoint,
nextOffsetDistance / nextEdgeLength
);
}
if (i === 0) {
g.moveTo(start.x, start.y);
} else {
g.lineTo(start.x, start.y);
}
g.quadraticCurveTo(thisPoint.x, thisPoint.y, end.x, end.y, smoothness);
}
}
exports.roundedShapeArc = roundedShapeArc;
exports.roundedShapeQuadraticCurve = roundedShapeQuadraticCurve;
//# sourceMappingURL=roundShape.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,129 @@
"use strict";
function roundedShapeArc(g, points, radius) {
const vecFrom = (p, pp) => {
const x = pp.x - p.x;
const y = pp.y - p.y;
const len = Math.sqrt(x * x + y * y);
const nx = x / len;
const ny = y / len;
return { len, nx, ny };
};
const sharpCorner = (i, p) => {
if (i === 0) {
g.moveTo(p.x, p.y);
} else {
g.lineTo(p.x, p.y);
}
};
let p1 = points[points.length - 1];
for (let i = 0; i < points.length; i++) {
const p2 = points[i % points.length];
const pRadius = p2.radius ?? radius;
if (pRadius <= 0) {
sharpCorner(i, p2);
p1 = p2;
continue;
}
const p3 = points[(i + 1) % points.length];
const v1 = vecFrom(p2, p1);
const v2 = vecFrom(p2, p3);
if (v1.len < 1e-4 || v2.len < 1e-4) {
sharpCorner(i, p2);
p1 = p2;
continue;
}
let angle = Math.asin(v1.nx * v2.ny - v1.ny * v2.nx);
let radDirection = 1;
let drawDirection = false;
if (v1.nx * v2.nx - v1.ny * -v2.ny < 0) {
if (angle < 0) {
angle = Math.PI + angle;
} else {
angle = Math.PI - angle;
radDirection = -1;
drawDirection = true;
}
} else if (angle > 0) {
radDirection = -1;
drawDirection = true;
}
const halfAngle = angle / 2;
let cRadius;
let lenOut = Math.abs(
Math.cos(halfAngle) * pRadius / Math.sin(halfAngle)
);
if (lenOut > Math.min(v1.len / 2, v2.len / 2)) {
lenOut = Math.min(v1.len / 2, v2.len / 2);
cRadius = Math.abs(lenOut * Math.sin(halfAngle) / Math.cos(halfAngle));
} else {
cRadius = pRadius;
}
const cX = p2.x + v2.nx * lenOut + -v2.ny * cRadius * radDirection;
const cY = p2.y + v2.ny * lenOut + v2.nx * cRadius * radDirection;
const startAngle = Math.atan2(v1.ny, v1.nx) + Math.PI / 2 * radDirection;
const endAngle = Math.atan2(v2.ny, v2.nx) - Math.PI / 2 * radDirection;
if (i === 0) {
g.moveTo(
cX + Math.cos(startAngle) * cRadius,
cY + Math.sin(startAngle) * cRadius
);
}
g.arc(cX, cY, cRadius, startAngle, endAngle, drawDirection);
p1 = p2;
}
}
function roundedShapeQuadraticCurve(g, points, radius, smoothness) {
const distance = (p1, p2) => Math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2);
const pointLerp = (p1, p2, t) => ({
x: p1.x + (p2.x - p1.x) * t,
y: p1.y + (p2.y - p1.y) * t
});
const numPoints = points.length;
for (let i = 0; i < numPoints; i++) {
const thisPoint = points[(i + 1) % numPoints];
const pRadius = thisPoint.radius ?? radius;
if (pRadius <= 0) {
if (i === 0) {
g.moveTo(thisPoint.x, thisPoint.y);
} else {
g.lineTo(thisPoint.x, thisPoint.y);
}
continue;
}
const lastPoint = points[i];
const nextPoint = points[(i + 2) % numPoints];
const lastEdgeLength = distance(lastPoint, thisPoint);
let start;
if (lastEdgeLength < 1e-4) {
start = thisPoint;
} else {
const lastOffsetDistance = Math.min(lastEdgeLength / 2, pRadius);
start = pointLerp(
thisPoint,
lastPoint,
lastOffsetDistance / lastEdgeLength
);
}
const nextEdgeLength = distance(nextPoint, thisPoint);
let end;
if (nextEdgeLength < 1e-4) {
end = thisPoint;
} else {
const nextOffsetDistance = Math.min(nextEdgeLength / 2, pRadius);
end = pointLerp(
thisPoint,
nextPoint,
nextOffsetDistance / nextEdgeLength
);
}
if (i === 0) {
g.moveTo(start.x, start.y);
} else {
g.lineTo(start.x, start.y);
}
g.quadraticCurveTo(thisPoint.x, thisPoint.y, end.x, end.y, smoothness);
}
}
export { roundedShapeArc, roundedShapeQuadraticCurve };
//# sourceMappingURL=roundShape.mjs.map

File diff suppressed because one or more lines are too long