mirror of
https://github.com/excalidraw/excalidraw.git
synced 2026-12-05 18:55:28 +03:00
chore(packages/excalidraw): vendor roughjs as @excalidraw/sloppy (#12832)
* chore(packages/sloppy): vendor roughjs as @excalidraw/sloppy - port roughjs 4.6.4 with hachure-fill, path-data-parser and points-on-path into packages/sloppy - move points-on-curve and roughjs's Random into @excalidraw/math - output is identical to roughjs 4.6.4 (tests/parity.test.ts) * fix(packages/sloppy): don't change the caller's points in polygon pattern fills The fillers rotate a polygon's points in place and back, which left float drift in an element's points every time a sharp, pattern-filled line's shape was regenerated.
This commit is contained in:
1 parent
548eff0c3d
commit
b03c3bb2c6
62 files changed
+3838
-64
No files matched your search
+2
-1
@@ -67,9 +67,10 @@
|
||||
"build:history": "pnpm --dir packages/history build:esm",
|
||||
"build:excalidraw": "pnpm --dir packages/excalidraw build:esm",
|
||||
"build:math": "pnpm --dir packages/math build:esm",
|
||||
"build:sloppy": "pnpm --dir packages/sloppy build:esm",
|
||||
"build:fractional-indexing": "pnpm --dir packages/fractional-indexing build:esm",
|
||||
"build:laser-pointer": "pnpm --dir packages/laser-pointer build:esm",
|
||||
"build:packages": "pnpm build:common && pnpm build:fractional-indexing && pnpm build:laser-pointer && pnpm build:math && pnpm build:element && pnpm build:history && pnpm build:excalidraw",
|
||||
"build:packages": "pnpm build:common && pnpm build:fractional-indexing && pnpm build:laser-pointer && pnpm build:math && pnpm build:sloppy && pnpm build:element && pnpm build:history && pnpm build:excalidraw",
|
||||
"build:version": "pnpm --dir excalidraw-app build:version",
|
||||
"stats:bundle": "pnpm --dir excalidraw-app exec cross-env VITE_APP_ENABLE_TRACKING=true vite build --config ../scripts/stats/vite.config.mts",
|
||||
"stats:perf": "node ./scripts/stats/perf.mjs",
|
||||
|
||||
@@ -78,7 +78,6 @@
|
||||
"@excalidraw/math": "workspace:*",
|
||||
"es6-promise-pool": "2.5.0",
|
||||
"nanoid": "3.3.8",
|
||||
"roughjs": "4.6.4",
|
||||
"tinycolor2": "1.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { nanoid } from "nanoid";
|
||||
import { Random } from "roughjs/bin/math";
|
||||
import { Random } from "@excalidraw/math";
|
||||
|
||||
import { isTestEnv } from "./utils";
|
||||
|
||||
|
||||
@@ -90,10 +90,9 @@
|
||||
"@excalidraw/common": "workspace:*",
|
||||
"@excalidraw/fractional-indexing": "workspace:*",
|
||||
"@excalidraw/math": "workspace:*",
|
||||
"@excalidraw/sloppy": "workspace:*",
|
||||
"lodash.throttle": "4.1.1",
|
||||
"perfect-freehand": "1.2.0",
|
||||
"points-on-curve": "0.2.0",
|
||||
"roughjs": "4.6.4"
|
||||
"perfect-freehand": "1.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@excalidraw/laser-pointer": "workspace:*",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import rough from "roughjs/bin/rough";
|
||||
import { rough } from "@excalidraw/sloppy";
|
||||
import {
|
||||
arrayToMap,
|
||||
type Bounds,
|
||||
@@ -17,10 +17,9 @@ import {
|
||||
pointRotateRads,
|
||||
vectorDot,
|
||||
vectorFromPoint,
|
||||
pointsOnBezierCurves,
|
||||
} from "@excalidraw/math";
|
||||
|
||||
import { pointsOnBezierCurves } from "points-on-curve";
|
||||
|
||||
import type {
|
||||
Curve,
|
||||
Degrees,
|
||||
@@ -31,6 +30,10 @@ import type {
|
||||
} from "@excalidraw/math";
|
||||
import type { Mutable } from "@excalidraw/common/utility-types";
|
||||
|
||||
import type { Drawable, Op } from "@excalidraw/sloppy";
|
||||
|
||||
import type { RoughPoint } from "@excalidraw/sloppy";
|
||||
|
||||
import { getCurvePathOps, type GeometricShape } from "./geometricShapes";
|
||||
|
||||
import { ELBOW_ARROW_CORNER_RADIUS, generateRoughOptions } from "./shape";
|
||||
@@ -60,8 +63,6 @@ import {
|
||||
isFrameClippable,
|
||||
} from "./frame";
|
||||
|
||||
import type { Drawable, Op } from "roughjs/bin/core";
|
||||
import type { Point as RoughPoint } from "roughjs/bin/geometry";
|
||||
import type {
|
||||
Arrowhead,
|
||||
CardinalityArrowhead,
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
import { pointsOnBezierCurves, simplify } from "points-on-curve";
|
||||
import { curveToBezier } from "points-on-curve/lib/curve-to-bezier";
|
||||
|
||||
import {
|
||||
distanceToLineSegment,
|
||||
lineSegment,
|
||||
@@ -12,6 +9,9 @@ import {
|
||||
polygonIncludesPoint,
|
||||
polygonIncludesPointNonZero,
|
||||
polygonSignedArea,
|
||||
pointsOnBezierCurves,
|
||||
simplify,
|
||||
curveToBezier,
|
||||
} from "@excalidraw/math";
|
||||
|
||||
import { isOpaqueColor, isTransparent } from "@excalidraw/common";
|
||||
@@ -43,8 +43,6 @@ import {
|
||||
} from "./typeChecks";
|
||||
import { isPathALoop } from "./utils";
|
||||
|
||||
import type { Point } from "points-on-curve";
|
||||
|
||||
import type {
|
||||
ElementsMap,
|
||||
ExcalidrawElement,
|
||||
@@ -346,7 +344,7 @@ const lineElementIdealSegments = (
|
||||
const localPoints =
|
||||
element.roundness && element.points.length > 2
|
||||
? (pointsOnBezierCurves(
|
||||
curveToBezier(element.points as unknown as Point[]),
|
||||
curveToBezier(element.points as unknown as [number, number][]),
|
||||
// near-exact adaptive subdivision (the lib default); the sample
|
||||
// count is then bounded by the RDP pass below, which is the
|
||||
// actual fidelity knob
|
||||
|
||||
@@ -11,7 +11,6 @@
|
||||
* also included in this file are methods for converting an Excalidraw element or a Drawable from roughjs
|
||||
* to pure shapes
|
||||
*/
|
||||
import { pointsOnBezierCurves } from "points-on-curve";
|
||||
|
||||
import { invariant } from "@excalidraw/common";
|
||||
import {
|
||||
@@ -32,10 +31,13 @@ import {
|
||||
vectorScale,
|
||||
type GlobalPoint,
|
||||
type LocalPoint,
|
||||
pointsOnBezierCurves,
|
||||
} from "@excalidraw/math";
|
||||
|
||||
import type { Curve, LineSegment, Polygon, Radians } from "@excalidraw/math";
|
||||
|
||||
import type { Drawable, Op } from "@excalidraw/sloppy";
|
||||
|
||||
import type {
|
||||
ExcalidrawBindableElement,
|
||||
ExcalidrawDiamondElement,
|
||||
@@ -52,8 +54,6 @@ import type {
|
||||
ExcalidrawTextElement,
|
||||
} from "./types";
|
||||
|
||||
import type { Drawable, Op } from "roughjs/bin/core";
|
||||
|
||||
// a polyline (made up term here) is a line consisting of other line segments
|
||||
// this corresponds to a straight line element in the editor but it could also
|
||||
// be used to model other elements
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import rough from "roughjs/bin/rough";
|
||||
import { rough } from "@excalidraw/sloppy";
|
||||
|
||||
import {
|
||||
clamp,
|
||||
@@ -35,6 +35,8 @@ import {
|
||||
|
||||
import type { Zoom } from "@excalidraw/common";
|
||||
|
||||
import type { RoughCanvas } from "@excalidraw/sloppy";
|
||||
|
||||
import { getCreatePath, getRenderEnvironment } from "./renderEnvironment";
|
||||
|
||||
import { getElementAbsoluteCoords, getElementBounds } from "./bounds";
|
||||
@@ -83,7 +85,6 @@ import type {
|
||||
ElementsMap,
|
||||
} from "./types";
|
||||
|
||||
import type { RoughCanvas } from "roughjs/bin/canvas";
|
||||
import type { ElementsState } from "./types";
|
||||
import type {
|
||||
ElementRenderOverrides,
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { pointsOnBezierCurves, simplify } from "points-on-curve";
|
||||
import { getStroke, getStrokePoints } from "perfect-freehand";
|
||||
import { LaserPointer } from "@excalidraw/laser-pointer";
|
||||
|
||||
@@ -8,6 +7,8 @@ import {
|
||||
type LocalPoint,
|
||||
pointRotateRads,
|
||||
polygonFromPoints,
|
||||
pointsOnBezierCurves,
|
||||
simplify,
|
||||
} from "@excalidraw/math";
|
||||
import {
|
||||
ROUGHNESS,
|
||||
@@ -20,12 +21,16 @@ import {
|
||||
DEFAULT_STROKE_STREAMLINE,
|
||||
} from "@excalidraw/common";
|
||||
|
||||
import { RoughGenerator } from "roughjs/bin/generator";
|
||||
import { RoughGenerator } from "@excalidraw/sloppy";
|
||||
|
||||
import type { GlobalPoint, Polygon } from "@excalidraw/math";
|
||||
|
||||
import type { Mutable } from "@excalidraw/common/utility-types";
|
||||
|
||||
import type { Drawable, Options } from "@excalidraw/sloppy";
|
||||
|
||||
import type { RoughPoint } from "@excalidraw/sloppy";
|
||||
|
||||
import {
|
||||
type GeometricShape,
|
||||
getClosedCurveShape,
|
||||
@@ -71,8 +76,6 @@ import type {
|
||||
Arrowhead,
|
||||
} from "./types";
|
||||
|
||||
import type { Drawable, Options } from "roughjs/bin/core";
|
||||
import type { Point as RoughPoint } from "roughjs/bin/geometry";
|
||||
import type {
|
||||
EmbedsValidationStatus,
|
||||
ElementShape,
|
||||
|
||||
@@ -24,7 +24,7 @@ import type {
|
||||
ValueOf,
|
||||
} from "@excalidraw/common/utility-types";
|
||||
|
||||
import type { Drawable } from "roughjs/bin/core";
|
||||
import type { Drawable } from "@excalidraw/sloppy";
|
||||
|
||||
import type { LinearElementEditor } from "./linearElementEditor";
|
||||
import type { RenderEnvironment } from "./renderEnvironment";
|
||||
|
||||
@@ -13,6 +13,14 @@ Please add the latest change on the top under the correct section.
|
||||
|
||||
## Unreleased
|
||||
|
||||
### rough.js vendored as `@excalidraw/sloppy` (2026-12-03)
|
||||
|
||||
Breaking for TypeScript users of `@excalidraw/element` who pass their own rough.js objects in. Rendering is unchanged.
|
||||
|
||||
- The editor packages no longer depend on `roughjs`: its code (4.6.4, with `hachure-fill`, `path-data-parser` and `points-on-path`) now lives in the new `@excalidraw/sloppy` package. `points-on-curve`'s `pointsOnBezierCurves`, `simplify` and `curveToBezier`, and rough.js's `Random`, are now exported from `@excalidraw/math`.
|
||||
- `renderElement` and the other APIs typed with rough.js's `RoughCanvas`, `Drawable` or `Options` now take `@excalidraw/sloppy`'s. rough.js's own classes are no longer accepted by TypeScript (they work at runtime): create them with `import { rough } from "@excalidraw/sloppy"` (`rough.canvas(canvas)`, `rough.generator()`) instead.
|
||||
- Fix: rendering a sharp line with a hachure, cross-hatch or zigzag fill no longer changes its `points` by a tiny amount each time its shape is regenerated.
|
||||
|
||||
### Package exports: undo/redo store, editor helpers and shared types (2026-12-01)
|
||||
|
||||
Breaking for direct users of `@excalidraw/element`, `@excalidraw/common` and `@excalidraw/utils`. Adds the `@excalidraw/history` package. `@excalidraw/excalidraw` keeps all its exports and adds a few.
|
||||
|
||||
@@ -2,7 +2,7 @@ import clsx from "clsx";
|
||||
import throttle from "lodash.throttle";
|
||||
import React from "react";
|
||||
import { flushSync } from "react-dom";
|
||||
import rough from "roughjs/bin/rough";
|
||||
import { rough } from "@excalidraw/sloppy";
|
||||
import { nanoid } from "nanoid";
|
||||
|
||||
import { clamp, pointFrom, pointDistance } from "@excalidraw/math";
|
||||
@@ -249,6 +249,8 @@ import type {
|
||||
|
||||
import type { Mutable, ValueOf } from "@excalidraw/common/utility-types";
|
||||
|
||||
import type { RoughCanvas } from "@excalidraw/sloppy";
|
||||
|
||||
import {
|
||||
actionAddToLibrary,
|
||||
actionBringForward,
|
||||
@@ -482,7 +484,6 @@ import type {
|
||||
UIConfig,
|
||||
UIControl,
|
||||
} from "../types";
|
||||
import type { RoughCanvas } from "roughjs/bin/canvas";
|
||||
import type { Action, ActionResult } from "../actions/types";
|
||||
|
||||
const isUIConfig = (ui: AppProps["ui"]): ui is UIConfig =>
|
||||
|
||||
@@ -2,6 +2,8 @@ import { useEffect, useRef } from "react";
|
||||
|
||||
import type { NonDeletedSceneElementsMap } from "@excalidraw/element/types";
|
||||
|
||||
import type { RoughCanvas } from "@excalidraw/sloppy";
|
||||
|
||||
import { isRenderThrottlingEnabled } from "../../reactUtils";
|
||||
import { renderNewElementScene } from "../../renderer/renderNewElementScene";
|
||||
|
||||
@@ -10,7 +12,6 @@ import type {
|
||||
StaticCanvasRenderConfig,
|
||||
} from "../../scene/types";
|
||||
import type { AppState } from "../../types";
|
||||
import type { RoughCanvas } from "roughjs/bin/canvas";
|
||||
|
||||
interface NewElementCanvasProps {
|
||||
appState: AppState;
|
||||
|
||||
@@ -7,6 +7,8 @@ import type {
|
||||
NonDeletedSceneElementsMap,
|
||||
} from "@excalidraw/element/types";
|
||||
|
||||
import type { RoughCanvas } from "@excalidraw/sloppy";
|
||||
|
||||
import { isRenderThrottlingEnabled } from "../../reactUtils";
|
||||
import { renderStaticScene } from "../../renderer/staticScene";
|
||||
|
||||
@@ -15,7 +17,6 @@ import type {
|
||||
StaticCanvasRenderConfig,
|
||||
} from "../../scene/types";
|
||||
import type { AppState, StaticCanvasAppState } from "../../types";
|
||||
import type { RoughCanvas } from "roughjs/bin/canvas";
|
||||
|
||||
type StaticCanvasProps = {
|
||||
canvas: HTMLCanvasElement;
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import { simplify } from "points-on-curve";
|
||||
|
||||
import {
|
||||
polygonFromPoints,
|
||||
lineSegment,
|
||||
@@ -7,6 +5,7 @@ import {
|
||||
pointOnLineSegment,
|
||||
polygonIncludesPointNonZero,
|
||||
PRECISION,
|
||||
simplify,
|
||||
} from "@excalidraw/math";
|
||||
|
||||
import { type Bounds } from "@excalidraw/common";
|
||||
|
||||
@@ -139,6 +139,7 @@
|
||||
"@excalidraw/laser-pointer": "workspace:*",
|
||||
"@excalidraw/math": "workspace:*",
|
||||
"@excalidraw/mermaid-to-excalidraw": "3.6.0",
|
||||
"@excalidraw/sloppy": "workspace:*",
|
||||
"@lezer/highlight": "^1.0.0",
|
||||
"browser-fs-access": "0.38.0",
|
||||
"canvas-roundrect-polyfill": "0.0.1",
|
||||
@@ -158,10 +159,8 @@
|
||||
"png-chunk-text": "1.0.0",
|
||||
"png-chunks-encode": "1.0.0",
|
||||
"png-chunks-extract": "1.0.0",
|
||||
"points-on-curve": "0.2.0",
|
||||
"pwacompat": "2.0.17",
|
||||
"radix-ui": "1.4.3",
|
||||
"roughjs": "4.6.4",
|
||||
"sass": "1.51.0",
|
||||
"tunnel-rat": "0.1.2"
|
||||
},
|
||||
|
||||
@@ -52,10 +52,12 @@ import type {
|
||||
NonDeletedExcalidrawElement,
|
||||
} from "@excalidraw/element/types";
|
||||
|
||||
import type { Drawable } from "@excalidraw/sloppy";
|
||||
|
||||
import type { RoughSVG } from "@excalidraw/sloppy";
|
||||
|
||||
import type { RenderableElementsMap, SVGRenderConfig } from "../scene/types";
|
||||
import type { AppState, BinaryFiles } from "../types";
|
||||
import type { Drawable } from "roughjs/bin/core";
|
||||
import type { RoughSVG } from "roughjs/bin/svg";
|
||||
|
||||
const roughSVGDrawWithPrecision = (
|
||||
rsvg: RoughSVG,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import rough from "roughjs/bin/rough";
|
||||
import { rough } from "@excalidraw/sloppy";
|
||||
|
||||
import {
|
||||
FRAME_STYLE,
|
||||
|
||||
@@ -18,6 +18,8 @@ import type {
|
||||
StaticCanvasRenderConfig,
|
||||
} from "@excalidraw/element/types";
|
||||
|
||||
import type { RoughCanvas } from "@excalidraw/sloppy";
|
||||
|
||||
import type {
|
||||
AppClassProperties,
|
||||
AppState,
|
||||
@@ -26,7 +28,6 @@ import type {
|
||||
StaticCanvasAppState,
|
||||
SocketId,
|
||||
} from "../types";
|
||||
import type { RoughCanvas } from "roughjs/bin/canvas";
|
||||
|
||||
export type { RenderableElementsMap, StaticCanvasRenderConfig };
|
||||
|
||||
|
||||
@@ -8,9 +8,9 @@ import {
|
||||
|
||||
import type { LocalPoint } from "@excalidraw/math";
|
||||
|
||||
import { API } from "../helpers/api";
|
||||
import type { Op } from "@excalidraw/sloppy";
|
||||
|
||||
import type { Op } from "roughjs/bin/core";
|
||||
import { API } from "../helpers/api";
|
||||
|
||||
describe("arrowhead shapes", () => {
|
||||
it.each(["triangle", "diamond_outline", "circle"] as const)(
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import rough from "roughjs/bin/rough";
|
||||
import { rough } from "@excalidraw/sloppy";
|
||||
|
||||
import {
|
||||
elementWithCanvasCache,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// @vitest-environment-options {"url": "http://localhost/"}
|
||||
|
||||
import { RoughCanvas } from "roughjs/bin/canvas";
|
||||
import { RoughCanvas } from "@excalidraw/sloppy";
|
||||
|
||||
import { newElement } from "@excalidraw/element";
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React from "react";
|
||||
import rough from "roughjs/bin/rough";
|
||||
import { rough } from "@excalidraw/sloppy";
|
||||
|
||||
import * as Element from "@excalidraw/element";
|
||||
import {
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2020 Excalidraw
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
---
|
||||
|
||||
src/pointsOnCurve.ts, src/curveToBezier.ts and src/random.ts are ported from
|
||||
the following projects by Preet Shihn, released under the MIT License:
|
||||
|
||||
- points-on-curve 0.2.0, Copyright (c) 2020 Preet Shihn
|
||||
https://github.com/pshihn/bezier-points
|
||||
- roughjs 4.6.4 (src/math.ts), Copyright (c) 2019 Preet Shihn
|
||||
https://github.com/pshihn/rough
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2019 Preet Shihn
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,51 @@
|
||||
// Ported from points-on-curve@0.2.0 (src/curve-to-bezier.ts): https://github.com/pshihn/bezier-points
|
||||
// MIT License, Copyright (c) 2020 Preet Shihn. See LICENSE.
|
||||
|
||||
import type { Point } from "./pointsOnCurve";
|
||||
|
||||
function clone(p: Point): Point {
|
||||
return [...p] as Point;
|
||||
}
|
||||
|
||||
export function curveToBezier(pointsIn: Point[], curveTightness = 0): Point[] {
|
||||
const len = pointsIn.length;
|
||||
if (len < 3) {
|
||||
throw new Error("A curve must have at least three points.");
|
||||
}
|
||||
const out: Point[] = [];
|
||||
if (len === 3) {
|
||||
out.push(
|
||||
clone(pointsIn[0]),
|
||||
clone(pointsIn[1]),
|
||||
clone(pointsIn[2]),
|
||||
clone(pointsIn[2]),
|
||||
);
|
||||
} else {
|
||||
const points: Point[] = [];
|
||||
points.push(pointsIn[0], pointsIn[0]);
|
||||
for (let i = 1; i < pointsIn.length; i++) {
|
||||
points.push(pointsIn[i]);
|
||||
if (i === pointsIn.length - 1) {
|
||||
points.push(pointsIn[i]);
|
||||
}
|
||||
}
|
||||
const b: Point[] = [];
|
||||
const s = 1 - curveTightness;
|
||||
out.push(clone(points[0]));
|
||||
for (let i = 1; i + 2 < points.length; i++) {
|
||||
const cachedVertArray = points[i];
|
||||
b[0] = [cachedVertArray[0], cachedVertArray[1]];
|
||||
b[1] = [
|
||||
cachedVertArray[0] + (s * points[i + 1][0] - s * points[i - 1][0]) / 6,
|
||||
cachedVertArray[1] + (s * points[i + 1][1] - s * points[i - 1][1]) / 6,
|
||||
];
|
||||
b[2] = [
|
||||
points[i + 1][0] + (s * points[i][0] - s * points[i + 2][0]) / 6,
|
||||
points[i + 1][1] + (s * points[i][1] - s * points[i + 2][1]) / 6,
|
||||
];
|
||||
b[3] = [points[i + 1][0], points[i + 1][1]];
|
||||
out.push(b[1], b[2], b[3]);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -12,3 +12,6 @@ export * from "./triangle";
|
||||
export * from "./types";
|
||||
export * from "./vector";
|
||||
export * from "./utils";
|
||||
export { pointsOnBezierCurves, simplify } from "./pointsOnCurve";
|
||||
export { curveToBezier } from "./curveToBezier";
|
||||
export { Random, randomSeed } from "./random";
|
||||
@@ -0,0 +1,166 @@
|
||||
// Ported from points-on-curve@0.2.0 (src/index.ts): https://github.com/pshihn/bezier-points
|
||||
// MIT License, Copyright (c) 2020 Preet Shihn. See LICENSE.
|
||||
|
||||
export type Point = [number, number];
|
||||
|
||||
// distance between 2 points
|
||||
function distance(p1: Point, p2: Point): number {
|
||||
return Math.sqrt(distanceSq(p1, p2));
|
||||
}
|
||||
|
||||
// distance between 2 points squared
|
||||
function distanceSq(p1: Point, p2: Point): number {
|
||||
return Math.pow(p1[0] - p2[0], 2) + Math.pow(p1[1] - p2[1], 2);
|
||||
}
|
||||
|
||||
// Sistance squared from a point p to the line segment vw
|
||||
function distanceToSegmentSq(p: Point, v: Point, w: Point): number {
|
||||
const l2 = distanceSq(v, w);
|
||||
if (l2 === 0) {
|
||||
return distanceSq(p, v);
|
||||
}
|
||||
let t = ((p[0] - v[0]) * (w[0] - v[0]) + (p[1] - v[1]) * (w[1] - v[1])) / l2;
|
||||
t = Math.max(0, Math.min(1, t));
|
||||
return distanceSq(p, lerp(v, w, t));
|
||||
}
|
||||
|
||||
function lerp(a: Point, b: Point, t: number): Point {
|
||||
return [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t];
|
||||
}
|
||||
|
||||
// Adapted from https://seant23.wordpress.com/2010/11/12/offset-bezier-curves/
|
||||
function flatness(points: Point[], offset: number): number {
|
||||
const p1 = points[offset + 0];
|
||||
const p2 = points[offset + 1];
|
||||
const p3 = points[offset + 2];
|
||||
const p4 = points[offset + 3];
|
||||
|
||||
let ux = 3 * p2[0] - 2 * p1[0] - p4[0];
|
||||
ux *= ux;
|
||||
let uy = 3 * p2[1] - 2 * p1[1] - p4[1];
|
||||
uy *= uy;
|
||||
let vx = 3 * p3[0] - 2 * p4[0] - p1[0];
|
||||
vx *= vx;
|
||||
let vy = 3 * p3[1] - 2 * p4[1] - p1[1];
|
||||
vy *= vy;
|
||||
|
||||
if (ux < vx) {
|
||||
ux = vx;
|
||||
}
|
||||
|
||||
if (uy < vy) {
|
||||
uy = vy;
|
||||
}
|
||||
|
||||
return ux + uy;
|
||||
}
|
||||
|
||||
function getPointsOnBezierCurveWithSplitting(
|
||||
points: Point[],
|
||||
offset: number,
|
||||
tolerance: number,
|
||||
newPoints?: Point[],
|
||||
): Point[] {
|
||||
const outPoints = newPoints || [];
|
||||
if (flatness(points, offset) < tolerance) {
|
||||
const p0 = points[offset + 0];
|
||||
if (outPoints.length) {
|
||||
const d = distance(outPoints[outPoints.length - 1], p0);
|
||||
if (d > 1) {
|
||||
outPoints.push(p0);
|
||||
}
|
||||
} else {
|
||||
outPoints.push(p0);
|
||||
}
|
||||
outPoints.push(points[offset + 3]);
|
||||
} else {
|
||||
// subdivide
|
||||
const t = 0.5;
|
||||
const p1 = points[offset + 0];
|
||||
const p2 = points[offset + 1];
|
||||
const p3 = points[offset + 2];
|
||||
const p4 = points[offset + 3];
|
||||
|
||||
const q1 = lerp(p1, p2, t);
|
||||
const q2 = lerp(p2, p3, t);
|
||||
const q3 = lerp(p3, p4, t);
|
||||
|
||||
const r1 = lerp(q1, q2, t);
|
||||
const r2 = lerp(q2, q3, t);
|
||||
|
||||
const red = lerp(r1, r2, t);
|
||||
|
||||
getPointsOnBezierCurveWithSplitting(
|
||||
[p1, q1, r1, red],
|
||||
0,
|
||||
tolerance,
|
||||
outPoints,
|
||||
);
|
||||
getPointsOnBezierCurveWithSplitting(
|
||||
[red, r2, q3, p4],
|
||||
0,
|
||||
tolerance,
|
||||
outPoints,
|
||||
);
|
||||
}
|
||||
return outPoints;
|
||||
}
|
||||
|
||||
export function simplify(points: Point[], distance: number): Point[] {
|
||||
return simplifyPoints(points, 0, points.length, distance);
|
||||
}
|
||||
|
||||
// Ramer–Douglas–Peucker algorithm
|
||||
// https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm
|
||||
function simplifyPoints(
|
||||
points: Point[],
|
||||
start: number,
|
||||
end: number,
|
||||
epsilon: number,
|
||||
newPoints?: Point[],
|
||||
): Point[] {
|
||||
const outPoints = newPoints || [];
|
||||
|
||||
// find the most distance point from the endpoints
|
||||
const s = points[start];
|
||||
const e = points[end - 1];
|
||||
let maxDistSq = 0;
|
||||
let maxNdx = 1;
|
||||
for (let i = start + 1; i < end - 1; ++i) {
|
||||
const distSq = distanceToSegmentSq(points[i], s, e);
|
||||
if (distSq > maxDistSq) {
|
||||
maxDistSq = distSq;
|
||||
maxNdx = i;
|
||||
}
|
||||
}
|
||||
|
||||
// if that point is too far, split
|
||||
if (Math.sqrt(maxDistSq) > epsilon) {
|
||||
simplifyPoints(points, start, maxNdx + 1, epsilon, outPoints);
|
||||
simplifyPoints(points, maxNdx, end, epsilon, outPoints);
|
||||
} else {
|
||||
if (!outPoints.length) {
|
||||
outPoints.push(s);
|
||||
}
|
||||
outPoints.push(e);
|
||||
}
|
||||
|
||||
return outPoints;
|
||||
}
|
||||
|
||||
export function pointsOnBezierCurves(
|
||||
points: Point[],
|
||||
tolerance: number = 0.15,
|
||||
distance?: number,
|
||||
): Point[] {
|
||||
const newPoints: Point[] = [];
|
||||
const numSegments = (points.length - 1) / 3;
|
||||
for (let i = 0; i < numSegments; i++) {
|
||||
const offset = i * 3;
|
||||
getPointsOnBezierCurveWithSplitting(points, offset, tolerance, newPoints);
|
||||
}
|
||||
if (distance && distance > 0) {
|
||||
return simplifyPoints(newPoints, 0, newPoints.length, distance);
|
||||
}
|
||||
return newPoints;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// Ported from roughjs@4.6.4 (src/math.ts): https://github.com/pshihn/rough/blob/7944f1c/src/math.ts
|
||||
// MIT License, Copyright (c) 2019 Preet Shihn. See LICENSE.
|
||||
|
||||
export function randomSeed(): number {
|
||||
return Math.floor(Math.random() * 2 ** 31);
|
||||
}
|
||||
|
||||
export class Random {
|
||||
private seed: number;
|
||||
|
||||
constructor(seed: number) {
|
||||
this.seed = seed;
|
||||
}
|
||||
|
||||
next(): number {
|
||||
if (this.seed) {
|
||||
return (
|
||||
((2 ** 31 - 1) & (this.seed = Math.imul(48271, this.seed))) / 2 ** 31
|
||||
);
|
||||
}
|
||||
return Math.random();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Excalidraw
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
---
|
||||
|
||||
This package contains code ported from the following projects by Preet Shihn,
|
||||
all released under the MIT License:
|
||||
|
||||
- roughjs 4.6.4, Copyright (c) 2019 Preet Shihn
|
||||
https://github.com/pshihn/rough
|
||||
- hachure-fill 0.5.2, Copyright (c) 2023 Preet Shihn
|
||||
https://github.com/pshihn/hachure-fill
|
||||
- path-data-parser 0.1.0, Copyright (c) 2020 Preet Shihn
|
||||
https://github.com/pshihn/path-data-parser
|
||||
- points-on-path 0.2.1, Copyright (c) 2020 Preet Shihn
|
||||
https://github.com/pshihn/points-on-path
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2019 Preet Shihn
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,18 @@
|
||||
# @excalidraw/sloppy
|
||||
|
||||
Hand-drawn shape generation for Excalidraw: generates sketchy shapes as op sets (`Drawable`) and draws them to a canvas or SVG.
|
||||
|
||||
Ported from [roughjs](https://github.com/pshihn/rough) 4.6.4, together with its [hachure-fill](https://github.com/pshihn/hachure-fill), [path-data-parser](https://github.com/pshihn/path-data-parser) and [points-on-path](https://github.com/pshihn/points-on-path) dependencies ([points-on-curve](https://github.com/pshihn/bezier-points) lives in `@excalidraw/math`). See [LICENSE](./LICENSE).
|
||||
|
||||
The output is kept identical to roughjs 4.6.4 for the same seed and options: every existing drawing's look depends on the exact sequence of random draws. `tests/parity.test.ts` compares the two.
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { rough } from "@excalidraw/sloppy";
|
||||
|
||||
const generator = rough.generator();
|
||||
const drawable = generator.ellipse(50, 50, 100, 60, { seed: 1, roughness: 1 });
|
||||
|
||||
rough.canvas(canvas).draw(drawable);
|
||||
```
|
||||
@@ -0,0 +1,71 @@
|
||||
{
|
||||
"name": "@excalidraw/sloppy",
|
||||
"version": "0.18.0",
|
||||
"type": "module",
|
||||
"types": "./dist/types/sloppy/src/index.d.ts",
|
||||
"main": "./dist/prod/index.js",
|
||||
"module": "./dist/prod/index.js",
|
||||
"exports": {
|
||||
".": {
|
||||
"excalidraw-source": "./src/index.ts",
|
||||
"types": "./dist/types/sloppy/src/index.d.ts",
|
||||
"development": "./dist/dev/index.js",
|
||||
"production": "./dist/prod/index.js",
|
||||
"default": "./dist/prod/index.js"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist/*"
|
||||
],
|
||||
"description": "Hand-drawn shape generation for Excalidraw, ported from roughjs",
|
||||
"publishConfig": {
|
||||
"access": "public",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/types/sloppy/src/index.d.ts",
|
||||
"development": "./dist/dev/index.js",
|
||||
"production": "./dist/prod/index.js",
|
||||
"default": "./dist/prod/index.js"
|
||||
}
|
||||
}
|
||||
},
|
||||
"license": "MIT",
|
||||
"keywords": [
|
||||
"excalidraw",
|
||||
"excalidraw-sloppy",
|
||||
"sketchy",
|
||||
"hand-drawn"
|
||||
],
|
||||
"browserslist": {
|
||||
"production": [
|
||||
">0.2%",
|
||||
"not dead",
|
||||
"not ie <= 11",
|
||||
"not op_mini all",
|
||||
"not safari < 12",
|
||||
"not kaios <= 2.5",
|
||||
"not edge < 79",
|
||||
"not chrome < 70",
|
||||
"not and_uc < 13",
|
||||
"not samsung < 10"
|
||||
],
|
||||
"development": [
|
||||
"last 1 chrome version",
|
||||
"last 1 firefox version",
|
||||
"last 1 safari version"
|
||||
]
|
||||
},
|
||||
"bugs": "https://github.com/excalidraw/excalidraw/issues",
|
||||
"repository": "https://github.com/excalidraw/excalidraw",
|
||||
"dependencies": {
|
||||
"@excalidraw/math": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"roughjs": "4.6.4"
|
||||
},
|
||||
"scripts": {
|
||||
"gen:types": "rimraf types && tsc",
|
||||
"build:esm": "rimraf dist && node ../../scripts/buildBase.js && pnpm gen:types",
|
||||
"prepublishOnly": "node ../../scripts/ensure-pnpm-publish.js"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
// Ported from roughjs@4.6.4 (src/canvas.ts): https://github.com/pshihn/rough/blob/7944f1c/src/canvas.ts
|
||||
// MIT License, Copyright (c) 2019 Preet Shihn. See LICENSE.
|
||||
|
||||
import { RoughGenerator } from "./generator";
|
||||
|
||||
import type { Config, Options, ResolvedOptions, Drawable, OpSet } from "./core";
|
||||
import type { Point } from "./geometry";
|
||||
|
||||
export class RoughCanvas {
|
||||
private gen: RoughGenerator;
|
||||
private canvas: HTMLCanvasElement;
|
||||
private ctx: CanvasRenderingContext2D;
|
||||
|
||||
constructor(canvas: HTMLCanvasElement, config?: Config) {
|
||||
this.canvas = canvas;
|
||||
this.ctx = this.canvas.getContext("2d")!;
|
||||
this.gen = new RoughGenerator(config);
|
||||
}
|
||||
|
||||
draw(drawable: Drawable): void {
|
||||
const sets = drawable.sets || [];
|
||||
const o = drawable.options || this.getDefaultOptions();
|
||||
const ctx = this.ctx;
|
||||
const precision = drawable.options.fixedDecimalPlaceDigits;
|
||||
for (const drawing of sets) {
|
||||
switch (drawing.type) {
|
||||
case "path":
|
||||
ctx.save();
|
||||
ctx.strokeStyle = o.stroke === "none" ? "transparent" : o.stroke;
|
||||
ctx.lineWidth = o.strokeWidth;
|
||||
if (o.strokeLineDash) {
|
||||
ctx.setLineDash(o.strokeLineDash);
|
||||
}
|
||||
if (o.strokeLineDashOffset) {
|
||||
ctx.lineDashOffset = o.strokeLineDashOffset;
|
||||
}
|
||||
this._drawToContext(ctx, drawing, precision);
|
||||
ctx.restore();
|
||||
break;
|
||||
case "fillPath": {
|
||||
ctx.save();
|
||||
ctx.fillStyle = o.fill || "";
|
||||
const fillRule: CanvasFillRule =
|
||||
drawable.shape === "curve" ||
|
||||
drawable.shape === "polygon" ||
|
||||
drawable.shape === "path"
|
||||
? "evenodd"
|
||||
: "nonzero";
|
||||
this._drawToContext(ctx, drawing, precision, fillRule);
|
||||
ctx.restore();
|
||||
break;
|
||||
}
|
||||
case "fillSketch":
|
||||
this.fillSketch(ctx, drawing, o);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fillSketch(
|
||||
ctx: CanvasRenderingContext2D,
|
||||
drawing: OpSet,
|
||||
o: ResolvedOptions,
|
||||
) {
|
||||
let fweight = o.fillWeight;
|
||||
if (fweight < 0) {
|
||||
fweight = o.strokeWidth / 2;
|
||||
}
|
||||
ctx.save();
|
||||
if (o.fillLineDash) {
|
||||
ctx.setLineDash(o.fillLineDash);
|
||||
}
|
||||
if (o.fillLineDashOffset) {
|
||||
ctx.lineDashOffset = o.fillLineDashOffset;
|
||||
}
|
||||
ctx.strokeStyle = o.fill || "";
|
||||
ctx.lineWidth = fweight;
|
||||
this._drawToContext(ctx, drawing, o.fixedDecimalPlaceDigits);
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
private _drawToContext(
|
||||
ctx: CanvasRenderingContext2D,
|
||||
drawing: OpSet,
|
||||
fixedDecimals?: number,
|
||||
rule: CanvasFillRule = "nonzero",
|
||||
) {
|
||||
ctx.beginPath();
|
||||
for (const item of drawing.ops) {
|
||||
const data =
|
||||
typeof fixedDecimals === "number" && fixedDecimals >= 0
|
||||
? item.data.map((d) => +d.toFixed(fixedDecimals))
|
||||
: item.data;
|
||||
switch (item.op) {
|
||||
case "move":
|
||||
ctx.moveTo(data[0], data[1]);
|
||||
break;
|
||||
case "bcurveTo":
|
||||
ctx.bezierCurveTo(
|
||||
data[0],
|
||||
data[1],
|
||||
data[2],
|
||||
data[3],
|
||||
data[4],
|
||||
data[5],
|
||||
);
|
||||
break;
|
||||
case "lineTo":
|
||||
ctx.lineTo(data[0], data[1]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (drawing.type === "fillPath") {
|
||||
ctx.fill(rule);
|
||||
} else {
|
||||
ctx.stroke();
|
||||
}
|
||||
}
|
||||
|
||||
get generator(): RoughGenerator {
|
||||
return this.gen;
|
||||
}
|
||||
|
||||
getDefaultOptions(): ResolvedOptions {
|
||||
return this.gen.defaultOptions;
|
||||
}
|
||||
|
||||
line(
|
||||
x1: number,
|
||||
y1: number,
|
||||
x2: number,
|
||||
y2: number,
|
||||
options?: Options,
|
||||
): Drawable {
|
||||
const d = this.gen.line(x1, y1, x2, y2, options);
|
||||
this.draw(d);
|
||||
return d;
|
||||
}
|
||||
|
||||
rectangle(
|
||||
x: number,
|
||||
y: number,
|
||||
width: number,
|
||||
height: number,
|
||||
options?: Options,
|
||||
): Drawable {
|
||||
const d = this.gen.rectangle(x, y, width, height, options);
|
||||
this.draw(d);
|
||||
return d;
|
||||
}
|
||||
|
||||
ellipse(
|
||||
x: number,
|
||||
y: number,
|
||||
width: number,
|
||||
height: number,
|
||||
options?: Options,
|
||||
): Drawable {
|
||||
const d = this.gen.ellipse(x, y, width, height, options);
|
||||
this.draw(d);
|
||||
return d;
|
||||
}
|
||||
|
||||
circle(x: number, y: number, diameter: number, options?: Options): Drawable {
|
||||
const d = this.gen.circle(x, y, diameter, options);
|
||||
this.draw(d);
|
||||
return d;
|
||||
}
|
||||
|
||||
linearPath(points: Point[], options?: Options): Drawable {
|
||||
const d = this.gen.linearPath(points, options);
|
||||
this.draw(d);
|
||||
return d;
|
||||
}
|
||||
|
||||
polygon(points: Point[], options?: Options): Drawable {
|
||||
const d = this.gen.polygon(points, options);
|
||||
this.draw(d);
|
||||
return d;
|
||||
}
|
||||
|
||||
arc(
|
||||
x: number,
|
||||
y: number,
|
||||
width: number,
|
||||
height: number,
|
||||
start: number,
|
||||
stop: number,
|
||||
closed: boolean = false,
|
||||
options?: Options,
|
||||
): Drawable {
|
||||
const d = this.gen.arc(x, y, width, height, start, stop, closed, options);
|
||||
this.draw(d);
|
||||
return d;
|
||||
}
|
||||
|
||||
curve(points: Point[], options?: Options): Drawable {
|
||||
const d = this.gen.curve(points, options);
|
||||
this.draw(d);
|
||||
return d;
|
||||
}
|
||||
|
||||
path(d: string, options?: Options): Drawable {
|
||||
const drawing = this.gen.path(d, options);
|
||||
this.draw(drawing);
|
||||
return drawing;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
// Ported from roughjs@4.6.4 (src/core.ts): https://github.com/pshihn/rough/blob/7944f1c/src/core.ts
|
||||
// MIT License, Copyright (c) 2019 Preet Shihn. See LICENSE.
|
||||
|
||||
import type { Random } from "@excalidraw/math";
|
||||
|
||||
import type { Point } from "./geometry";
|
||||
|
||||
export const SVGNS = "http://www.w3.org/2000/svg";
|
||||
|
||||
export interface Config {
|
||||
options?: Options;
|
||||
}
|
||||
|
||||
export interface DrawingSurface {
|
||||
width: number | SVGAnimatedLength;
|
||||
height: number | SVGAnimatedLength;
|
||||
}
|
||||
|
||||
export interface Options {
|
||||
maxRandomnessOffset?: number;
|
||||
roughness?: number;
|
||||
bowing?: number;
|
||||
stroke?: string;
|
||||
strokeWidth?: number;
|
||||
curveFitting?: number;
|
||||
curveTightness?: number;
|
||||
curveStepCount?: number;
|
||||
fill?: string;
|
||||
fillStyle?: string;
|
||||
fillWeight?: number;
|
||||
hachureAngle?: number;
|
||||
hachureGap?: number;
|
||||
simplification?: number;
|
||||
dashOffset?: number;
|
||||
dashGap?: number;
|
||||
zigzagOffset?: number;
|
||||
seed?: number;
|
||||
strokeLineDash?: number[];
|
||||
strokeLineDashOffset?: number;
|
||||
fillLineDash?: number[];
|
||||
fillLineDashOffset?: number;
|
||||
disableMultiStroke?: boolean;
|
||||
disableMultiStrokeFill?: boolean;
|
||||
preserveVertices?: boolean;
|
||||
fixedDecimalPlaceDigits?: number;
|
||||
fillShapeRoughnessGain?: number;
|
||||
}
|
||||
|
||||
export interface ResolvedOptions extends Options {
|
||||
maxRandomnessOffset: number;
|
||||
roughness: number;
|
||||
bowing: number;
|
||||
stroke: string;
|
||||
strokeWidth: number;
|
||||
curveFitting: number;
|
||||
curveTightness: number;
|
||||
curveStepCount: number;
|
||||
fillStyle: string;
|
||||
fillWeight: number;
|
||||
hachureAngle: number;
|
||||
hachureGap: number;
|
||||
dashOffset: number;
|
||||
dashGap: number;
|
||||
zigzagOffset: number;
|
||||
seed: number;
|
||||
randomizer?: Random;
|
||||
disableMultiStroke: boolean;
|
||||
disableMultiStrokeFill: boolean;
|
||||
preserveVertices: boolean;
|
||||
fillShapeRoughnessGain: number;
|
||||
}
|
||||
|
||||
export declare type OpType = "move" | "bcurveTo" | "lineTo";
|
||||
export declare type OpSetType = "path" | "fillPath" | "fillSketch";
|
||||
|
||||
export interface Op {
|
||||
op: OpType;
|
||||
data: number[];
|
||||
}
|
||||
|
||||
export interface OpSet {
|
||||
type: OpSetType;
|
||||
ops: Op[];
|
||||
size?: Point;
|
||||
path?: string;
|
||||
}
|
||||
|
||||
export interface Drawable {
|
||||
shape: string;
|
||||
options: ResolvedOptions;
|
||||
sets: OpSet[];
|
||||
}
|
||||
|
||||
export interface PathInfo {
|
||||
d: string;
|
||||
stroke: string;
|
||||
strokeWidth: number;
|
||||
fill?: string;
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
// Ported from roughjs@4.6.4 (src/fillers/dashed-filler.ts): https://github.com/pshihn/rough/blob/7944f1c/src/fillers/dashed-filler.ts
|
||||
// MIT License, Copyright (c) 2019 Preet Shihn. See LICENSE.
|
||||
|
||||
import { lineLength } from "../geometry";
|
||||
|
||||
import { polygonHachureLines } from "./scanLineHachure";
|
||||
|
||||
import type { ResolvedOptions, OpSet, Op } from "../core";
|
||||
import type { Point, Line } from "../geometry";
|
||||
|
||||
import type { PatternFiller, RenderHelper } from "./fillerInterface";
|
||||
|
||||
export class DashedFiller implements PatternFiller {
|
||||
private helper: RenderHelper;
|
||||
|
||||
constructor(helper: RenderHelper) {
|
||||
this.helper = helper;
|
||||
}
|
||||
|
||||
fillPolygons(polygonList: Point[][], o: ResolvedOptions): OpSet {
|
||||
const lines = polygonHachureLines(polygonList, o);
|
||||
return { type: "fillSketch", ops: this.dashedLine(lines, o) };
|
||||
}
|
||||
|
||||
private dashedLine(lines: Line[], o: ResolvedOptions): Op[] {
|
||||
const offset =
|
||||
o.dashOffset < 0
|
||||
? o.hachureGap < 0
|
||||
? o.strokeWidth * 4
|
||||
: o.hachureGap
|
||||
: o.dashOffset;
|
||||
const gap =
|
||||
o.dashGap < 0
|
||||
? o.hachureGap < 0
|
||||
? o.strokeWidth * 4
|
||||
: o.hachureGap
|
||||
: o.dashGap;
|
||||
const ops: Op[] = [];
|
||||
lines.forEach((line) => {
|
||||
const length = lineLength(line);
|
||||
const count = Math.floor(length / (offset + gap));
|
||||
const startOffset = (length + gap - count * (offset + gap)) / 2;
|
||||
let p1 = line[0];
|
||||
let p2 = line[1];
|
||||
if (p1[0] > p2[0]) {
|
||||
p1 = line[1];
|
||||
p2 = line[0];
|
||||
}
|
||||
const alpha = Math.atan((p2[1] - p1[1]) / (p2[0] - p1[0]));
|
||||
for (let i = 0; i < count; i++) {
|
||||
const lstart = i * (offset + gap);
|
||||
const lend = lstart + offset;
|
||||
const start: Point = [
|
||||
p1[0] + lstart * Math.cos(alpha) + startOffset * Math.cos(alpha),
|
||||
p1[1] + lstart * Math.sin(alpha) + startOffset * Math.sin(alpha),
|
||||
];
|
||||
const end: Point = [
|
||||
p1[0] + lend * Math.cos(alpha) + startOffset * Math.cos(alpha),
|
||||
p1[1] + lend * Math.sin(alpha) + startOffset * Math.sin(alpha),
|
||||
];
|
||||
ops.push(
|
||||
...this.helper.doubleLineOps(start[0], start[1], end[0], end[1], o),
|
||||
);
|
||||
}
|
||||
});
|
||||
return ops;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
// Ported from roughjs@4.6.4 (src/fillers/dot-filler.ts): https://github.com/pshihn/rough/blob/7944f1c/src/fillers/dot-filler.ts
|
||||
// MIT License, Copyright (c) 2019 Preet Shihn. See LICENSE.
|
||||
|
||||
import { lineLength } from "../geometry";
|
||||
|
||||
import { polygonHachureLines } from "./scanLineHachure";
|
||||
|
||||
import type { ResolvedOptions, OpSet, Op } from "../core";
|
||||
import type { Point, Line } from "../geometry";
|
||||
|
||||
import type { PatternFiller, RenderHelper } from "./fillerInterface";
|
||||
|
||||
export class DotFiller implements PatternFiller {
|
||||
private helper: RenderHelper;
|
||||
|
||||
constructor(helper: RenderHelper) {
|
||||
this.helper = helper;
|
||||
}
|
||||
|
||||
fillPolygons(polygonList: Point[][], o: ResolvedOptions): OpSet {
|
||||
o = Object.assign({}, o, { hachureAngle: 0 });
|
||||
const lines = polygonHachureLines(polygonList, o);
|
||||
return this.dotsOnLines(lines, o);
|
||||
}
|
||||
|
||||
private dotsOnLines(lines: Line[], o: ResolvedOptions): OpSet {
|
||||
const ops: Op[] = [];
|
||||
let gap = o.hachureGap;
|
||||
if (gap < 0) {
|
||||
gap = o.strokeWidth * 4;
|
||||
}
|
||||
gap = Math.max(gap, 0.1);
|
||||
let fweight = o.fillWeight;
|
||||
if (fweight < 0) {
|
||||
fweight = o.strokeWidth / 2;
|
||||
}
|
||||
const ro = gap / 4;
|
||||
for (const line of lines) {
|
||||
const length = lineLength(line);
|
||||
const dl = length / gap;
|
||||
const count = Math.ceil(dl) - 1;
|
||||
const offset = length - count * gap;
|
||||
const x = (line[0][0] + line[1][0]) / 2 - gap / 4;
|
||||
const minY = Math.min(line[0][1], line[1][1]);
|
||||
|
||||
for (let i = 0; i < count; i++) {
|
||||
const y = minY + offset + i * gap;
|
||||
const cx = x - ro + Math.random() * 2 * ro;
|
||||
const cy = y - ro + Math.random() * 2 * ro;
|
||||
const el = this.helper.ellipse(cx, cy, fweight, fweight, o);
|
||||
ops.push(...el.ops);
|
||||
}
|
||||
}
|
||||
return { type: "fillSketch", ops };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
// Ported from roughjs@4.6.4 (src/fillers/filler.ts): https://github.com/pshihn/rough/blob/7944f1c/src/fillers/filler.ts
|
||||
// MIT License, Copyright (c) 2019 Preet Shihn. See LICENSE.
|
||||
|
||||
import { HachureFiller } from "./hachureFiller";
|
||||
import { ZigZagFiller } from "./zigzagFiller";
|
||||
import { HatchFiller } from "./hatchFiller";
|
||||
import { DotFiller } from "./dotFiller";
|
||||
import { DashedFiller } from "./dashedFiller";
|
||||
import { ZigZagLineFiller } from "./zigzagLineFiller";
|
||||
|
||||
import type { PatternFiller, RenderHelper } from "./fillerInterface";
|
||||
|
||||
import type { ResolvedOptions } from "../core";
|
||||
|
||||
const fillers: { [name: string]: PatternFiller } = {};
|
||||
|
||||
export function getFiller(
|
||||
o: ResolvedOptions,
|
||||
helper: RenderHelper,
|
||||
): PatternFiller {
|
||||
let fillerName = o.fillStyle || "hachure";
|
||||
if (!fillers[fillerName]) {
|
||||
switch (fillerName) {
|
||||
case "zigzag":
|
||||
if (!fillers[fillerName]) {
|
||||
fillers[fillerName] = new ZigZagFiller(helper);
|
||||
}
|
||||
break;
|
||||
case "cross-hatch":
|
||||
if (!fillers[fillerName]) {
|
||||
fillers[fillerName] = new HatchFiller(helper);
|
||||
}
|
||||
break;
|
||||
case "dots":
|
||||
if (!fillers[fillerName]) {
|
||||
fillers[fillerName] = new DotFiller(helper);
|
||||
}
|
||||
break;
|
||||
case "dashed":
|
||||
if (!fillers[fillerName]) {
|
||||
fillers[fillerName] = new DashedFiller(helper);
|
||||
}
|
||||
break;
|
||||
case "zigzag-line":
|
||||
if (!fillers[fillerName]) {
|
||||
fillers[fillerName] = new ZigZagLineFiller(helper);
|
||||
}
|
||||
break;
|
||||
case "hachure":
|
||||
default:
|
||||
fillerName = "hachure";
|
||||
if (!fillers[fillerName]) {
|
||||
fillers[fillerName] = new HachureFiller(helper);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
return fillers[fillerName];
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
// Ported from roughjs@4.6.4 (src/fillers/filler-interface.ts): https://github.com/pshihn/rough/blob/7944f1c/src/fillers/filler-interface.ts
|
||||
// MIT License, Copyright (c) 2019 Preet Shihn. See LICENSE.
|
||||
|
||||
import type { ResolvedOptions, OpSet, Op } from "../core";
|
||||
import type { Point } from "../geometry";
|
||||
|
||||
export interface PatternFiller {
|
||||
fillPolygons(polygonList: Point[][], o: ResolvedOptions): OpSet;
|
||||
}
|
||||
|
||||
export interface RenderHelper {
|
||||
randOffset(x: number, o: ResolvedOptions): number;
|
||||
randOffsetWithRange(min: number, max: number, o: ResolvedOptions): number;
|
||||
ellipse(
|
||||
x: number,
|
||||
y: number,
|
||||
width: number,
|
||||
height: number,
|
||||
o: ResolvedOptions,
|
||||
): OpSet;
|
||||
doubleLineOps(
|
||||
x1: number,
|
||||
y1: number,
|
||||
x2: number,
|
||||
y2: number,
|
||||
o: ResolvedOptions,
|
||||
): Op[];
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// Ported from roughjs@4.6.4 (src/fillers/hachure-filler.ts): https://github.com/pshihn/rough/blob/7944f1c/src/fillers/hachure-filler.ts
|
||||
// MIT License, Copyright (c) 2019 Preet Shihn. See LICENSE.
|
||||
|
||||
import { polygonHachureLines } from "./scanLineHachure";
|
||||
|
||||
import type { ResolvedOptions, OpSet, Op } from "../core";
|
||||
import type { Point, Line } from "../geometry";
|
||||
|
||||
import type { PatternFiller, RenderHelper } from "./fillerInterface";
|
||||
|
||||
export class HachureFiller implements PatternFiller {
|
||||
private helper: RenderHelper;
|
||||
|
||||
constructor(helper: RenderHelper) {
|
||||
this.helper = helper;
|
||||
}
|
||||
|
||||
fillPolygons(polygonList: Point[][], o: ResolvedOptions): OpSet {
|
||||
return this._fillPolygons(polygonList, o);
|
||||
}
|
||||
|
||||
protected _fillPolygons(polygonList: Point[][], o: ResolvedOptions): OpSet {
|
||||
const lines = polygonHachureLines(polygonList, o);
|
||||
const ops = this.renderLines(lines, o);
|
||||
return { type: "fillSketch", ops };
|
||||
}
|
||||
|
||||
protected renderLines(lines: Line[], o: ResolvedOptions): Op[] {
|
||||
const ops: Op[] = [];
|
||||
for (const line of lines) {
|
||||
ops.push(
|
||||
...this.helper.doubleLineOps(
|
||||
line[0][0],
|
||||
line[0][1],
|
||||
line[1][0],
|
||||
line[1][1],
|
||||
o,
|
||||
),
|
||||
);
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// Ported from roughjs@4.6.4 (src/fillers/hatch-filler.ts): https://github.com/pshihn/rough/blob/7944f1c/src/fillers/hatch-filler.ts
|
||||
// MIT License, Copyright (c) 2019 Preet Shihn. See LICENSE.
|
||||
|
||||
import { HachureFiller } from "./hachureFiller";
|
||||
|
||||
import type { ResolvedOptions, OpSet } from "../core";
|
||||
import type { Point } from "../geometry";
|
||||
|
||||
export class HatchFiller extends HachureFiller {
|
||||
fillPolygons(polygonList: Point[][], o: ResolvedOptions): OpSet {
|
||||
const set = this._fillPolygons(polygonList, o);
|
||||
const o2 = Object.assign({}, o, { hachureAngle: o.hachureAngle + 90 });
|
||||
const set2 = this._fillPolygons(polygonList, o2);
|
||||
set.ops = set.ops.concat(set2.ops);
|
||||
return set;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// Ported from roughjs@4.6.4 (src/fillers/scan-line-hachure.ts): https://github.com/pshihn/rough/blob/7944f1c/src/fillers/scan-line-hachure.ts
|
||||
// MIT License, Copyright (c) 2019 Preet Shihn. See LICENSE.
|
||||
|
||||
import { hachureLines } from "../hachure";
|
||||
|
||||
import type { Point, Line } from "../geometry";
|
||||
import type { ResolvedOptions } from "../core";
|
||||
|
||||
export function polygonHachureLines(
|
||||
polygonList: Point[][],
|
||||
o: ResolvedOptions,
|
||||
): Line[] {
|
||||
const angle = o.hachureAngle + 90;
|
||||
let gap = o.hachureGap;
|
||||
if (gap < 0) {
|
||||
gap = o.strokeWidth * 4;
|
||||
}
|
||||
gap = Math.max(gap, 0.1);
|
||||
let skipOffset = 1;
|
||||
if (o.roughness >= 1) {
|
||||
if ((o.randomizer?.next() || Math.random()) > 0.7) {
|
||||
skipOffset = gap;
|
||||
}
|
||||
}
|
||||
return hachureLines(polygonList, gap, angle, skipOffset || 1);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
// Ported from roughjs@4.6.4 (src/fillers/zigzag-filler.ts): https://github.com/pshihn/rough/blob/7944f1c/src/fillers/zigzag-filler.ts
|
||||
// MIT License, Copyright (c) 2019 Preet Shihn. See LICENSE.
|
||||
|
||||
import { lineLength } from "../geometry";
|
||||
|
||||
import { HachureFiller } from "./hachureFiller";
|
||||
import { polygonHachureLines } from "./scanLineHachure";
|
||||
|
||||
import type { Point, Line } from "../geometry";
|
||||
|
||||
import type { ResolvedOptions, OpSet } from "../core";
|
||||
|
||||
export class ZigZagFiller extends HachureFiller {
|
||||
fillPolygons(polygonList: Point[][], o: ResolvedOptions): OpSet {
|
||||
let gap = o.hachureGap;
|
||||
if (gap < 0) {
|
||||
gap = o.strokeWidth * 4;
|
||||
}
|
||||
gap = Math.max(gap, 0.1);
|
||||
const o2 = Object.assign({}, o, { hachureGap: gap });
|
||||
const lines = polygonHachureLines(polygonList, o2);
|
||||
const zigZagAngle = (Math.PI / 180) * o.hachureAngle;
|
||||
const zigzagLines: Line[] = [];
|
||||
const dgx = gap * 0.5 * Math.cos(zigZagAngle);
|
||||
const dgy = gap * 0.5 * Math.sin(zigZagAngle);
|
||||
for (const [p1, p2] of lines) {
|
||||
if (lineLength([p1, p2])) {
|
||||
zigzagLines.push(
|
||||
[[p1[0] - dgx, p1[1] + dgy], [...p2]],
|
||||
[[p1[0] + dgx, p1[1] - dgy], [...p2]],
|
||||
);
|
||||
}
|
||||
}
|
||||
const ops = this.renderLines(zigzagLines, o);
|
||||
return { type: "fillSketch", ops };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
// Ported from roughjs@4.6.4 (src/fillers/zigzag-line-filler.ts): https://github.com/pshihn/rough/blob/7944f1c/src/fillers/zigzag-line-filler.ts
|
||||
// MIT License, Copyright (c) 2019 Preet Shihn. See LICENSE.
|
||||
|
||||
import { lineLength } from "../geometry";
|
||||
|
||||
import { polygonHachureLines } from "./scanLineHachure";
|
||||
|
||||
import type { ResolvedOptions, OpSet, Op } from "../core";
|
||||
import type { Point, Line } from "../geometry";
|
||||
|
||||
import type { PatternFiller, RenderHelper } from "./fillerInterface";
|
||||
|
||||
export class ZigZagLineFiller implements PatternFiller {
|
||||
private helper: RenderHelper;
|
||||
|
||||
constructor(helper: RenderHelper) {
|
||||
this.helper = helper;
|
||||
}
|
||||
|
||||
fillPolygons(polygonList: Point[][], o: ResolvedOptions): OpSet {
|
||||
const gap = o.hachureGap < 0 ? o.strokeWidth * 4 : o.hachureGap;
|
||||
const zo = o.zigzagOffset < 0 ? gap : o.zigzagOffset;
|
||||
o = Object.assign({}, o, { hachureGap: gap + zo });
|
||||
const lines = polygonHachureLines(polygonList, o);
|
||||
return { type: "fillSketch", ops: this.zigzagLines(lines, zo, o) };
|
||||
}
|
||||
|
||||
private zigzagLines(lines: Line[], zo: number, o: ResolvedOptions): Op[] {
|
||||
const ops: Op[] = [];
|
||||
lines.forEach((line) => {
|
||||
const length = lineLength(line);
|
||||
const count = Math.round(length / (2 * zo));
|
||||
let p1 = line[0];
|
||||
let p2 = line[1];
|
||||
if (p1[0] > p2[0]) {
|
||||
p1 = line[1];
|
||||
p2 = line[0];
|
||||
}
|
||||
const alpha = Math.atan((p2[1] - p1[1]) / (p2[0] - p1[0]));
|
||||
for (let i = 0; i < count; i++) {
|
||||
const lstart = i * 2 * zo;
|
||||
const lend = (i + 1) * 2 * zo;
|
||||
const dz = Math.sqrt(2 * Math.pow(zo, 2));
|
||||
const start: Point = [
|
||||
p1[0] + lstart * Math.cos(alpha),
|
||||
p1[1] + lstart * Math.sin(alpha),
|
||||
];
|
||||
const end: Point = [
|
||||
p1[0] + lend * Math.cos(alpha),
|
||||
p1[1] + lend * Math.sin(alpha),
|
||||
];
|
||||
const middle: Point = [
|
||||
start[0] + dz * Math.cos(alpha + Math.PI / 4),
|
||||
start[1] + dz * Math.sin(alpha + Math.PI / 4),
|
||||
];
|
||||
ops.push(
|
||||
...this.helper.doubleLineOps(
|
||||
start[0],
|
||||
start[1],
|
||||
middle[0],
|
||||
middle[1],
|
||||
o,
|
||||
),
|
||||
...this.helper.doubleLineOps(middle[0], middle[1], end[0], end[1], o),
|
||||
);
|
||||
}
|
||||
});
|
||||
return ops;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,388 @@
|
||||
// Ported from roughjs@4.6.4 (src/generator.ts): https://github.com/pshihn/rough/blob/7944f1c/src/generator.ts
|
||||
// MIT License, Copyright (c) 2019 Preet Shihn. See LICENSE.
|
||||
|
||||
import { randomSeed } from "@excalidraw/math";
|
||||
|
||||
import { curveToBezier } from "@excalidraw/math";
|
||||
|
||||
import { pointsOnBezierCurves } from "@excalidraw/math";
|
||||
|
||||
import {
|
||||
line,
|
||||
solidFillPolygon,
|
||||
patternFillPolygons,
|
||||
rectangle,
|
||||
ellipseWithParams,
|
||||
generateEllipseParams,
|
||||
linearPath,
|
||||
arc,
|
||||
patternFillArc,
|
||||
curve,
|
||||
svgPath,
|
||||
} from "./renderer";
|
||||
|
||||
import { pointsOnPath } from "./pointsOnPath";
|
||||
|
||||
import type {
|
||||
Config,
|
||||
Options,
|
||||
Drawable,
|
||||
OpSet,
|
||||
Op,
|
||||
ResolvedOptions,
|
||||
PathInfo,
|
||||
} from "./core";
|
||||
import type { Point } from "./geometry";
|
||||
|
||||
const NOS = "none";
|
||||
|
||||
export class RoughGenerator {
|
||||
private config: Config;
|
||||
|
||||
defaultOptions: ResolvedOptions = {
|
||||
maxRandomnessOffset: 2,
|
||||
roughness: 1,
|
||||
bowing: 1,
|
||||
stroke: "#000",
|
||||
strokeWidth: 1,
|
||||
curveTightness: 0,
|
||||
curveFitting: 0.95,
|
||||
curveStepCount: 9,
|
||||
fillStyle: "hachure",
|
||||
fillWeight: -1,
|
||||
hachureAngle: -41,
|
||||
hachureGap: -1,
|
||||
dashOffset: -1,
|
||||
dashGap: -1,
|
||||
zigzagOffset: -1,
|
||||
seed: 0,
|
||||
disableMultiStroke: false,
|
||||
disableMultiStrokeFill: false,
|
||||
preserveVertices: false,
|
||||
fillShapeRoughnessGain: 0.8,
|
||||
};
|
||||
|
||||
constructor(config?: Config) {
|
||||
this.config = config || {};
|
||||
if (this.config.options) {
|
||||
this.defaultOptions = this._o(this.config.options);
|
||||
}
|
||||
}
|
||||
|
||||
static newSeed(): number {
|
||||
return randomSeed();
|
||||
}
|
||||
|
||||
private _o(options?: Options): ResolvedOptions {
|
||||
return options
|
||||
? Object.assign({}, this.defaultOptions, options)
|
||||
: this.defaultOptions;
|
||||
}
|
||||
|
||||
private _d(shape: string, sets: OpSet[], options: ResolvedOptions): Drawable {
|
||||
return { shape, sets: sets || [], options: options || this.defaultOptions };
|
||||
}
|
||||
|
||||
line(
|
||||
x1: number,
|
||||
y1: number,
|
||||
x2: number,
|
||||
y2: number,
|
||||
options?: Options,
|
||||
): Drawable {
|
||||
const o = this._o(options);
|
||||
return this._d("line", [line(x1, y1, x2, y2, o)], o);
|
||||
}
|
||||
|
||||
rectangle(
|
||||
x: number,
|
||||
y: number,
|
||||
width: number,
|
||||
height: number,
|
||||
options?: Options,
|
||||
): Drawable {
|
||||
const o = this._o(options);
|
||||
const paths = [];
|
||||
const outline = rectangle(x, y, width, height, o);
|
||||
if (o.fill) {
|
||||
const points: Point[] = [
|
||||
[x, y],
|
||||
[x + width, y],
|
||||
[x + width, y + height],
|
||||
[x, y + height],
|
||||
];
|
||||
if (o.fillStyle === "solid") {
|
||||
paths.push(solidFillPolygon([points], o));
|
||||
} else {
|
||||
paths.push(patternFillPolygons([points], o));
|
||||
}
|
||||
}
|
||||
if (o.stroke !== NOS) {
|
||||
paths.push(outline);
|
||||
}
|
||||
return this._d("rectangle", paths, o);
|
||||
}
|
||||
|
||||
ellipse(
|
||||
x: number,
|
||||
y: number,
|
||||
width: number,
|
||||
height: number,
|
||||
options?: Options,
|
||||
): Drawable {
|
||||
const o = this._o(options);
|
||||
const paths: OpSet[] = [];
|
||||
const ellipseParams = generateEllipseParams(width, height, o);
|
||||
const ellipseResponse = ellipseWithParams(x, y, o, ellipseParams);
|
||||
if (o.fill) {
|
||||
if (o.fillStyle === "solid") {
|
||||
const shape = ellipseWithParams(x, y, o, ellipseParams).opset;
|
||||
shape.type = "fillPath";
|
||||
paths.push(shape);
|
||||
} else {
|
||||
paths.push(patternFillPolygons([ellipseResponse.estimatedPoints], o));
|
||||
}
|
||||
}
|
||||
if (o.stroke !== NOS) {
|
||||
paths.push(ellipseResponse.opset);
|
||||
}
|
||||
return this._d("ellipse", paths, o);
|
||||
}
|
||||
|
||||
circle(x: number, y: number, diameter: number, options?: Options): Drawable {
|
||||
const ret = this.ellipse(x, y, diameter, diameter, options);
|
||||
ret.shape = "circle";
|
||||
return ret;
|
||||
}
|
||||
|
||||
linearPath(points: Point[], options?: Options): Drawable {
|
||||
const o = this._o(options);
|
||||
return this._d("linearPath", [linearPath(points, false, o)], o);
|
||||
}
|
||||
|
||||
arc(
|
||||
x: number,
|
||||
y: number,
|
||||
width: number,
|
||||
height: number,
|
||||
start: number,
|
||||
stop: number,
|
||||
closed: boolean = false,
|
||||
options?: Options,
|
||||
): Drawable {
|
||||
const o = this._o(options);
|
||||
const paths = [];
|
||||
const outline = arc(x, y, width, height, start, stop, closed, true, o);
|
||||
if (closed && o.fill) {
|
||||
if (o.fillStyle === "solid") {
|
||||
const fillOptions: ResolvedOptions = { ...o };
|
||||
fillOptions.disableMultiStroke = true;
|
||||
const shape = arc(
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
height,
|
||||
start,
|
||||
stop,
|
||||
true,
|
||||
false,
|
||||
fillOptions,
|
||||
);
|
||||
shape.type = "fillPath";
|
||||
paths.push(shape);
|
||||
} else {
|
||||
paths.push(patternFillArc(x, y, width, height, start, stop, o));
|
||||
}
|
||||
}
|
||||
if (o.stroke !== NOS) {
|
||||
paths.push(outline);
|
||||
}
|
||||
return this._d("arc", paths, o);
|
||||
}
|
||||
|
||||
curve(points: Point[], options?: Options): Drawable {
|
||||
const o = this._o(options);
|
||||
const paths: OpSet[] = [];
|
||||
const outline = curve(points, o);
|
||||
if (o.fill && o.fill !== NOS && points.length >= 3) {
|
||||
if (o.fillStyle === "solid") {
|
||||
const fillShape = curve(points, {
|
||||
...o,
|
||||
disableMultiStroke: true,
|
||||
roughness: o.roughness ? o.roughness + o.fillShapeRoughnessGain : 0,
|
||||
});
|
||||
paths.push({
|
||||
type: "fillPath",
|
||||
ops: this._mergedShape(fillShape.ops),
|
||||
});
|
||||
} else {
|
||||
const bcurve = curveToBezier(points);
|
||||
const polyPoints = pointsOnBezierCurves(
|
||||
bcurve,
|
||||
10,
|
||||
(1 + o.roughness) / 2,
|
||||
);
|
||||
paths.push(patternFillPolygons([polyPoints], o));
|
||||
}
|
||||
}
|
||||
if (o.stroke !== NOS) {
|
||||
paths.push(outline);
|
||||
}
|
||||
return this._d("curve", paths, o);
|
||||
}
|
||||
|
||||
polygon(points: Point[], options?: Options): Drawable {
|
||||
const o = this._o(options);
|
||||
const paths: OpSet[] = [];
|
||||
const outline = linearPath(points, true, o);
|
||||
if (o.fill) {
|
||||
if (o.fillStyle === "solid") {
|
||||
paths.push(solidFillPolygon([points], o));
|
||||
} else {
|
||||
// the fillers rotate the points in place and back, leaving float
|
||||
// drift in them: hand them a copy, not the caller's (e.g. an
|
||||
// Excalidraw element's) points
|
||||
paths.push(
|
||||
patternFillPolygons([points.map(([x, y]): Point => [x, y])], o),
|
||||
);
|
||||
}
|
||||
}
|
||||
if (o.stroke !== NOS) {
|
||||
paths.push(outline);
|
||||
}
|
||||
return this._d("polygon", paths, o);
|
||||
}
|
||||
|
||||
path(d: string, options?: Options): Drawable {
|
||||
const o = this._o(options);
|
||||
const paths: OpSet[] = [];
|
||||
if (!d) {
|
||||
return this._d("path", paths, o);
|
||||
}
|
||||
d = (d || "")
|
||||
.replace(/\n/g, " ")
|
||||
.replace(/(-\s)/g, "-")
|
||||
.replace("/(ss)/g", " ");
|
||||
|
||||
const hasFill = o.fill && o.fill !== "transparent" && o.fill !== NOS;
|
||||
const hasStroke = o.stroke !== NOS;
|
||||
const simplified = !!(o.simplification && o.simplification < 1);
|
||||
const distance = simplified
|
||||
? 4 - 4 * (o.simplification || 1)
|
||||
: (1 + o.roughness) / 2;
|
||||
const sets = pointsOnPath(d, 1, distance);
|
||||
const shape = svgPath(d, o);
|
||||
|
||||
if (hasFill) {
|
||||
if (o.fillStyle === "solid") {
|
||||
if (sets.length === 1) {
|
||||
const fillShape = svgPath(d, {
|
||||
...o,
|
||||
disableMultiStroke: true,
|
||||
roughness: o.roughness ? o.roughness + o.fillShapeRoughnessGain : 0,
|
||||
});
|
||||
paths.push({
|
||||
type: "fillPath",
|
||||
ops: this._mergedShape(fillShape.ops),
|
||||
});
|
||||
} else {
|
||||
paths.push(solidFillPolygon(sets, o));
|
||||
}
|
||||
} else {
|
||||
paths.push(patternFillPolygons(sets, o));
|
||||
}
|
||||
}
|
||||
if (hasStroke) {
|
||||
if (simplified) {
|
||||
sets.forEach((set) => {
|
||||
paths.push(linearPath(set, false, o));
|
||||
});
|
||||
} else {
|
||||
paths.push(shape);
|
||||
}
|
||||
}
|
||||
|
||||
return this._d("path", paths, o);
|
||||
}
|
||||
|
||||
opsToPath(drawing: OpSet, fixedDecimals?: number): string {
|
||||
let path = "";
|
||||
for (const item of drawing.ops) {
|
||||
const data =
|
||||
typeof fixedDecimals === "number" && fixedDecimals >= 0
|
||||
? item.data.map((d) => +d.toFixed(fixedDecimals))
|
||||
: item.data;
|
||||
switch (item.op) {
|
||||
case "move":
|
||||
path += `M${data[0]} ${data[1]} `;
|
||||
break;
|
||||
case "bcurveTo":
|
||||
path += `C${data[0]} ${data[1]}, ${data[2]} ${data[3]}, ${data[4]} ${data[5]} `;
|
||||
break;
|
||||
case "lineTo":
|
||||
path += `L${data[0]} ${data[1]} `;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return path.trim();
|
||||
}
|
||||
|
||||
toPaths(drawable: Drawable): PathInfo[] {
|
||||
const sets = drawable.sets || [];
|
||||
const o = drawable.options || this.defaultOptions;
|
||||
const paths: PathInfo[] = [];
|
||||
for (const drawing of sets) {
|
||||
let path: PathInfo | null = null;
|
||||
switch (drawing.type) {
|
||||
case "path":
|
||||
path = {
|
||||
d: this.opsToPath(drawing),
|
||||
stroke: o.stroke,
|
||||
strokeWidth: o.strokeWidth,
|
||||
fill: NOS,
|
||||
};
|
||||
break;
|
||||
case "fillPath":
|
||||
path = {
|
||||
d: this.opsToPath(drawing),
|
||||
stroke: NOS,
|
||||
strokeWidth: 0,
|
||||
fill: o.fill || NOS,
|
||||
};
|
||||
break;
|
||||
case "fillSketch":
|
||||
path = this.fillSketch(drawing, o);
|
||||
break;
|
||||
}
|
||||
if (path) {
|
||||
paths.push(path);
|
||||
}
|
||||
}
|
||||
return paths;
|
||||
}
|
||||
|
||||
private fillSketch(drawing: OpSet, o: ResolvedOptions): PathInfo {
|
||||
let fweight = o.fillWeight;
|
||||
if (fweight < 0) {
|
||||
fweight = o.strokeWidth / 2;
|
||||
}
|
||||
return {
|
||||
d: this.opsToPath(drawing),
|
||||
stroke: o.fill || NOS,
|
||||
strokeWidth: fweight,
|
||||
fill: NOS,
|
||||
};
|
||||
}
|
||||
|
||||
private _mergedShape(input: Op[]): Op[] {
|
||||
return input.filter((d, i) => {
|
||||
if (i === 0) {
|
||||
return true;
|
||||
}
|
||||
if (d.op === "move") {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
// Ported from roughjs@4.6.4 (src/geometry.ts): https://github.com/pshihn/rough/blob/7944f1c/src/geometry.ts
|
||||
// MIT License, Copyright (c) 2019 Preet Shihn. See LICENSE.
|
||||
|
||||
export type Point = [number, number];
|
||||
export type Line = [Point, Point];
|
||||
|
||||
export interface Rectangle {
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
export function lineLength(line: Line): number {
|
||||
const p1 = line[0];
|
||||
const p2 = line[1];
|
||||
return Math.sqrt(Math.pow(p1[0] - p2[0], 2) + Math.pow(p1[1] - p2[1], 2));
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
// Ported from hachure-fill@0.5.2 (src/hachure.ts): https://github.com/pshihn/hachure-fill/blob/80e47ba/src/hachure.ts
|
||||
// MIT License, Copyright (c) 2023 Preet Shihn. See LICENSE.
|
||||
|
||||
// the loop callbacks run synchronously, so they never see a stale variable
|
||||
/* eslint-disable no-loop-func */
|
||||
|
||||
export type Point = [number, number];
|
||||
export type Line = [Point, Point];
|
||||
export type Polygon = Point[];
|
||||
|
||||
interface EdgeEntry {
|
||||
ymin: number;
|
||||
ymax: number;
|
||||
x: number;
|
||||
islope: number;
|
||||
}
|
||||
|
||||
interface ActiveEdgeEntry {
|
||||
s: number;
|
||||
edge: EdgeEntry;
|
||||
}
|
||||
|
||||
function rotatePoints(points: Point[], center: Point, degrees: number): void {
|
||||
if (points && points.length) {
|
||||
const [cx, cy] = center;
|
||||
const angle = (Math.PI / 180) * degrees;
|
||||
const cos = Math.cos(angle);
|
||||
const sin = Math.sin(angle);
|
||||
for (const p of points) {
|
||||
const [x, y] = p;
|
||||
p[0] = (x - cx) * cos - (y - cy) * sin + cx;
|
||||
p[1] = (x - cx) * sin + (y - cy) * cos + cy;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function rotateLines(lines: Line[], center: Point, degrees: number): void {
|
||||
const points: Point[] = [];
|
||||
lines.forEach((line) => points.push(...line));
|
||||
rotatePoints(points, center, degrees);
|
||||
}
|
||||
|
||||
function areSamePoints(p1: Point, p2: Point): boolean {
|
||||
return p1[0] === p2[0] && p1[1] === p2[1];
|
||||
}
|
||||
|
||||
export function hachureLines(
|
||||
polygons: Polygon | Polygon[],
|
||||
hachureGap: number,
|
||||
hachureAngle: number,
|
||||
hachureStepOffset = 1,
|
||||
): Line[] {
|
||||
const angle = hachureAngle;
|
||||
const gap = Math.max(hachureGap, 0.1);
|
||||
const polygonList =
|
||||
polygons[0] && polygons[0][0] && typeof polygons[0][0] === "number"
|
||||
? [polygons as Polygon]
|
||||
: (polygons as Polygon[]);
|
||||
|
||||
const rotationCenter: Point = [0, 0];
|
||||
if (angle) {
|
||||
for (const polygon of polygonList) {
|
||||
rotatePoints(polygon, rotationCenter, angle);
|
||||
}
|
||||
}
|
||||
const lines = straightHachureLines(polygonList, gap, hachureStepOffset);
|
||||
if (angle) {
|
||||
for (const polygon of polygonList) {
|
||||
rotatePoints(polygon, rotationCenter, -angle);
|
||||
}
|
||||
rotateLines(lines, rotationCenter, -angle);
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
function straightHachureLines(
|
||||
polygons: Polygon[],
|
||||
gap: number,
|
||||
hachureStepOffset: number,
|
||||
): Line[] {
|
||||
const vertexArray: Point[][] = [];
|
||||
for (const polygon of polygons) {
|
||||
const vertices = [...polygon];
|
||||
if (!areSamePoints(vertices[0], vertices[vertices.length - 1])) {
|
||||
vertices.push([vertices[0][0], vertices[0][1]]);
|
||||
}
|
||||
if (vertices.length > 2) {
|
||||
vertexArray.push(vertices);
|
||||
}
|
||||
}
|
||||
|
||||
const lines: Line[] = [];
|
||||
gap = Math.max(gap, 0.1);
|
||||
|
||||
// Create sorted edges table
|
||||
const edges: EdgeEntry[] = [];
|
||||
|
||||
for (const vertices of vertexArray) {
|
||||
for (let i = 0; i < vertices.length - 1; i++) {
|
||||
const p1 = vertices[i];
|
||||
const p2 = vertices[i + 1];
|
||||
if (p1[1] !== p2[1]) {
|
||||
const ymin = Math.min(p1[1], p2[1]);
|
||||
edges.push({
|
||||
ymin,
|
||||
ymax: Math.max(p1[1], p2[1]),
|
||||
x: ymin === p1[1] ? p1[0] : p2[0],
|
||||
islope: (p2[0] - p1[0]) / (p2[1] - p1[1]),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
edges.sort((e1, e2) => {
|
||||
if (e1.ymin < e2.ymin) {
|
||||
return -1;
|
||||
}
|
||||
if (e1.ymin > e2.ymin) {
|
||||
return 1;
|
||||
}
|
||||
if (e1.x < e2.x) {
|
||||
return -1;
|
||||
}
|
||||
if (e1.x > e2.x) {
|
||||
return 1;
|
||||
}
|
||||
if (e1.ymax === e2.ymax) {
|
||||
return 0;
|
||||
}
|
||||
return (e1.ymax - e2.ymax) / Math.abs(e1.ymax - e2.ymax);
|
||||
});
|
||||
if (!edges.length) {
|
||||
return lines;
|
||||
}
|
||||
|
||||
// Start scanning
|
||||
let activeEdges: ActiveEdgeEntry[] = [];
|
||||
let y = edges[0].ymin;
|
||||
let iteration = 0;
|
||||
while (activeEdges.length || edges.length) {
|
||||
if (edges.length) {
|
||||
let ix = -1;
|
||||
for (let i = 0; i < edges.length; i++) {
|
||||
if (edges[i].ymin > y) {
|
||||
break;
|
||||
}
|
||||
ix = i;
|
||||
}
|
||||
const removed = edges.splice(0, ix + 1);
|
||||
removed.forEach((edge) => {
|
||||
activeEdges.push({ s: y, edge });
|
||||
});
|
||||
}
|
||||
activeEdges = activeEdges.filter((ae) => {
|
||||
if (ae.edge.ymax <= y) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
activeEdges.sort((ae1, ae2) => {
|
||||
if (ae1.edge.x === ae2.edge.x) {
|
||||
return 0;
|
||||
}
|
||||
return (ae1.edge.x - ae2.edge.x) / Math.abs(ae1.edge.x - ae2.edge.x);
|
||||
});
|
||||
|
||||
// fill between the edges
|
||||
if (hachureStepOffset !== 1 || iteration % gap === 0) {
|
||||
if (activeEdges.length > 1) {
|
||||
for (let i = 0; i < activeEdges.length; i = i + 2) {
|
||||
const nexti = i + 1;
|
||||
if (nexti >= activeEdges.length) {
|
||||
break;
|
||||
}
|
||||
const ce = activeEdges[i].edge;
|
||||
const ne = activeEdges[nexti].edge;
|
||||
lines.push([
|
||||
[Math.round(ce.x), y],
|
||||
[Math.round(ne.x), y],
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
y += hachureStepOffset;
|
||||
activeEdges.forEach((ae) => {
|
||||
ae.edge.x = ae.edge.x + hachureStepOffset * ae.edge.islope;
|
||||
});
|
||||
iteration++;
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
export { rough } from "./rough";
|
||||
export { RoughCanvas } from "./canvas";
|
||||
export { RoughSVG } from "./svg";
|
||||
export { RoughGenerator } from "./generator";
|
||||
|
||||
export type {
|
||||
Config,
|
||||
DrawingSurface,
|
||||
Drawable,
|
||||
Op,
|
||||
OpSet,
|
||||
OpSetType,
|
||||
OpType,
|
||||
Options,
|
||||
PathInfo,
|
||||
ResolvedOptions,
|
||||
} from "./core";
|
||||
export type { Point as RoughPoint } from "./geometry";
|
||||
@@ -0,0 +1,123 @@
|
||||
// Ported from path-data-parser@0.1.0 (src/absolutize.ts): https://github.com/pshihn/path-data-parser
|
||||
// MIT License, Copyright (c) 2020 Preet Shihn. See LICENSE.
|
||||
|
||||
// the loop callbacks run synchronously, so they never see a stale variable
|
||||
/* eslint-disable no-loop-func */
|
||||
|
||||
import type { Segment } from "./parser";
|
||||
|
||||
// Translate relative commands to absolute commands
|
||||
export function absolutize(segments: Segment[]): Segment[] {
|
||||
let cx = 0;
|
||||
let cy = 0;
|
||||
let subx = 0;
|
||||
let suby = 0;
|
||||
const out: Segment[] = [];
|
||||
for (const { key, data } of segments) {
|
||||
switch (key) {
|
||||
case "M":
|
||||
out.push({ key: "M", data: [...data] });
|
||||
[cx, cy] = data;
|
||||
[subx, suby] = data;
|
||||
break;
|
||||
case "m":
|
||||
cx += data[0];
|
||||
cy += data[1];
|
||||
out.push({ key: "M", data: [cx, cy] });
|
||||
subx = cx;
|
||||
suby = cy;
|
||||
break;
|
||||
case "L":
|
||||
out.push({ key: "L", data: [...data] });
|
||||
[cx, cy] = data;
|
||||
break;
|
||||
case "l":
|
||||
cx += data[0];
|
||||
cy += data[1];
|
||||
out.push({ key: "L", data: [cx, cy] });
|
||||
break;
|
||||
case "C":
|
||||
out.push({ key: "C", data: [...data] });
|
||||
cx = data[4];
|
||||
cy = data[5];
|
||||
break;
|
||||
case "c": {
|
||||
const newdata = data.map((d, i) => (i % 2 ? d + cy : d + cx));
|
||||
out.push({ key: "C", data: newdata });
|
||||
cx = newdata[4];
|
||||
cy = newdata[5];
|
||||
break;
|
||||
}
|
||||
case "Q":
|
||||
out.push({ key: "Q", data: [...data] });
|
||||
cx = data[2];
|
||||
cy = data[3];
|
||||
break;
|
||||
case "q": {
|
||||
const newdata = data.map((d, i) => (i % 2 ? d + cy : d + cx));
|
||||
out.push({ key: "Q", data: newdata });
|
||||
cx = newdata[2];
|
||||
cy = newdata[3];
|
||||
break;
|
||||
}
|
||||
case "A":
|
||||
out.push({ key: "A", data: [...data] });
|
||||
cx = data[5];
|
||||
cy = data[6];
|
||||
break;
|
||||
case "a":
|
||||
cx += data[5];
|
||||
cy += data[6];
|
||||
out.push({
|
||||
key: "A",
|
||||
data: [data[0], data[1], data[2], data[3], data[4], cx, cy],
|
||||
});
|
||||
break;
|
||||
case "H":
|
||||
out.push({ key: "H", data: [...data] });
|
||||
cx = data[0];
|
||||
break;
|
||||
case "h":
|
||||
cx += data[0];
|
||||
out.push({ key: "H", data: [cx] });
|
||||
break;
|
||||
case "V":
|
||||
out.push({ key: "V", data: [...data] });
|
||||
cy = data[0];
|
||||
break;
|
||||
case "v":
|
||||
cy += data[0];
|
||||
out.push({ key: "V", data: [cy] });
|
||||
break;
|
||||
case "S":
|
||||
out.push({ key: "S", data: [...data] });
|
||||
cx = data[2];
|
||||
cy = data[3];
|
||||
break;
|
||||
case "s": {
|
||||
const newdata = data.map((d, i) => (i % 2 ? d + cy : d + cx));
|
||||
out.push({ key: "S", data: newdata });
|
||||
cx = newdata[2];
|
||||
cy = newdata[3];
|
||||
break;
|
||||
}
|
||||
case "T":
|
||||
out.push({ key: "T", data: [...data] });
|
||||
cx = data[0];
|
||||
cy = data[1];
|
||||
break;
|
||||
case "t":
|
||||
cx += data[0];
|
||||
cy += data[1];
|
||||
out.push({ key: "T", data: [cx, cy] });
|
||||
break;
|
||||
case "Z":
|
||||
case "z":
|
||||
out.push({ key: "Z", data: [] });
|
||||
cx = subx;
|
||||
cy = suby;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
// Ported from path-data-parser@0.1.0 (src/index.ts): https://github.com/pshihn/path-data-parser
|
||||
// MIT License, Copyright (c) 2020 Preet Shihn. See LICENSE.
|
||||
|
||||
export { parsePath, serialize } from "./parser";
|
||||
export { absolutize } from "./absolutize";
|
||||
export { normalize } from "./normalize";
|
||||
@@ -0,0 +1,280 @@
|
||||
// Ported from path-data-parser@0.1.0 (src/normalize.ts): https://github.com/pshihn/path-data-parser
|
||||
// MIT License, Copyright (c) 2020 Preet Shihn. See LICENSE.
|
||||
|
||||
import type { Segment } from "./parser";
|
||||
|
||||
// Normalize path to include only M, L, C, and Z commands
|
||||
export function normalize(segments: Segment[]): Segment[] {
|
||||
const out: Segment[] = [];
|
||||
|
||||
let lastType = "";
|
||||
let cx = 0;
|
||||
let cy = 0;
|
||||
let subx = 0;
|
||||
let suby = 0;
|
||||
let lcx = 0;
|
||||
let lcy = 0;
|
||||
|
||||
for (const { key, data } of segments) {
|
||||
switch (key) {
|
||||
case "M":
|
||||
out.push({ key: "M", data: [...data] });
|
||||
[cx, cy] = data;
|
||||
[subx, suby] = data;
|
||||
break;
|
||||
case "C":
|
||||
out.push({ key: "C", data: [...data] });
|
||||
cx = data[4];
|
||||
cy = data[5];
|
||||
lcx = data[2];
|
||||
lcy = data[3];
|
||||
break;
|
||||
case "L":
|
||||
out.push({ key: "L", data: [...data] });
|
||||
[cx, cy] = data;
|
||||
break;
|
||||
case "H":
|
||||
cx = data[0];
|
||||
out.push({ key: "L", data: [cx, cy] });
|
||||
break;
|
||||
case "V":
|
||||
cy = data[0];
|
||||
out.push({ key: "L", data: [cx, cy] });
|
||||
break;
|
||||
case "S": {
|
||||
let cx1 = 0;
|
||||
let cy1 = 0;
|
||||
if (lastType === "C" || lastType === "S") {
|
||||
cx1 = cx + (cx - lcx);
|
||||
cy1 = cy + (cy - lcy);
|
||||
} else {
|
||||
cx1 = cx;
|
||||
cy1 = cy;
|
||||
}
|
||||
out.push({ key: "C", data: [cx1, cy1, ...data] });
|
||||
lcx = data[0];
|
||||
lcy = data[1];
|
||||
cx = data[2];
|
||||
cy = data[3];
|
||||
break;
|
||||
}
|
||||
case "T": {
|
||||
const [x, y] = data;
|
||||
let x1 = 0;
|
||||
let y1 = 0;
|
||||
if (lastType === "Q" || lastType === "T") {
|
||||
x1 = cx + (cx - lcx);
|
||||
y1 = cy + (cy - lcy);
|
||||
} else {
|
||||
x1 = cx;
|
||||
y1 = cy;
|
||||
}
|
||||
const cx1 = cx + (2 * (x1 - cx)) / 3;
|
||||
const cy1 = cy + (2 * (y1 - cy)) / 3;
|
||||
const cx2 = x + (2 * (x1 - x)) / 3;
|
||||
const cy2 = y + (2 * (y1 - y)) / 3;
|
||||
out.push({ key: "C", data: [cx1, cy1, cx2, cy2, x, y] });
|
||||
lcx = x1;
|
||||
lcy = y1;
|
||||
cx = x;
|
||||
cy = y;
|
||||
break;
|
||||
}
|
||||
case "Q": {
|
||||
const [x1, y1, x, y] = data;
|
||||
const cx1 = cx + (2 * (x1 - cx)) / 3;
|
||||
const cy1 = cy + (2 * (y1 - cy)) / 3;
|
||||
const cx2 = x + (2 * (x1 - x)) / 3;
|
||||
const cy2 = y + (2 * (y1 - y)) / 3;
|
||||
out.push({ key: "C", data: [cx1, cy1, cx2, cy2, x, y] });
|
||||
lcx = x1;
|
||||
lcy = y1;
|
||||
cx = x;
|
||||
cy = y;
|
||||
break;
|
||||
}
|
||||
case "A": {
|
||||
const r1 = Math.abs(data[0]);
|
||||
const r2 = Math.abs(data[1]);
|
||||
const angle = data[2];
|
||||
const largeArcFlag = data[3];
|
||||
const sweepFlag = data[4];
|
||||
const x = data[5];
|
||||
const y = data[6];
|
||||
if (r1 === 0 || r2 === 0) {
|
||||
out.push({ key: "C", data: [cx, cy, x, y, x, y] });
|
||||
cx = x;
|
||||
cy = y;
|
||||
} else if (cx !== x || cy !== y) {
|
||||
const curves: number[][] = arcToCubicCurves(
|
||||
cx,
|
||||
cy,
|
||||
x,
|
||||
y,
|
||||
r1,
|
||||
r2,
|
||||
angle,
|
||||
largeArcFlag,
|
||||
sweepFlag,
|
||||
);
|
||||
curves.forEach((curve) => {
|
||||
out.push({ key: "C", data: curve });
|
||||
});
|
||||
cx = x;
|
||||
cy = y;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "Z":
|
||||
out.push({ key: "Z", data: [] });
|
||||
cx = subx;
|
||||
cy = suby;
|
||||
break;
|
||||
}
|
||||
lastType = key;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function degToRad(degrees: number): number {
|
||||
return (Math.PI * degrees) / 180;
|
||||
}
|
||||
|
||||
function rotate(x: number, y: number, angleRad: number): [number, number] {
|
||||
const X = x * Math.cos(angleRad) - y * Math.sin(angleRad);
|
||||
const Y = x * Math.sin(angleRad) + y * Math.cos(angleRad);
|
||||
return [X, Y];
|
||||
}
|
||||
|
||||
function arcToCubicCurves(
|
||||
x1: number,
|
||||
y1: number,
|
||||
x2: number,
|
||||
y2: number,
|
||||
r1: number,
|
||||
r2: number,
|
||||
angle: number,
|
||||
largeArcFlag: number,
|
||||
sweepFlag: number,
|
||||
recursive?: number[],
|
||||
): number[][] {
|
||||
const angleRad = degToRad(angle);
|
||||
let params: number[][] = [];
|
||||
|
||||
let f1 = 0;
|
||||
let f2 = 0;
|
||||
let cx = 0;
|
||||
let cy = 0;
|
||||
if (recursive) {
|
||||
[f1, f2, cx, cy] = recursive;
|
||||
} else {
|
||||
[x1, y1] = rotate(x1, y1, -angleRad);
|
||||
[x2, y2] = rotate(x2, y2, -angleRad);
|
||||
|
||||
const x = (x1 - x2) / 2;
|
||||
const y = (y1 - y2) / 2;
|
||||
let h = (x * x) / (r1 * r1) + (y * y) / (r2 * r2);
|
||||
if (h > 1) {
|
||||
h = Math.sqrt(h);
|
||||
r1 = h * r1;
|
||||
r2 = h * r2;
|
||||
}
|
||||
|
||||
const sign = largeArcFlag === sweepFlag ? -1 : 1;
|
||||
|
||||
const r1Pow = r1 * r1;
|
||||
const r2Pow = r2 * r2;
|
||||
|
||||
const left = r1Pow * r2Pow - r1Pow * y * y - r2Pow * x * x;
|
||||
const right = r1Pow * y * y + r2Pow * x * x;
|
||||
|
||||
const k = sign * Math.sqrt(Math.abs(left / right));
|
||||
|
||||
cx = (k * r1 * y) / r2 + (x1 + x2) / 2;
|
||||
cy = (k * -r2 * x) / r1 + (y1 + y2) / 2;
|
||||
|
||||
f1 = Math.asin(parseFloat(((y1 - cy) / r2).toFixed(9)));
|
||||
f2 = Math.asin(parseFloat(((y2 - cy) / r2).toFixed(9)));
|
||||
|
||||
if (x1 < cx) {
|
||||
f1 = Math.PI - f1;
|
||||
}
|
||||
if (x2 < cx) {
|
||||
f2 = Math.PI - f2;
|
||||
}
|
||||
|
||||
if (f1 < 0) {
|
||||
f1 = Math.PI * 2 + f1;
|
||||
}
|
||||
if (f2 < 0) {
|
||||
f2 = Math.PI * 2 + f2;
|
||||
}
|
||||
|
||||
if (sweepFlag && f1 > f2) {
|
||||
f1 = f1 - Math.PI * 2;
|
||||
}
|
||||
if (!sweepFlag && f2 > f1) {
|
||||
f2 = f2 - Math.PI * 2;
|
||||
}
|
||||
}
|
||||
|
||||
let df = f2 - f1;
|
||||
|
||||
if (Math.abs(df) > (Math.PI * 120) / 180) {
|
||||
const f2old = f2;
|
||||
const x2old = x2;
|
||||
const y2old = y2;
|
||||
|
||||
if (sweepFlag && f2 > f1) {
|
||||
f2 = f1 + ((Math.PI * 120) / 180) * 1;
|
||||
} else {
|
||||
f2 = f1 + ((Math.PI * 120) / 180) * -1;
|
||||
}
|
||||
|
||||
x2 = cx + r1 * Math.cos(f2);
|
||||
y2 = cy + r2 * Math.sin(f2);
|
||||
params = arcToCubicCurves(
|
||||
x2,
|
||||
y2,
|
||||
x2old,
|
||||
y2old,
|
||||
r1,
|
||||
r2,
|
||||
angle,
|
||||
0,
|
||||
sweepFlag,
|
||||
[f2, f2old, cx, cy],
|
||||
);
|
||||
}
|
||||
|
||||
df = f2 - f1;
|
||||
|
||||
const c1 = Math.cos(f1);
|
||||
const s1 = Math.sin(f1);
|
||||
const c2 = Math.cos(f2);
|
||||
const s2 = Math.sin(f2);
|
||||
const t = Math.tan(df / 4);
|
||||
const hx = (4 / 3) * r1 * t;
|
||||
const hy = (4 / 3) * r2 * t;
|
||||
|
||||
const m1 = [x1, y1];
|
||||
const m2 = [x1 + hx * s1, y1 - hy * c1];
|
||||
const m3 = [x2 + hx * s2, y2 - hy * c2];
|
||||
const m4 = [x2, y2];
|
||||
|
||||
m2[0] = 2 * m1[0] - m2[0];
|
||||
m2[1] = 2 * m1[1] - m2[1];
|
||||
|
||||
if (recursive) {
|
||||
return [m2, m3, m4].concat(params);
|
||||
}
|
||||
params = [m2, m3, m4].concat(params);
|
||||
const curves = [];
|
||||
for (let i = 0; i < params.length; i += 3) {
|
||||
const r1 = rotate(params[i][0], params[i][1], angleRad);
|
||||
const r2 = rotate(params[i + 1][0], params[i + 1][1], angleRad);
|
||||
const r3 = rotate(params[i + 2][0], params[i + 2][1], angleRad);
|
||||
curves.push([r1[0], r1[1], r2[0], r2[1], r3[0], r3[1]]);
|
||||
}
|
||||
return curves;
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
// Ported from path-data-parser@0.1.0 (src/parser.ts): https://github.com/pshihn/path-data-parser
|
||||
// MIT License, Copyright (c) 2020 Preet Shihn. See LICENSE.
|
||||
|
||||
const COMMAND = 0;
|
||||
const NUMBER = 1;
|
||||
const EOD = 2;
|
||||
type TokenType = 0 | 1 | 2;
|
||||
|
||||
interface PathToken {
|
||||
type: TokenType;
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface Segment {
|
||||
key: string;
|
||||
data: number[];
|
||||
}
|
||||
|
||||
const PARAMS: { [key: string]: number } = {
|
||||
A: 7,
|
||||
a: 7,
|
||||
C: 6,
|
||||
c: 6,
|
||||
H: 1,
|
||||
h: 1,
|
||||
L: 2,
|
||||
l: 2,
|
||||
M: 2,
|
||||
m: 2,
|
||||
Q: 4,
|
||||
q: 4,
|
||||
S: 4,
|
||||
s: 4,
|
||||
T: 2,
|
||||
t: 2,
|
||||
V: 1,
|
||||
v: 1,
|
||||
Z: 0,
|
||||
z: 0,
|
||||
};
|
||||
|
||||
function tokenize(d: string): PathToken[] {
|
||||
const tokens: PathToken[] = [];
|
||||
while (d !== "") {
|
||||
if (d.match(/^([ \t\r\n,]+)/)) {
|
||||
d = d.substr(RegExp.$1.length);
|
||||
} else if (d.match(/^([aAcChHlLmMqQsStTvVzZ])/)) {
|
||||
tokens[tokens.length] = { type: COMMAND, text: RegExp.$1 };
|
||||
d = d.substr(RegExp.$1.length);
|
||||
} else if (
|
||||
d.match(/^(([-+]?[0-9]+(\.[0-9]*)?|[-+]?\.[0-9]+)([eE][-+]?[0-9]+)?)/)
|
||||
) {
|
||||
tokens[tokens.length] = {
|
||||
type: NUMBER,
|
||||
text: `${parseFloat(RegExp.$1)}`,
|
||||
};
|
||||
d = d.substr(RegExp.$1.length);
|
||||
} else {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
tokens[tokens.length] = { type: EOD, text: "" };
|
||||
return tokens;
|
||||
}
|
||||
|
||||
function isType(token: PathToken, type: number) {
|
||||
return token.type === type;
|
||||
}
|
||||
|
||||
export function parsePath(d: string): Segment[] {
|
||||
const segments: Segment[] = [];
|
||||
const tokens = tokenize(d);
|
||||
let mode = "BOD";
|
||||
let index = 0;
|
||||
let token = tokens[index];
|
||||
while (!isType(token, EOD)) {
|
||||
let paramsCount = 0;
|
||||
const params: number[] = [];
|
||||
if (mode === "BOD") {
|
||||
if (token.text === "M" || token.text === "m") {
|
||||
index++;
|
||||
paramsCount = PARAMS[token.text];
|
||||
mode = token.text;
|
||||
} else {
|
||||
return parsePath(`M0,0${d}`);
|
||||
}
|
||||
} else if (isType(token, NUMBER)) {
|
||||
paramsCount = PARAMS[mode];
|
||||
} else {
|
||||
index++;
|
||||
paramsCount = PARAMS[token.text];
|
||||
mode = token.text;
|
||||
}
|
||||
if (index + paramsCount < tokens.length) {
|
||||
for (let i = index; i < index + paramsCount; i++) {
|
||||
const numbeToken = tokens[i];
|
||||
if (isType(numbeToken, NUMBER)) {
|
||||
params[params.length] = +numbeToken.text;
|
||||
} else {
|
||||
throw new Error(`Param not a number: ${mode},${numbeToken.text}`);
|
||||
}
|
||||
}
|
||||
if (typeof PARAMS[mode] === "number") {
|
||||
const segment: Segment = { key: mode, data: params };
|
||||
segments.push(segment);
|
||||
index += paramsCount;
|
||||
token = tokens[index];
|
||||
if (mode === "M") {
|
||||
mode = "L";
|
||||
}
|
||||
if (mode === "m") {
|
||||
mode = "l";
|
||||
}
|
||||
} else {
|
||||
throw new Error(`Bad segment: ${mode}`);
|
||||
}
|
||||
} else {
|
||||
throw new Error("Path data ended short");
|
||||
}
|
||||
}
|
||||
return segments;
|
||||
}
|
||||
|
||||
export function serialize(segments: Segment[]): string {
|
||||
const tokens: (string | number)[] = [];
|
||||
for (const { key, data } of segments) {
|
||||
tokens.push(key);
|
||||
switch (key) {
|
||||
case "C":
|
||||
case "c":
|
||||
tokens.push(
|
||||
data[0],
|
||||
`${data[1]},`,
|
||||
data[2],
|
||||
`${data[3]},`,
|
||||
data[4],
|
||||
data[5],
|
||||
);
|
||||
break;
|
||||
case "S":
|
||||
case "s":
|
||||
case "Q":
|
||||
case "q":
|
||||
tokens.push(data[0], `${data[1]},`, data[2], data[3]);
|
||||
break;
|
||||
default:
|
||||
tokens.push(...data);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return tokens.join(" ");
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
// Ported from points-on-path@0.2.1 (src/index.ts): https://github.com/pshihn/points-on-path
|
||||
// MIT License, Copyright (c) 2020 Preet Shihn. See LICENSE.
|
||||
|
||||
import { pointsOnBezierCurves, simplify } from "@excalidraw/math";
|
||||
|
||||
import { parsePath, absolutize, normalize } from "./pathData";
|
||||
|
||||
import type { Point } from "./geometry";
|
||||
|
||||
export function pointsOnPath(
|
||||
path: string,
|
||||
tolerance?: number,
|
||||
distance?: number,
|
||||
): Point[][] {
|
||||
const segments = parsePath(path);
|
||||
const normalized = normalize(absolutize(segments));
|
||||
|
||||
const sets: Point[][] = [];
|
||||
let currentPoints: Point[] = [];
|
||||
let start: Point = [0, 0];
|
||||
let pendingCurve: Point[] = [];
|
||||
|
||||
const appendPendingCurve = () => {
|
||||
if (pendingCurve.length >= 4) {
|
||||
currentPoints.push(...pointsOnBezierCurves(pendingCurve, tolerance));
|
||||
}
|
||||
pendingCurve = [];
|
||||
};
|
||||
|
||||
const appendPendingPoints = () => {
|
||||
appendPendingCurve();
|
||||
if (currentPoints.length) {
|
||||
sets.push(currentPoints);
|
||||
currentPoints = [];
|
||||
}
|
||||
};
|
||||
|
||||
for (const { key, data } of normalized) {
|
||||
switch (key) {
|
||||
case "M":
|
||||
appendPendingPoints();
|
||||
start = [data[0], data[1]];
|
||||
currentPoints.push(start);
|
||||
break;
|
||||
case "L":
|
||||
appendPendingCurve();
|
||||
currentPoints.push([data[0], data[1]]);
|
||||
break;
|
||||
case "C":
|
||||
if (!pendingCurve.length) {
|
||||
const lastPoint = currentPoints.length
|
||||
? currentPoints[currentPoints.length - 1]
|
||||
: start;
|
||||
pendingCurve.push([lastPoint[0], lastPoint[1]]);
|
||||
}
|
||||
pendingCurve.push([data[0], data[1]]);
|
||||
pendingCurve.push([data[2], data[3]]);
|
||||
pendingCurve.push([data[4], data[5]]);
|
||||
break;
|
||||
case "Z":
|
||||
appendPendingCurve();
|
||||
currentPoints.push([start[0], start[1]]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
appendPendingPoints();
|
||||
|
||||
if (!distance) {
|
||||
return sets;
|
||||
}
|
||||
|
||||
const out: Point[][] = [];
|
||||
for (const set of sets) {
|
||||
const simplifiedSet = simplify(set, distance);
|
||||
if (simplifiedSet.length) {
|
||||
out.push(simplifiedSet);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,740 @@
|
||||
// Ported from roughjs@4.6.4 (src/renderer.ts): https://github.com/pshihn/rough/blob/7944f1c/src/renderer.ts
|
||||
// MIT License, Copyright (c) 2019 Preet Shihn. See LICENSE.
|
||||
|
||||
import { Random } from "@excalidraw/math";
|
||||
|
||||
import { getFiller } from "./fillers/filler";
|
||||
|
||||
import { parsePath, normalize, absolutize } from "./pathData";
|
||||
|
||||
import type { ResolvedOptions, Op, OpSet } from "./core";
|
||||
import type { Point } from "./geometry";
|
||||
import type { RenderHelper } from "./fillers/fillerInterface";
|
||||
|
||||
interface EllipseParams {
|
||||
rx: number;
|
||||
ry: number;
|
||||
increment: number;
|
||||
}
|
||||
|
||||
const helper: RenderHelper = {
|
||||
randOffset,
|
||||
randOffsetWithRange,
|
||||
ellipse,
|
||||
doubleLineOps: doubleLineFillOps,
|
||||
};
|
||||
|
||||
export function line(
|
||||
x1: number,
|
||||
y1: number,
|
||||
x2: number,
|
||||
y2: number,
|
||||
o: ResolvedOptions,
|
||||
): OpSet {
|
||||
return { type: "path", ops: _doubleLine(x1, y1, x2, y2, o) };
|
||||
}
|
||||
|
||||
export function linearPath(
|
||||
points: Point[],
|
||||
close: boolean,
|
||||
o: ResolvedOptions,
|
||||
): OpSet {
|
||||
const len = (points || []).length;
|
||||
if (len > 2) {
|
||||
const ops: Op[] = [];
|
||||
for (let i = 0; i < len - 1; i++) {
|
||||
ops.push(
|
||||
..._doubleLine(
|
||||
points[i][0],
|
||||
points[i][1],
|
||||
points[i + 1][0],
|
||||
points[i + 1][1],
|
||||
o,
|
||||
),
|
||||
);
|
||||
}
|
||||
if (close) {
|
||||
ops.push(
|
||||
..._doubleLine(
|
||||
points[len - 1][0],
|
||||
points[len - 1][1],
|
||||
points[0][0],
|
||||
points[0][1],
|
||||
o,
|
||||
),
|
||||
);
|
||||
}
|
||||
return { type: "path", ops };
|
||||
} else if (len === 2) {
|
||||
return line(points[0][0], points[0][1], points[1][0], points[1][1], o);
|
||||
}
|
||||
return { type: "path", ops: [] };
|
||||
}
|
||||
|
||||
export function polygon(points: Point[], o: ResolvedOptions): OpSet {
|
||||
return linearPath(points, true, o);
|
||||
}
|
||||
|
||||
export function rectangle(
|
||||
x: number,
|
||||
y: number,
|
||||
width: number,
|
||||
height: number,
|
||||
o: ResolvedOptions,
|
||||
): OpSet {
|
||||
const points: Point[] = [
|
||||
[x, y],
|
||||
[x + width, y],
|
||||
[x + width, y + height],
|
||||
[x, y + height],
|
||||
];
|
||||
return polygon(points, o);
|
||||
}
|
||||
|
||||
export function curve(points: Point[], o: ResolvedOptions): OpSet {
|
||||
let o1 = _curveWithOffset(points, 1 * (1 + o.roughness * 0.2), o);
|
||||
if (!o.disableMultiStroke) {
|
||||
const o2 = _curveWithOffset(
|
||||
points,
|
||||
1.5 * (1 + o.roughness * 0.22),
|
||||
cloneOptionsAlterSeed(o),
|
||||
);
|
||||
o1 = o1.concat(o2);
|
||||
}
|
||||
return { type: "path", ops: o1 };
|
||||
}
|
||||
|
||||
export interface EllipseResult {
|
||||
opset: OpSet;
|
||||
estimatedPoints: Point[];
|
||||
}
|
||||
|
||||
export function ellipse(
|
||||
x: number,
|
||||
y: number,
|
||||
width: number,
|
||||
height: number,
|
||||
o: ResolvedOptions,
|
||||
): OpSet {
|
||||
const params = generateEllipseParams(width, height, o);
|
||||
return ellipseWithParams(x, y, o, params).opset;
|
||||
}
|
||||
|
||||
export function generateEllipseParams(
|
||||
width: number,
|
||||
height: number,
|
||||
o: ResolvedOptions,
|
||||
): EllipseParams {
|
||||
const psq = Math.sqrt(
|
||||
Math.PI *
|
||||
2 *
|
||||
Math.sqrt((Math.pow(width / 2, 2) + Math.pow(height / 2, 2)) / 2),
|
||||
);
|
||||
const stepCount = Math.ceil(
|
||||
Math.max(o.curveStepCount, (o.curveStepCount / Math.sqrt(200)) * psq),
|
||||
);
|
||||
const increment = (Math.PI * 2) / stepCount;
|
||||
let rx = Math.abs(width / 2);
|
||||
let ry = Math.abs(height / 2);
|
||||
const curveFitRandomness = 1 - o.curveFitting;
|
||||
rx += _offsetOpt(rx * curveFitRandomness, o);
|
||||
ry += _offsetOpt(ry * curveFitRandomness, o);
|
||||
return { increment, rx, ry };
|
||||
}
|
||||
|
||||
export function ellipseWithParams(
|
||||
x: number,
|
||||
y: number,
|
||||
o: ResolvedOptions,
|
||||
ellipseParams: EllipseParams,
|
||||
): EllipseResult {
|
||||
const [ap1, cp1] = _computeEllipsePoints(
|
||||
ellipseParams.increment,
|
||||
x,
|
||||
y,
|
||||
ellipseParams.rx,
|
||||
ellipseParams.ry,
|
||||
1,
|
||||
ellipseParams.increment * _offset(0.1, _offset(0.4, 1, o), o),
|
||||
o,
|
||||
);
|
||||
let o1 = _curve(ap1, null, o);
|
||||
if (!o.disableMultiStroke && o.roughness !== 0) {
|
||||
const [ap2] = _computeEllipsePoints(
|
||||
ellipseParams.increment,
|
||||
x,
|
||||
y,
|
||||
ellipseParams.rx,
|
||||
ellipseParams.ry,
|
||||
1.5,
|
||||
0,
|
||||
o,
|
||||
);
|
||||
const o2 = _curve(ap2, null, o);
|
||||
o1 = o1.concat(o2);
|
||||
}
|
||||
return {
|
||||
estimatedPoints: cp1,
|
||||
opset: { type: "path", ops: o1 },
|
||||
};
|
||||
}
|
||||
|
||||
export function arc(
|
||||
x: number,
|
||||
y: number,
|
||||
width: number,
|
||||
height: number,
|
||||
start: number,
|
||||
stop: number,
|
||||
closed: boolean,
|
||||
roughClosure: boolean,
|
||||
o: ResolvedOptions,
|
||||
): OpSet {
|
||||
const cx = x;
|
||||
const cy = y;
|
||||
let rx = Math.abs(width / 2);
|
||||
let ry = Math.abs(height / 2);
|
||||
rx += _offsetOpt(rx * 0.01, o);
|
||||
ry += _offsetOpt(ry * 0.01, o);
|
||||
let strt = start;
|
||||
let stp = stop;
|
||||
while (strt < 0) {
|
||||
strt += Math.PI * 2;
|
||||
stp += Math.PI * 2;
|
||||
}
|
||||
if (stp - strt > Math.PI * 2) {
|
||||
strt = 0;
|
||||
stp = Math.PI * 2;
|
||||
}
|
||||
const ellipseInc = (Math.PI * 2) / o.curveStepCount;
|
||||
const arcInc = Math.min(ellipseInc / 2, (stp - strt) / 2);
|
||||
const ops = _arc(arcInc, cx, cy, rx, ry, strt, stp, 1, o);
|
||||
if (!o.disableMultiStroke) {
|
||||
const o2 = _arc(arcInc, cx, cy, rx, ry, strt, stp, 1.5, o);
|
||||
ops.push(...o2);
|
||||
}
|
||||
if (closed) {
|
||||
if (roughClosure) {
|
||||
ops.push(
|
||||
..._doubleLine(
|
||||
cx,
|
||||
cy,
|
||||
cx + rx * Math.cos(strt),
|
||||
cy + ry * Math.sin(strt),
|
||||
o,
|
||||
),
|
||||
..._doubleLine(
|
||||
cx,
|
||||
cy,
|
||||
cx + rx * Math.cos(stp),
|
||||
cy + ry * Math.sin(stp),
|
||||
o,
|
||||
),
|
||||
);
|
||||
} else {
|
||||
ops.push(
|
||||
{ op: "lineTo", data: [cx, cy] },
|
||||
{
|
||||
op: "lineTo",
|
||||
data: [cx + rx * Math.cos(strt), cy + ry * Math.sin(strt)],
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
return { type: "path", ops };
|
||||
}
|
||||
|
||||
export function svgPath(path: string, o: ResolvedOptions): OpSet {
|
||||
const segments = normalize(absolutize(parsePath(path)));
|
||||
const ops: Op[] = [];
|
||||
let first: Point = [0, 0];
|
||||
let current: Point = [0, 0];
|
||||
for (const { key, data } of segments) {
|
||||
switch (key) {
|
||||
case "M": {
|
||||
current = [data[0], data[1]];
|
||||
first = [data[0], data[1]];
|
||||
break;
|
||||
}
|
||||
case "L":
|
||||
ops.push(..._doubleLine(current[0], current[1], data[0], data[1], o));
|
||||
current = [data[0], data[1]];
|
||||
break;
|
||||
case "C": {
|
||||
const [x1, y1, x2, y2, x, y] = data;
|
||||
ops.push(..._bezierTo(x1, y1, x2, y2, x, y, current, o));
|
||||
current = [x, y];
|
||||
break;
|
||||
}
|
||||
case "Z":
|
||||
ops.push(..._doubleLine(current[0], current[1], first[0], first[1], o));
|
||||
current = [first[0], first[1]];
|
||||
break;
|
||||
}
|
||||
}
|
||||
return { type: "path", ops };
|
||||
}
|
||||
|
||||
// Fills
|
||||
|
||||
export function solidFillPolygon(
|
||||
polygonList: Point[][],
|
||||
o: ResolvedOptions,
|
||||
): OpSet {
|
||||
const ops: Op[] = [];
|
||||
for (const points of polygonList) {
|
||||
if (points.length) {
|
||||
const offset = o.maxRandomnessOffset || 0;
|
||||
const len = points.length;
|
||||
if (len > 2) {
|
||||
ops.push({
|
||||
op: "move",
|
||||
data: [
|
||||
points[0][0] + _offsetOpt(offset, o),
|
||||
points[0][1] + _offsetOpt(offset, o),
|
||||
],
|
||||
});
|
||||
for (let i = 1; i < len; i++) {
|
||||
ops.push({
|
||||
op: "lineTo",
|
||||
data: [
|
||||
points[i][0] + _offsetOpt(offset, o),
|
||||
points[i][1] + _offsetOpt(offset, o),
|
||||
],
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return { type: "fillPath", ops };
|
||||
}
|
||||
|
||||
export function patternFillPolygons(
|
||||
polygonList: Point[][],
|
||||
o: ResolvedOptions,
|
||||
): OpSet {
|
||||
return getFiller(o, helper).fillPolygons(polygonList, o);
|
||||
}
|
||||
|
||||
export function patternFillArc(
|
||||
x: number,
|
||||
y: number,
|
||||
width: number,
|
||||
height: number,
|
||||
start: number,
|
||||
stop: number,
|
||||
o: ResolvedOptions,
|
||||
): OpSet {
|
||||
const cx = x;
|
||||
const cy = y;
|
||||
let rx = Math.abs(width / 2);
|
||||
let ry = Math.abs(height / 2);
|
||||
rx += _offsetOpt(rx * 0.01, o);
|
||||
ry += _offsetOpt(ry * 0.01, o);
|
||||
let strt = start;
|
||||
let stp = stop;
|
||||
while (strt < 0) {
|
||||
strt += Math.PI * 2;
|
||||
stp += Math.PI * 2;
|
||||
}
|
||||
if (stp - strt > Math.PI * 2) {
|
||||
strt = 0;
|
||||
stp = Math.PI * 2;
|
||||
}
|
||||
const increment = (stp - strt) / o.curveStepCount;
|
||||
const points: Point[] = [];
|
||||
for (let angle = strt; angle <= stp; angle = angle + increment) {
|
||||
points.push([cx + rx * Math.cos(angle), cy + ry * Math.sin(angle)]);
|
||||
}
|
||||
points.push([cx + rx * Math.cos(stp), cy + ry * Math.sin(stp)]);
|
||||
points.push([cx, cy]);
|
||||
return patternFillPolygons([points], o);
|
||||
}
|
||||
|
||||
export function randOffset(x: number, o: ResolvedOptions): number {
|
||||
return _offsetOpt(x, o);
|
||||
}
|
||||
|
||||
export function randOffsetWithRange(
|
||||
min: number,
|
||||
max: number,
|
||||
o: ResolvedOptions,
|
||||
): number {
|
||||
return _offset(min, max, o);
|
||||
}
|
||||
|
||||
export function doubleLineFillOps(
|
||||
x1: number,
|
||||
y1: number,
|
||||
x2: number,
|
||||
y2: number,
|
||||
o: ResolvedOptions,
|
||||
): Op[] {
|
||||
return _doubleLine(x1, y1, x2, y2, o, true);
|
||||
}
|
||||
|
||||
// Private helpers
|
||||
|
||||
function cloneOptionsAlterSeed(ops: ResolvedOptions): ResolvedOptions {
|
||||
const result: ResolvedOptions = { ...ops };
|
||||
result.randomizer = undefined;
|
||||
if (ops.seed) {
|
||||
result.seed = ops.seed + 1;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function random(ops: ResolvedOptions): number {
|
||||
if (!ops.randomizer) {
|
||||
ops.randomizer = new Random(ops.seed || 0);
|
||||
}
|
||||
return ops.randomizer.next();
|
||||
}
|
||||
|
||||
function _offset(
|
||||
min: number,
|
||||
max: number,
|
||||
ops: ResolvedOptions,
|
||||
roughnessGain = 1,
|
||||
): number {
|
||||
return ops.roughness * roughnessGain * (random(ops) * (max - min) + min);
|
||||
}
|
||||
|
||||
function _offsetOpt(
|
||||
x: number,
|
||||
ops: ResolvedOptions,
|
||||
roughnessGain = 1,
|
||||
): number {
|
||||
return _offset(-x, x, ops, roughnessGain);
|
||||
}
|
||||
|
||||
function _doubleLine(
|
||||
x1: number,
|
||||
y1: number,
|
||||
x2: number,
|
||||
y2: number,
|
||||
o: ResolvedOptions,
|
||||
filling = false,
|
||||
): Op[] {
|
||||
const singleStroke = filling
|
||||
? o.disableMultiStrokeFill
|
||||
: o.disableMultiStroke;
|
||||
const o1 = _line(x1, y1, x2, y2, o, true, false);
|
||||
if (singleStroke) {
|
||||
return o1;
|
||||
}
|
||||
const o2 = _line(x1, y1, x2, y2, o, true, true);
|
||||
return o1.concat(o2);
|
||||
}
|
||||
|
||||
function _line(
|
||||
x1: number,
|
||||
y1: number,
|
||||
x2: number,
|
||||
y2: number,
|
||||
o: ResolvedOptions,
|
||||
move: boolean,
|
||||
overlay: boolean,
|
||||
): Op[] {
|
||||
const lengthSq = Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2);
|
||||
const length = Math.sqrt(lengthSq);
|
||||
let roughnessGain = 1;
|
||||
if (length < 200) {
|
||||
roughnessGain = 1;
|
||||
} else if (length > 500) {
|
||||
roughnessGain = 0.4;
|
||||
} else {
|
||||
roughnessGain = -0.0016668 * length + 1.233334;
|
||||
}
|
||||
|
||||
let offset = o.maxRandomnessOffset || 0;
|
||||
if (offset * offset * 100 > lengthSq) {
|
||||
offset = length / 10;
|
||||
}
|
||||
const halfOffset = offset / 2;
|
||||
const divergePoint = 0.2 + random(o) * 0.2;
|
||||
let midDispX = (o.bowing * o.maxRandomnessOffset * (y2 - y1)) / 200;
|
||||
let midDispY = (o.bowing * o.maxRandomnessOffset * (x1 - x2)) / 200;
|
||||
midDispX = _offsetOpt(midDispX, o, roughnessGain);
|
||||
midDispY = _offsetOpt(midDispY, o, roughnessGain);
|
||||
const ops: Op[] = [];
|
||||
const randomHalf = () => _offsetOpt(halfOffset, o, roughnessGain);
|
||||
const randomFull = () => _offsetOpt(offset, o, roughnessGain);
|
||||
const preserveVertices = o.preserveVertices;
|
||||
if (move) {
|
||||
if (overlay) {
|
||||
ops.push({
|
||||
op: "move",
|
||||
data: [
|
||||
x1 + (preserveVertices ? 0 : randomHalf()),
|
||||
y1 + (preserveVertices ? 0 : randomHalf()),
|
||||
],
|
||||
});
|
||||
} else {
|
||||
ops.push({
|
||||
op: "move",
|
||||
data: [
|
||||
x1 + (preserveVertices ? 0 : _offsetOpt(offset, o, roughnessGain)),
|
||||
y1 + (preserveVertices ? 0 : _offsetOpt(offset, o, roughnessGain)),
|
||||
],
|
||||
});
|
||||
}
|
||||
}
|
||||
if (overlay) {
|
||||
ops.push({
|
||||
op: "bcurveTo",
|
||||
data: [
|
||||
midDispX + x1 + (x2 - x1) * divergePoint + randomHalf(),
|
||||
midDispY + y1 + (y2 - y1) * divergePoint + randomHalf(),
|
||||
midDispX + x1 + 2 * (x2 - x1) * divergePoint + randomHalf(),
|
||||
midDispY + y1 + 2 * (y2 - y1) * divergePoint + randomHalf(),
|
||||
x2 + (preserveVertices ? 0 : randomHalf()),
|
||||
y2 + (preserveVertices ? 0 : randomHalf()),
|
||||
],
|
||||
});
|
||||
} else {
|
||||
ops.push({
|
||||
op: "bcurveTo",
|
||||
data: [
|
||||
midDispX + x1 + (x2 - x1) * divergePoint + randomFull(),
|
||||
midDispY + y1 + (y2 - y1) * divergePoint + randomFull(),
|
||||
midDispX + x1 + 2 * (x2 - x1) * divergePoint + randomFull(),
|
||||
midDispY + y1 + 2 * (y2 - y1) * divergePoint + randomFull(),
|
||||
x2 + (preserveVertices ? 0 : randomFull()),
|
||||
y2 + (preserveVertices ? 0 : randomFull()),
|
||||
],
|
||||
});
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
function _curveWithOffset(
|
||||
points: Point[],
|
||||
offset: number,
|
||||
o: ResolvedOptions,
|
||||
): Op[] {
|
||||
const ps: Point[] = [];
|
||||
ps.push([
|
||||
points[0][0] + _offsetOpt(offset, o),
|
||||
points[0][1] + _offsetOpt(offset, o),
|
||||
]);
|
||||
ps.push([
|
||||
points[0][0] + _offsetOpt(offset, o),
|
||||
points[0][1] + _offsetOpt(offset, o),
|
||||
]);
|
||||
for (let i = 1; i < points.length; i++) {
|
||||
ps.push([
|
||||
points[i][0] + _offsetOpt(offset, o),
|
||||
points[i][1] + _offsetOpt(offset, o),
|
||||
]);
|
||||
if (i === points.length - 1) {
|
||||
ps.push([
|
||||
points[i][0] + _offsetOpt(offset, o),
|
||||
points[i][1] + _offsetOpt(offset, o),
|
||||
]);
|
||||
}
|
||||
}
|
||||
return _curve(ps, null, o);
|
||||
}
|
||||
|
||||
function _curve(
|
||||
points: Point[],
|
||||
closePoint: Point | null,
|
||||
o: ResolvedOptions,
|
||||
): Op[] {
|
||||
const len = points.length;
|
||||
const ops: Op[] = [];
|
||||
if (len > 3) {
|
||||
const b = [];
|
||||
const s = 1 - o.curveTightness;
|
||||
ops.push({ op: "move", data: [points[1][0], points[1][1]] });
|
||||
for (let i = 1; i + 2 < len; i++) {
|
||||
const cachedVertArray = points[i];
|
||||
b[0] = [cachedVertArray[0], cachedVertArray[1]];
|
||||
b[1] = [
|
||||
cachedVertArray[0] + (s * points[i + 1][0] - s * points[i - 1][0]) / 6,
|
||||
cachedVertArray[1] + (s * points[i + 1][1] - s * points[i - 1][1]) / 6,
|
||||
];
|
||||
b[2] = [
|
||||
points[i + 1][0] + (s * points[i][0] - s * points[i + 2][0]) / 6,
|
||||
points[i + 1][1] + (s * points[i][1] - s * points[i + 2][1]) / 6,
|
||||
];
|
||||
b[3] = [points[i + 1][0], points[i + 1][1]];
|
||||
ops.push({
|
||||
op: "bcurveTo",
|
||||
data: [b[1][0], b[1][1], b[2][0], b[2][1], b[3][0], b[3][1]],
|
||||
});
|
||||
}
|
||||
if (closePoint && closePoint.length === 2) {
|
||||
const ro = o.maxRandomnessOffset;
|
||||
ops.push({
|
||||
op: "lineTo",
|
||||
data: [
|
||||
closePoint[0] + _offsetOpt(ro, o),
|
||||
closePoint[1] + _offsetOpt(ro, o),
|
||||
],
|
||||
});
|
||||
}
|
||||
} else if (len === 3) {
|
||||
ops.push({ op: "move", data: [points[1][0], points[1][1]] });
|
||||
ops.push({
|
||||
op: "bcurveTo",
|
||||
data: [
|
||||
points[1][0],
|
||||
points[1][1],
|
||||
points[2][0],
|
||||
points[2][1],
|
||||
points[2][0],
|
||||
points[2][1],
|
||||
],
|
||||
});
|
||||
} else if (len === 2) {
|
||||
ops.push(
|
||||
..._doubleLine(points[0][0], points[0][1], points[1][0], points[1][1], o),
|
||||
);
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
function _computeEllipsePoints(
|
||||
increment: number,
|
||||
cx: number,
|
||||
cy: number,
|
||||
rx: number,
|
||||
ry: number,
|
||||
offset: number,
|
||||
overlap: number,
|
||||
o: ResolvedOptions,
|
||||
): Point[][] {
|
||||
const coreOnly = o.roughness === 0;
|
||||
const corePoints: Point[] = [];
|
||||
const allPoints: Point[] = [];
|
||||
|
||||
if (coreOnly) {
|
||||
increment = increment / 4;
|
||||
allPoints.push([
|
||||
cx + rx * Math.cos(-increment),
|
||||
cy + ry * Math.sin(-increment),
|
||||
]);
|
||||
for (let angle = 0; angle <= Math.PI * 2; angle = angle + increment) {
|
||||
const p: Point = [cx + rx * Math.cos(angle), cy + ry * Math.sin(angle)];
|
||||
corePoints.push(p);
|
||||
allPoints.push(p);
|
||||
}
|
||||
allPoints.push([cx + rx * Math.cos(0), cy + ry * Math.sin(0)]);
|
||||
allPoints.push([
|
||||
cx + rx * Math.cos(increment),
|
||||
cy + ry * Math.sin(increment),
|
||||
]);
|
||||
} else {
|
||||
const radOffset = _offsetOpt(0.5, o) - Math.PI / 2;
|
||||
allPoints.push([
|
||||
_offsetOpt(offset, o) + cx + 0.9 * rx * Math.cos(radOffset - increment),
|
||||
_offsetOpt(offset, o) + cy + 0.9 * ry * Math.sin(radOffset - increment),
|
||||
]);
|
||||
const endAngle = Math.PI * 2 + radOffset - 0.01;
|
||||
for (let angle = radOffset; angle < endAngle; angle = angle + increment) {
|
||||
const p: Point = [
|
||||
_offsetOpt(offset, o) + cx + rx * Math.cos(angle),
|
||||
_offsetOpt(offset, o) + cy + ry * Math.sin(angle),
|
||||
];
|
||||
corePoints.push(p);
|
||||
allPoints.push(p);
|
||||
}
|
||||
allPoints.push([
|
||||
_offsetOpt(offset, o) +
|
||||
cx +
|
||||
rx * Math.cos(radOffset + Math.PI * 2 + overlap * 0.5),
|
||||
_offsetOpt(offset, o) +
|
||||
cy +
|
||||
ry * Math.sin(radOffset + Math.PI * 2 + overlap * 0.5),
|
||||
]);
|
||||
allPoints.push([
|
||||
_offsetOpt(offset, o) + cx + 0.98 * rx * Math.cos(radOffset + overlap),
|
||||
_offsetOpt(offset, o) + cy + 0.98 * ry * Math.sin(radOffset + overlap),
|
||||
]);
|
||||
allPoints.push([
|
||||
_offsetOpt(offset, o) +
|
||||
cx +
|
||||
0.9 * rx * Math.cos(radOffset + overlap * 0.5),
|
||||
_offsetOpt(offset, o) +
|
||||
cy +
|
||||
0.9 * ry * Math.sin(radOffset + overlap * 0.5),
|
||||
]);
|
||||
}
|
||||
|
||||
return [allPoints, corePoints];
|
||||
}
|
||||
|
||||
function _arc(
|
||||
increment: number,
|
||||
cx: number,
|
||||
cy: number,
|
||||
rx: number,
|
||||
ry: number,
|
||||
strt: number,
|
||||
stp: number,
|
||||
offset: number,
|
||||
o: ResolvedOptions,
|
||||
) {
|
||||
const radOffset = strt + _offsetOpt(0.1, o);
|
||||
const points: Point[] = [];
|
||||
points.push([
|
||||
_offsetOpt(offset, o) + cx + 0.9 * rx * Math.cos(radOffset - increment),
|
||||
_offsetOpt(offset, o) + cy + 0.9 * ry * Math.sin(radOffset - increment),
|
||||
]);
|
||||
for (let angle = radOffset; angle <= stp; angle = angle + increment) {
|
||||
points.push([
|
||||
_offsetOpt(offset, o) + cx + rx * Math.cos(angle),
|
||||
_offsetOpt(offset, o) + cy + ry * Math.sin(angle),
|
||||
]);
|
||||
}
|
||||
points.push([cx + rx * Math.cos(stp), cy + ry * Math.sin(stp)]);
|
||||
points.push([cx + rx * Math.cos(stp), cy + ry * Math.sin(stp)]);
|
||||
return _curve(points, null, o);
|
||||
}
|
||||
|
||||
function _bezierTo(
|
||||
x1: number,
|
||||
y1: number,
|
||||
x2: number,
|
||||
y2: number,
|
||||
x: number,
|
||||
y: number,
|
||||
current: Point,
|
||||
o: ResolvedOptions,
|
||||
): Op[] {
|
||||
const ops: Op[] = [];
|
||||
const ros = [o.maxRandomnessOffset || 1, (o.maxRandomnessOffset || 1) + 0.3];
|
||||
let f: Point = [0, 0];
|
||||
const iterations = o.disableMultiStroke ? 1 : 2;
|
||||
const preserveVertices = o.preserveVertices;
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
if (i === 0) {
|
||||
ops.push({ op: "move", data: [current[0], current[1]] });
|
||||
} else {
|
||||
ops.push({
|
||||
op: "move",
|
||||
data: [
|
||||
current[0] + (preserveVertices ? 0 : _offsetOpt(ros[0], o)),
|
||||
current[1] + (preserveVertices ? 0 : _offsetOpt(ros[0], o)),
|
||||
],
|
||||
});
|
||||
}
|
||||
f = preserveVertices
|
||||
? [x, y]
|
||||
: [x + _offsetOpt(ros[i], o), y + _offsetOpt(ros[i], o)];
|
||||
ops.push({
|
||||
op: "bcurveTo",
|
||||
data: [
|
||||
x1 + _offsetOpt(ros[i], o),
|
||||
y1 + _offsetOpt(ros[i], o),
|
||||
x2 + _offsetOpt(ros[i], o),
|
||||
y2 + _offsetOpt(ros[i], o),
|
||||
f[0],
|
||||
f[1],
|
||||
],
|
||||
});
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// Ported from roughjs@4.6.4 (src/rough.ts): https://github.com/pshihn/rough/blob/7944f1c/src/rough.ts
|
||||
// MIT License, Copyright (c) 2019 Preet Shihn. See LICENSE.
|
||||
|
||||
import { RoughCanvas } from "./canvas";
|
||||
import { RoughGenerator } from "./generator";
|
||||
import { RoughSVG } from "./svg";
|
||||
|
||||
import type { Config } from "./core";
|
||||
|
||||
export const rough = {
|
||||
canvas(canvas: HTMLCanvasElement, config?: Config): RoughCanvas {
|
||||
return new RoughCanvas(canvas, config);
|
||||
},
|
||||
|
||||
svg(svg: SVGSVGElement, config?: Config): RoughSVG {
|
||||
return new RoughSVG(svg, config);
|
||||
},
|
||||
|
||||
generator(config?: Config): RoughGenerator {
|
||||
return new RoughGenerator(config);
|
||||
},
|
||||
|
||||
newSeed(): number {
|
||||
return RoughGenerator.newSeed();
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,179 @@
|
||||
// Ported from roughjs@4.6.4 (src/svg.ts): https://github.com/pshihn/rough/blob/7944f1c/src/svg.ts
|
||||
// MIT License, Copyright (c) 2019 Preet Shihn. See LICENSE.
|
||||
|
||||
import { SVGNS } from "./core";
|
||||
import { RoughGenerator } from "./generator";
|
||||
|
||||
import type { Config, Options, OpSet, ResolvedOptions, Drawable } from "./core";
|
||||
import type { Point } from "./geometry";
|
||||
|
||||
export class RoughSVG {
|
||||
private gen: RoughGenerator;
|
||||
private svg: SVGSVGElement;
|
||||
|
||||
constructor(svg: SVGSVGElement, config?: Config) {
|
||||
this.svg = svg;
|
||||
this.gen = new RoughGenerator(config);
|
||||
}
|
||||
|
||||
draw(drawable: Drawable): SVGGElement {
|
||||
const sets = drawable.sets || [];
|
||||
const o = drawable.options || this.getDefaultOptions();
|
||||
const doc = this.svg.ownerDocument || window.document;
|
||||
const g = doc.createElementNS(SVGNS, "g");
|
||||
const precision = drawable.options.fixedDecimalPlaceDigits;
|
||||
for (const drawing of sets) {
|
||||
let path = null;
|
||||
switch (drawing.type) {
|
||||
case "path": {
|
||||
path = doc.createElementNS(SVGNS, "path");
|
||||
path.setAttribute("d", this.opsToPath(drawing, precision));
|
||||
path.setAttribute("stroke", o.stroke);
|
||||
path.setAttribute("stroke-width", `${o.strokeWidth}`);
|
||||
path.setAttribute("fill", "none");
|
||||
if (o.strokeLineDash) {
|
||||
path.setAttribute(
|
||||
"stroke-dasharray",
|
||||
o.strokeLineDash.join(" ").trim(),
|
||||
);
|
||||
}
|
||||
if (o.strokeLineDashOffset) {
|
||||
path.setAttribute("stroke-dashoffset", `${o.strokeLineDashOffset}`);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "fillPath": {
|
||||
path = doc.createElementNS(SVGNS, "path");
|
||||
path.setAttribute("d", this.opsToPath(drawing, precision));
|
||||
path.setAttribute("stroke", "none");
|
||||
path.setAttribute("stroke-width", "0");
|
||||
path.setAttribute("fill", o.fill || "");
|
||||
if (drawable.shape === "curve" || drawable.shape === "polygon") {
|
||||
path.setAttribute("fill-rule", "evenodd");
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "fillSketch": {
|
||||
path = this.fillSketch(doc, drawing, o);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (path) {
|
||||
g.appendChild(path);
|
||||
}
|
||||
}
|
||||
return g;
|
||||
}
|
||||
|
||||
private fillSketch(
|
||||
doc: Document,
|
||||
drawing: OpSet,
|
||||
o: ResolvedOptions,
|
||||
): SVGPathElement {
|
||||
let fweight = o.fillWeight;
|
||||
if (fweight < 0) {
|
||||
fweight = o.strokeWidth / 2;
|
||||
}
|
||||
const path = doc.createElementNS(SVGNS, "path");
|
||||
path.setAttribute("d", this.opsToPath(drawing, o.fixedDecimalPlaceDigits));
|
||||
path.setAttribute("stroke", o.fill || "");
|
||||
path.setAttribute("stroke-width", `${fweight}`);
|
||||
path.setAttribute("fill", "none");
|
||||
if (o.fillLineDash) {
|
||||
path.setAttribute("stroke-dasharray", o.fillLineDash.join(" ").trim());
|
||||
}
|
||||
if (o.fillLineDashOffset) {
|
||||
path.setAttribute("stroke-dashoffset", `${o.fillLineDashOffset}`);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
get generator(): RoughGenerator {
|
||||
return this.gen;
|
||||
}
|
||||
|
||||
getDefaultOptions(): ResolvedOptions {
|
||||
return this.gen.defaultOptions;
|
||||
}
|
||||
|
||||
opsToPath(drawing: OpSet, fixedDecimalPlaceDigits?: number): string {
|
||||
return this.gen.opsToPath(drawing, fixedDecimalPlaceDigits);
|
||||
}
|
||||
|
||||
line(
|
||||
x1: number,
|
||||
y1: number,
|
||||
x2: number,
|
||||
y2: number,
|
||||
options?: Options,
|
||||
): SVGGElement {
|
||||
const d = this.gen.line(x1, y1, x2, y2, options);
|
||||
return this.draw(d);
|
||||
}
|
||||
|
||||
rectangle(
|
||||
x: number,
|
||||
y: number,
|
||||
width: number,
|
||||
height: number,
|
||||
options?: Options,
|
||||
): SVGGElement {
|
||||
const d = this.gen.rectangle(x, y, width, height, options);
|
||||
return this.draw(d);
|
||||
}
|
||||
|
||||
ellipse(
|
||||
x: number,
|
||||
y: number,
|
||||
width: number,
|
||||
height: number,
|
||||
options?: Options,
|
||||
): SVGGElement {
|
||||
const d = this.gen.ellipse(x, y, width, height, options);
|
||||
return this.draw(d);
|
||||
}
|
||||
|
||||
circle(
|
||||
x: number,
|
||||
y: number,
|
||||
diameter: number,
|
||||
options?: Options,
|
||||
): SVGGElement {
|
||||
const d = this.gen.circle(x, y, diameter, options);
|
||||
return this.draw(d);
|
||||
}
|
||||
|
||||
linearPath(points: Point[], options?: Options): SVGGElement {
|
||||
const d = this.gen.linearPath(points, options);
|
||||
return this.draw(d);
|
||||
}
|
||||
|
||||
polygon(points: Point[], options?: Options): SVGGElement {
|
||||
const d = this.gen.polygon(points, options);
|
||||
return this.draw(d);
|
||||
}
|
||||
|
||||
arc(
|
||||
x: number,
|
||||
y: number,
|
||||
width: number,
|
||||
height: number,
|
||||
start: number,
|
||||
stop: number,
|
||||
closed: boolean = false,
|
||||
options?: Options,
|
||||
): SVGGElement {
|
||||
const d = this.gen.arc(x, y, width, height, start, stop, closed, options);
|
||||
return this.draw(d);
|
||||
}
|
||||
|
||||
curve(points: Point[], options?: Options): SVGGElement {
|
||||
const d = this.gen.curve(points, options);
|
||||
return this.draw(d);
|
||||
}
|
||||
|
||||
path(d: string, options?: Options): SVGGElement {
|
||||
const drawing = this.gen.path(d, options);
|
||||
return this.draw(drawing);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { RoughGenerator } from "../src";
|
||||
|
||||
import type { RoughPoint } from "../src";
|
||||
|
||||
describe("pattern fills", () => {
|
||||
// Excalidraw passes an element's own points to `polygon()`
|
||||
it("leave the caller's points untouched", () => {
|
||||
const points: RoughPoint[] = [
|
||||
[0, 0],
|
||||
[150, -40],
|
||||
[120, 130],
|
||||
[-60, 90],
|
||||
];
|
||||
const before = JSON.stringify(points);
|
||||
const generator = new RoughGenerator();
|
||||
|
||||
for (const fillStyle of ["hachure", "cross-hatch", "zigzag", "dashed"]) {
|
||||
generator.polygon(points, { seed: 1, fill: "red", fillStyle });
|
||||
}
|
||||
|
||||
expect(JSON.stringify(points)).toBe(before);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,370 @@
|
||||
// The port must produce exactly what roughjs 4.6.4 produces for the same
|
||||
// seed and options: every existing drawing's look depends on the exact
|
||||
// sequence of random draws. Remove this test (in favour of snapshots) once we
|
||||
// deliberately change the output.
|
||||
//
|
||||
// Each side gets its own copy of the input points (roughjs's pattern fills
|
||||
// rotate a polygon's points in place and back, which leaves float drift in
|
||||
// them) and the same `Math.random` sequence (the dots filler, and the hachure
|
||||
// skip offset when no seeded randomizer exists yet, call it).
|
||||
|
||||
import { RoughCanvas as UpstreamCanvas } from "roughjs/bin/canvas";
|
||||
import { RoughGenerator as UpstreamGenerator } from "roughjs/bin/generator";
|
||||
import { RoughSVG as UpstreamSVG } from "roughjs/bin/svg";
|
||||
|
||||
import { Random } from "@excalidraw/math";
|
||||
|
||||
import { RoughCanvas, RoughGenerator, RoughSVG } from "../src";
|
||||
|
||||
import type { Drawable, Options, RoughPoint } from "../src";
|
||||
|
||||
type Shape = {
|
||||
name: string;
|
||||
draw: (generator: RoughGenerator, options: Options) => Drawable;
|
||||
};
|
||||
|
||||
const random = new Random(42);
|
||||
const num = (min: number, max: number) => min + random.next() * (max - min);
|
||||
const points = (count: number, size: number): RoughPoint[] =>
|
||||
Array.from({ length: count }, () => [num(-size, size), num(-size, size)]);
|
||||
|
||||
const copy = (pts: RoughPoint[]) => pts.map(([x, y]): RoughPoint => [x, y]);
|
||||
|
||||
let mathRandom = new Random(99);
|
||||
|
||||
/** runs `fn` with `Math.random` restarted at a fixed sequence */
|
||||
const isolated = <T>(fn: () => T): T => {
|
||||
mathRandom = new Random(99);
|
||||
return fn();
|
||||
};
|
||||
|
||||
const PATH_POINTS = points(6, 150);
|
||||
const POLYGON_POINTS = points(7, 150);
|
||||
const CURVE_POINTS_2 = points(2, 100);
|
||||
const CURVE_POINTS_3 = points(3, 100);
|
||||
const CURVE_POINTS_12 = points(12, 200);
|
||||
|
||||
const SHAPES: Shape[] = [
|
||||
{
|
||||
name: "line",
|
||||
draw: (g, o) => g.line(0, 0, 120, 40, o),
|
||||
},
|
||||
{
|
||||
name: "long line",
|
||||
draw: (g, o) => g.line(-300, 10, 400, 380, o),
|
||||
},
|
||||
{
|
||||
name: "rectangle",
|
||||
draw: (g, o) => g.rectangle(10, 20, 200, 120, o),
|
||||
},
|
||||
{
|
||||
// a cross-hatch scan line lands on a boundary here, so float drift in
|
||||
// the points between the two passes changes the number of hachure lines
|
||||
name: "rectangle on a scan-line boundary",
|
||||
draw: (g, o) => g.rectangle(0, 0, 10, 33.7075484089997, o),
|
||||
},
|
||||
{
|
||||
name: "negative rectangle",
|
||||
draw: (g, o) => g.rectangle(10, 20, -80, -60, o),
|
||||
},
|
||||
{
|
||||
name: "ellipse",
|
||||
draw: (g, o) => g.ellipse(100, 60, 200, 120, o),
|
||||
},
|
||||
{
|
||||
name: "large ellipse",
|
||||
draw: (g, o) => g.ellipse(0, 0, 900, 300, o),
|
||||
},
|
||||
{
|
||||
name: "circle",
|
||||
draw: (g, o) => g.circle(50, 50, 80, o),
|
||||
},
|
||||
{
|
||||
name: "linearPath",
|
||||
draw: (g, o) => g.linearPath(copy(PATH_POINTS), o),
|
||||
},
|
||||
{
|
||||
name: "polygon",
|
||||
draw: (g, o) => g.polygon(copy(POLYGON_POINTS), o),
|
||||
},
|
||||
{
|
||||
name: "curve (2 points)",
|
||||
draw: (g, o) => g.curve(copy(CURVE_POINTS_2), o),
|
||||
},
|
||||
{
|
||||
name: "curve (3 points)",
|
||||
draw: (g, o) => g.curve(copy(CURVE_POINTS_3), o),
|
||||
},
|
||||
{
|
||||
name: "curve (12 points)",
|
||||
draw: (g, o) => g.curve(copy(CURVE_POINTS_12), o),
|
||||
},
|
||||
{
|
||||
name: "open arc",
|
||||
draw: (g, o) => g.arc(100, 100, 200, 160, 0.3, 2.1, false, o),
|
||||
},
|
||||
{
|
||||
name: "closed arc",
|
||||
draw: (g, o) => g.arc(100, 100, 200, 160, -1, Math.PI * 1.4, true, o),
|
||||
},
|
||||
{
|
||||
name: "full arc",
|
||||
draw: (g, o) => g.arc(0, 0, 300, 300, 0, Math.PI * 3, true, o),
|
||||
},
|
||||
{
|
||||
name: "reversed arc",
|
||||
draw: (g, o) => g.arc(0, 0, 300, 300, 2, 1, true, o),
|
||||
},
|
||||
{
|
||||
// the shape of an Excalidraw rounded rectangle
|
||||
name: "path (rounded rectangle)",
|
||||
draw: (g, o) =>
|
||||
g.path(
|
||||
"M 32 0 L 168 0 Q 200 0 200 32 L 200 88 Q 200 120 168 120 L 32 120 Q 0 120 0 88 L 0 32 Q 0 0 32 0",
|
||||
o,
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "path (relative commands)",
|
||||
draw: (g, o) =>
|
||||
g.path(
|
||||
"m10 10 h80 v40 c10 10 20 10 30 0 s20 -10 30 0 q10 20 20 0 t20 0 l-40 60 z",
|
||||
o,
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "path (arcs)",
|
||||
draw: (g, o) =>
|
||||
g.path(
|
||||
"M0 0 L100 0 A100 80 0 0 1 0 80 Z M150 0 a50 50 0 1 0 100 0 a50 50 0 1 0 -100 0",
|
||||
o,
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "path (subpaths, packed numbers)",
|
||||
draw: (g, o) =>
|
||||
g.path(
|
||||
"M0,0L-.5.5,10e1,20H150V-20ZM200 200C210,180-5e-1 160 230 200z",
|
||||
o,
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
const FILL_STYLES = [
|
||||
"hachure",
|
||||
"solid",
|
||||
"zigzag",
|
||||
"cross-hatch",
|
||||
"dots",
|
||||
"dashed",
|
||||
"zigzag-line",
|
||||
];
|
||||
|
||||
const OPTION_SETS: Options[] = [
|
||||
{},
|
||||
{ roughness: 0 },
|
||||
{ roughness: 0.5, bowing: 2 },
|
||||
{ roughness: 2 },
|
||||
{ roughness: 2.8, maxRandomnessOffset: 4 },
|
||||
{ disableMultiStroke: true },
|
||||
{ preserveVertices: true },
|
||||
{ roughness: 0, preserveVertices: true },
|
||||
{ curveFitting: 1 },
|
||||
{ curveFitting: 0.8, curveStepCount: 14 },
|
||||
{ curveTightness: 0.6 },
|
||||
{ strokeLineDash: [8, 4], strokeLineDashOffset: 2, strokeWidth: 2.5 },
|
||||
{ simplification: 0.6 },
|
||||
{ fixedDecimalPlaceDigits: 2 },
|
||||
...FILL_STYLES.map((fillStyle) => ({
|
||||
fill: "#a5d8ff",
|
||||
fillStyle,
|
||||
fillWeight: 1,
|
||||
// Excalidraw doesn't use these three, and they're expensive with a dense gap
|
||||
hachureGap: ["dots", "dashed", "zigzag-line"].includes(fillStyle) ? 24 : 8,
|
||||
})),
|
||||
{
|
||||
fill: "red",
|
||||
fillStyle: "hachure",
|
||||
hachureAngle: 30,
|
||||
hachureGap: 5,
|
||||
roughness: 0,
|
||||
},
|
||||
{ fill: "red", fillStyle: "cross-hatch", roughness: 0, strokeWidth: 2 },
|
||||
{ fill: "red", fillStyle: "solid", fillShapeRoughnessGain: 1.2 },
|
||||
{ fill: "red", fillStyle: "dashed", dashOffset: 6, dashGap: 3 },
|
||||
{ fill: "red", fillStyle: "zigzag-line", zigzagOffset: 3 },
|
||||
{
|
||||
fill: "red",
|
||||
fillStyle: "hachure",
|
||||
disableMultiStrokeFill: true,
|
||||
fillLineDash: [4, 2],
|
||||
fillLineDashOffset: 1,
|
||||
},
|
||||
{ fill: "red", stroke: "none" },
|
||||
// what Excalidraw passes for a dashed, hachure-filled shape
|
||||
{
|
||||
strokeLineDash: [8, 12],
|
||||
disableMultiStroke: true,
|
||||
strokeWidth: 2.5,
|
||||
fillWeight: 1,
|
||||
hachureGap: 8,
|
||||
roughness: 1,
|
||||
stroke: "#1e1e1e",
|
||||
preserveVertices: false,
|
||||
fillStyle: "hachure",
|
||||
fill: "#ffc9c9",
|
||||
curveFitting: 1,
|
||||
},
|
||||
];
|
||||
|
||||
const SEEDS = [1, 7, 1337, 2 ** 31 - 2];
|
||||
|
||||
const CASES = SHAPES.flatMap((shape) =>
|
||||
OPTION_SETS.flatMap((options, optionsIndex) =>
|
||||
SEEDS.map((seed) => ({
|
||||
name: `${shape.name} / options[${optionsIndex}] / seed ${seed}`,
|
||||
shape,
|
||||
options: { ...options, seed },
|
||||
})),
|
||||
),
|
||||
);
|
||||
|
||||
/** records every call and property assignment made on a 2D context */
|
||||
const recordingCanvas = () => {
|
||||
const log: unknown[] = [];
|
||||
const ctx = new Proxy(
|
||||
{},
|
||||
{
|
||||
get:
|
||||
(_, prop) =>
|
||||
(...args: unknown[]) =>
|
||||
log.push([prop, ...args]),
|
||||
set: (_, prop, value) => {
|
||||
log.push(["set", prop, value]);
|
||||
return true;
|
||||
},
|
||||
},
|
||||
);
|
||||
const canvas = { getContext: () => ctx } as unknown as HTMLCanvasElement;
|
||||
return { canvas, log };
|
||||
};
|
||||
|
||||
const svgElement = () =>
|
||||
document.createElementNS("http://www.w3.org/2000/svg", "svg");
|
||||
|
||||
// a few thousand cases each, which takes a few seconds
|
||||
describe("parity with roughjs 4.6.4", () => {
|
||||
const generator = new RoughGenerator();
|
||||
let drawables: Drawable[] = [];
|
||||
|
||||
beforeAll(() => {
|
||||
vi.spyOn(Math, "random").mockImplementation(() => mathRandom.next());
|
||||
drawables = CASES.map(({ shape, options }) =>
|
||||
isolated(() => shape.draw(generator, options)),
|
||||
);
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("generates identical drawables and paths", () => {
|
||||
const upstream = new UpstreamGenerator();
|
||||
const mismatches: string[] = [];
|
||||
|
||||
for (const [index, { name, shape, options }] of CASES.entries()) {
|
||||
const ours = drawables[index];
|
||||
const theirs = isolated(() =>
|
||||
shape.draw(upstream as unknown as RoughGenerator, options),
|
||||
);
|
||||
if (JSON.stringify(ours) !== JSON.stringify(theirs)) {
|
||||
mismatches.push(`drawable: ${name}`);
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
JSON.stringify(generator.toPaths(ours)) !==
|
||||
JSON.stringify(upstream.toPaths(theirs as any))
|
||||
) {
|
||||
mismatches.push(`toPaths: ${name}`);
|
||||
}
|
||||
for (const set of ours.sets) {
|
||||
if (generator.opsToPath(set, 3) !== upstream.opsToPath(set, 3)) {
|
||||
mismatches.push(`opsToPath: ${name}`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
expect(mismatches).toEqual([]);
|
||||
}, 30_000);
|
||||
|
||||
it("draws identically to a canvas", () => {
|
||||
const mismatches: string[] = [];
|
||||
|
||||
for (const [index, { name }] of CASES.entries()) {
|
||||
const drawable = drawables[index];
|
||||
const ours = recordingCanvas();
|
||||
const theirs = recordingCanvas();
|
||||
new RoughCanvas(ours.canvas).draw(drawable);
|
||||
new UpstreamCanvas(theirs.canvas).draw(drawable as any);
|
||||
if (JSON.stringify(ours.log) !== JSON.stringify(theirs.log)) {
|
||||
mismatches.push(name);
|
||||
}
|
||||
}
|
||||
|
||||
expect(mismatches).toEqual([]);
|
||||
}, 30_000);
|
||||
|
||||
it("draws identically to an SVG", () => {
|
||||
const mismatches: string[] = [];
|
||||
|
||||
for (const [index, { name }] of CASES.entries()) {
|
||||
const drawable = drawables[index];
|
||||
const ours = new RoughSVG(svgElement()).draw(drawable).outerHTML;
|
||||
const theirs = new UpstreamSVG(svgElement()).draw(
|
||||
drawable as any,
|
||||
).outerHTML;
|
||||
if (ours !== theirs) {
|
||||
mismatches.push(name);
|
||||
}
|
||||
}
|
||||
|
||||
expect(mismatches).toEqual([]);
|
||||
}, 30_000);
|
||||
|
||||
it("generates identically through the canvas and SVG shortcuts", () => {
|
||||
const options = { seed: 3, fill: "blue", fillStyle: "cross-hatch" };
|
||||
const pts = points(5, 100);
|
||||
|
||||
const ours = recordingCanvas();
|
||||
const theirs = recordingCanvas();
|
||||
const rc = new RoughCanvas(ours.canvas, { options: { roughness: 1.5 } });
|
||||
const urc = new UpstreamCanvas(theirs.canvas, {
|
||||
options: { roughness: 1.5 },
|
||||
});
|
||||
for (const rough of [rc, urc] as unknown as RoughCanvas[]) {
|
||||
isolated(() => {
|
||||
rough.line(0, 0, 50, 50, options);
|
||||
rough.rectangle(0, 0, 50, 50, options);
|
||||
rough.ellipse(0, 0, 50, 30, options);
|
||||
rough.circle(0, 0, 40, options);
|
||||
rough.linearPath(copy(pts), options);
|
||||
rough.polygon(copy(pts), options);
|
||||
rough.arc(0, 0, 80, 60, 0, 2, true, options);
|
||||
rough.curve(copy(pts), options);
|
||||
rough.path("M0 0 Q 50 50 100 0 T 200 0", options);
|
||||
});
|
||||
}
|
||||
expect(ours.log).toEqual(theirs.log);
|
||||
expect(rc.getDefaultOptions()).toEqual(urc.getDefaultOptions());
|
||||
|
||||
const svg = new RoughSVG(svgElement());
|
||||
const usvg = new UpstreamSVG(svgElement());
|
||||
expect(svg.polygon(copy(pts), options).outerHTML).toBe(
|
||||
usvg.polygon(copy(pts), options).outerHTML,
|
||||
);
|
||||
expect(svg.path("M0 0 C 10 40 60 40 70 0", options).outerHTML).toBe(
|
||||
usvg.path("M0 0 C 10 40 60 40 70 0", options).outerHTML,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"extends": "../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "../",
|
||||
"outDir": "./dist/types"
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["**/*.test.*", "tests", "types", "examples", "dist"]
|
||||
}
|
||||
@@ -68,14 +68,14 @@
|
||||
"perfect-freehand": "1.2.0",
|
||||
"png-chunk-text": "1.0.0",
|
||||
"png-chunks-encode": "1.0.0",
|
||||
"png-chunks-extract": "1.0.0",
|
||||
"roughjs": "4.6.4"
|
||||
"png-chunks-extract": "1.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@excalidraw/common": "workspace:*",
|
||||
"@excalidraw/element": "workspace:*",
|
||||
"@excalidraw/excalidraw": "workspace:*",
|
||||
"@excalidraw/math": "workspace:*",
|
||||
"@excalidraw/sloppy": "workspace:*",
|
||||
"cross-env": "7.0.3",
|
||||
"typescript": "5.9.3",
|
||||
"wawoff2": "2.0.1",
|
||||
|
||||
Generated
+19
-18
@@ -305,9 +305,6 @@ importers:
|
||||
nanoid:
|
||||
specifier: 3.3.8
|
||||
version: 3.3.8
|
||||
roughjs:
|
||||
specifier: 4.6.4
|
||||
version: 4.6.4
|
||||
tinycolor2:
|
||||
specifier: 1.6.0
|
||||
version: 1.6.0
|
||||
@@ -327,18 +324,15 @@ importers:
|
||||
'@excalidraw/math':
|
||||
specifier: workspace:*
|
||||
version: link:../math
|
||||
'@excalidraw/sloppy':
|
||||
specifier: workspace:*
|
||||
version: link:../sloppy
|
||||
lodash.throttle:
|
||||
specifier: 4.1.1
|
||||
version: 4.1.1
|
||||
perfect-freehand:
|
||||
specifier: 1.2.0
|
||||
version: 1.2.0
|
||||
points-on-curve:
|
||||
specifier: 0.2.0
|
||||
version: 0.2.0
|
||||
roughjs:
|
||||
specifier: 4.6.4
|
||||
version: 4.6.4
|
||||
devDependencies:
|
||||
'@excalidraw/laser-pointer':
|
||||
specifier: workspace:*
|
||||
@@ -394,6 +388,9 @@ importers:
|
||||
'@excalidraw/mermaid-to-excalidraw':
|
||||
specifier: 3.6.0
|
||||
version: 3.6.0
|
||||
'@excalidraw/sloppy':
|
||||
specifier: workspace:*
|
||||
version: link:../sloppy
|
||||
'@lezer/highlight':
|
||||
specifier: ^1.0.0
|
||||
version: 1.2.3
|
||||
@@ -451,18 +448,12 @@ importers:
|
||||
png-chunks-extract:
|
||||
specifier: 1.0.0
|
||||
version: 1.0.0
|
||||
points-on-curve:
|
||||
specifier: 0.2.0
|
||||
version: 0.2.0
|
||||
pwacompat:
|
||||
specifier: 2.0.17
|
||||
version: 2.0.17
|
||||
radix-ui:
|
||||
specifier: 1.4.3
|
||||
version: 1.4.3(@types/react-dom@19.0.4(@types/react@19.0.10))(@types/react@19.0.10)(react-dom@19.0.0(react@19.0.0))(react@19.0.0)
|
||||
roughjs:
|
||||
specifier: 4.6.4
|
||||
version: 4.6.4
|
||||
sass:
|
||||
specifier: 1.51.0
|
||||
version: 1.51.0
|
||||
@@ -559,6 +550,16 @@ importers:
|
||||
|
||||
packages/math: {}
|
||||
|
||||
packages/sloppy:
|
||||
dependencies:
|
||||
'@excalidraw/math':
|
||||
specifier: workspace:*
|
||||
version: link:../math
|
||||
devDependencies:
|
||||
roughjs:
|
||||
specifier: 4.6.4
|
||||
version: 4.6.4
|
||||
|
||||
packages/utils:
|
||||
dependencies:
|
||||
'@braintree/sanitize-url':
|
||||
@@ -585,9 +586,6 @@ importers:
|
||||
png-chunks-extract:
|
||||
specifier: 1.0.0
|
||||
version: 1.0.0
|
||||
roughjs:
|
||||
specifier: 4.6.4
|
||||
version: 4.6.4
|
||||
devDependencies:
|
||||
'@excalidraw/common':
|
||||
specifier: workspace:*
|
||||
@@ -601,6 +599,9 @@ importers:
|
||||
'@excalidraw/math':
|
||||
specifier: workspace:*
|
||||
version: link:../math
|
||||
'@excalidraw/sloppy':
|
||||
specifier: workspace:*
|
||||
version: link:../sloppy
|
||||
cross-env:
|
||||
specifier: 7.0.3
|
||||
version: 7.0.3
|
||||
|
||||
@@ -16,6 +16,7 @@ const getConfig = (outdir) => ({
|
||||
"@excalidraw/element",
|
||||
"@excalidraw/history",
|
||||
"@excalidraw/math",
|
||||
"@excalidraw/sloppy",
|
||||
"@excalidraw/fractional-indexing",
|
||||
],
|
||||
});
|
||||
|
||||
@@ -76,6 +76,7 @@ const getConfig = (outdir) => ({
|
||||
"@excalidraw/element",
|
||||
"@excalidraw/history",
|
||||
"@excalidraw/math",
|
||||
"@excalidraw/sloppy",
|
||||
"@excalidraw/fractional-indexing",
|
||||
],
|
||||
loader: {
|
||||
|
||||
@@ -10,6 +10,7 @@ const PACKAGES = [
|
||||
"common",
|
||||
"fractional-indexing",
|
||||
"math",
|
||||
"sloppy",
|
||||
"element",
|
||||
"history",
|
||||
"excalidraw",
|
||||
|
||||
Reference in new issue
Block a user