Sfoglia il codice sorgente

feat: improved freedraw (#3512)

Co-authored-by: dwelle <luzar.david@gmail.com>
vanilla_orig
Steve Ruiz 4 anni fa
parent
commit
49c6bdd520
Nessun account collegato all'indirizzo email del committer
66 ha cambiato i file con 782 aggiunte e 243 eliminazioni
  1. 1
    0
      package.json
  2. 10
    8
      src/actions/actionFinalize.tsx
  3. 2
    2
      src/actions/actionFlip.ts
  4. 1
    0
      src/actions/types.ts
  5. 12
    4
      src/components/Actions.tsx
  6. 120
    32
      src/components/App.tsx
  7. 1
    1
      src/components/HelpDialog.tsx
  8. 1
    1
      src/components/HintViewer.tsx
  9. 13
    2
      src/data/restore.ts
  10. 116
    44
      src/element/bounds.ts
  11. 98
    3
      src/element/collision.ts
  12. 17
    0
      src/element/newElement.ts
  13. 11
    3
      src/element/resizeElements.ts
  14. 3
    3
      src/element/sizeHelpers.ts
  15. 1
    1
      src/element/transformHandles.ts
  16. 15
    2
      src/element/typeChecks.ts
  17. 11
    1
      src/element/types.ts
  18. 1
    1
      src/locales/ar-SA.json
  19. 1
    1
      src/locales/bg-BG.json
  20. 1
    1
      src/locales/ca-ES.json
  21. 1
    1
      src/locales/de-DE.json
  22. 1
    1
      src/locales/el-GR.json
  23. 4
    1
      src/locales/en.json
  24. 1
    1
      src/locales/es-ES.json
  25. 1
    1
      src/locales/fa-IR.json
  26. 1
    1
      src/locales/fi-FI.json
  27. 1
    1
      src/locales/fr-FR.json
  28. 1
    1
      src/locales/he-IL.json
  29. 1
    1
      src/locales/hi-IN.json
  30. 1
    1
      src/locales/hu-HU.json
  31. 1
    1
      src/locales/id-ID.json
  32. 1
    1
      src/locales/it-IT.json
  33. 1
    1
      src/locales/ja-JP.json
  34. 1
    1
      src/locales/kab-KAB.json
  35. 1
    1
      src/locales/ko-KR.json
  36. 1
    1
      src/locales/my-MM.json
  37. 1
    1
      src/locales/nb-NO.json
  38. 1
    1
      src/locales/nl-NL.json
  39. 1
    1
      src/locales/nn-NO.json
  40. 1
    1
      src/locales/oc-FR.json
  41. 1
    1
      src/locales/pa-IN.json
  42. 1
    1
      src/locales/pl-PL.json
  43. 1
    1
      src/locales/pt-BR.json
  44. 1
    1
      src/locales/pt-PT.json
  45. 1
    1
      src/locales/ro-RO.json
  46. 1
    1
      src/locales/ru-RU.json
  47. 1
    1
      src/locales/sk-SK.json
  48. 1
    1
      src/locales/sv-SE.json
  49. 1
    1
      src/locales/tr-TR.json
  50. 1
    1
      src/locales/uk-UA.json
  51. 1
    1
      src/locales/zh-CN.json
  52. 1
    1
      src/locales/zh-TW.json
  53. 1
    0
      src/math.ts
  54. 1
    0
      src/points.ts
  55. 180
    28
      src/renderer/renderElement.ts
  56. 2
    1
      src/renderer/renderScene.ts
  57. 8
    5
      src/scene/comparisons.ts
  58. 2
    1
      src/scene/index.ts
  59. 1
    1
      src/shapes.tsx
  60. 91
    55
      src/tests/__snapshots__/regressionTests.test.tsx.snap
  61. 1
    1
      src/tests/flip.test.tsx
  62. 13
    3
      src/tests/helpers/api.ts
  63. 2
    2
      src/tests/helpers/ui.ts
  64. 1
    1
      src/tests/queries/toolQueries.ts
  65. 3
    3
      src/tests/regressionTests.test.tsx
  66. 5
    0
      yarn.lock

+ 1
- 0
package.json Vedi File

@@ -35,6 +35,7 @@
35 35
     "nanoid": "3.1.22",
36 36
     "open-color": "1.8.0",
37 37
     "pako": "1.0.11",
38
+    "perfect-freehand": "0.4.7",
38 39
     "png-chunk-text": "1.0.0",
39 40
     "png-chunks-encode": "1.0.0",
40 41
     "png-chunks-extract": "1.0.0",

+ 10
- 8
src/actions/actionFinalize.tsx Vedi File

@@ -56,14 +56,14 @@ export const actionFinalize = register({
56 56
 
57 57
     const multiPointElement = appState.multiElement
58 58
       ? appState.multiElement
59
-      : appState.editingElement?.type === "draw"
59
+      : appState.editingElement?.type === "freedraw"
60 60
       ? appState.editingElement
61 61
       : null;
62 62
 
63 63
     if (multiPointElement) {
64 64
       // pen and mouse have hover
65 65
       if (
66
-        multiPointElement.type !== "draw" &&
66
+        multiPointElement.type !== "freedraw" &&
67 67
         appState.lastPointerDownWith !== "touch"
68 68
       ) {
69 69
         const { points, lastCommittedPoint } = multiPointElement;
@@ -86,7 +86,7 @@ export const actionFinalize = register({
86 86
       const isLoop = isPathALoop(multiPointElement.points, appState.zoom.value);
87 87
       if (
88 88
         multiPointElement.type === "line" ||
89
-        multiPointElement.type === "draw"
89
+        multiPointElement.type === "freedraw"
90 90
       ) {
91 91
         if (isLoop) {
92 92
           const linePoints = multiPointElement.points;
@@ -118,22 +118,24 @@ export const actionFinalize = register({
118 118
         );
119 119
       }
120 120
 
121
-      if (!appState.elementLocked && appState.elementType !== "draw") {
121
+      if (!appState.elementLocked && appState.elementType !== "freedraw") {
122 122
         appState.selectedElementIds[multiPointElement.id] = true;
123 123
       }
124 124
     }
125
+
125 126
     if (
126
-      (!appState.elementLocked && appState.elementType !== "draw") ||
127
+      (!appState.elementLocked && appState.elementType !== "freedraw") ||
127 128
       !multiPointElement
128 129
     ) {
129 130
       resetCursor(canvas);
130 131
     }
132
+
131 133
     return {
132 134
       elements: newElements,
133 135
       appState: {
134 136
         ...appState,
135 137
         elementType:
136
-          (appState.elementLocked || appState.elementType === "draw") &&
138
+          (appState.elementLocked || appState.elementType === "freedraw") &&
137 139
           multiPointElement
138 140
             ? appState.elementType
139 141
             : "selection",
@@ -145,14 +147,14 @@ export const actionFinalize = register({
145 147
         selectedElementIds:
146 148
           multiPointElement &&
147 149
           !appState.elementLocked &&
148
-          appState.elementType !== "draw"
150
+          appState.elementType !== "freedraw"
149 151
             ? {
150 152
                 ...appState.selectedElementIds,
151 153
                 [multiPointElement.id]: true,
152 154
               }
153 155
             : appState.selectedElementIds,
154 156
       },
155
-      commitToHistory: appState.elementType === "draw",
157
+      commitToHistory: appState.elementType === "freedraw",
156 158
     };
157 159
   },
158 160
   keyTest: (event, appState) =>

+ 2
- 2
src/actions/actionFlip.ts Vedi File

@@ -6,7 +6,7 @@ import { ExcalidrawElement, NonDeleted } from "../element/types";
6 6
 import { normalizeAngle, resizeSingleElement } from "../element/resizeElements";
7 7
 import { AppState } from "../types";
8 8
 import { getTransformHandles } from "../element/transformHandles";
9
-import { isLinearElement } from "../element/typeChecks";
9
+import { isFreeDrawElement, isLinearElement } from "../element/typeChecks";
10 10
 import { updateBoundElements } from "../element/binding";
11 11
 import { LinearElementEditor } from "../element/linearElementEditor";
12 12
 
@@ -114,7 +114,7 @@ const flipElement = (
114 114
   const originalAngle = normalizeAngle(element.angle);
115 115
 
116 116
   let finalOffsetX = 0;
117
-  if (isLinearElement(element)) {
117
+  if (isLinearElement(element) || isFreeDrawElement(element)) {
118 118
     finalOffsetX =
119 119
       element.points.reduce((max, point) => Math.max(max, point[0]), 0) * 2 -
120 120
       element.width;

+ 1
- 0
src/actions/types.ts Vedi File

@@ -52,6 +52,7 @@ export type ActionName =
52 52
   | "changeBackgroundColor"
53 53
   | "changeFillStyle"
54 54
   | "changeStrokeWidth"
55
+  | "changeStrokeShape"
55 56
   | "changeSloppiness"
56 57
   | "changeStrokeStyle"
57 58
   | "changeArrowhead"

+ 12
- 4
src/components/Actions.tsx Vedi File

@@ -9,7 +9,8 @@ import {
9 9
   canHaveArrowheads,
10 10
   getTargetElements,
11 11
   hasBackground,
12
-  hasStroke,
12
+  hasStrokeStyle,
13
+  hasStrokeWidth,
13 14
   hasText,
14 15
 } from "../scene";
15 16
 import { SHAPES } from "../shapes";
@@ -53,10 +54,17 @@ export const SelectedShapeActions = ({
53 54
       {showChangeBackgroundIcons && renderAction("changeBackgroundColor")}
54 55
       {showFillIcons && renderAction("changeFillStyle")}
55 56
 
56
-      {(hasStroke(elementType) ||
57
-        targetElements.some((element) => hasStroke(element.type))) && (
57
+      {(hasStrokeWidth(elementType) ||
58
+        targetElements.some((element) => hasStrokeWidth(element.type))) &&
59
+        renderAction("changeStrokeWidth")}
60
+
61
+      {(elementType === "freedraw" ||
62
+        targetElements.some((element) => element.type === "freedraw")) &&
63
+        renderAction("changeStrokeShape")}
64
+
65
+      {(hasStrokeStyle(elementType) ||
66
+        targetElements.some((element) => hasStrokeStyle(element.type))) && (
58 67
         <>
59
-          {renderAction("changeStrokeWidth")}
60 68
           {renderAction("changeStrokeStyle")}
61 69
           {renderAction("changeSloppiness")}
62 70
         </>

+ 120
- 32
src/components/App.tsx Vedi File

@@ -1,4 +1,3 @@
1
-import { Point, simplify } from "points-on-curve";
2 1
 import React, { useContext } from "react";
3 2
 import { RoughCanvas } from "roughjs/bin/canvas";
4 3
 import rough from "roughjs/bin/rough";
@@ -70,7 +69,7 @@ import {
70 69
 import { loadFromBlob } from "../data";
71 70
 import { isValidLibrary } from "../data/json";
72 71
 import Library from "../data/library";
73
-import { restore } from "../data/restore";
72
+import { restore, restoreElements } from "../data/restore";
74 73
 import {
75 74
   dragNewElement,
76 75
   dragSelectedElements,
@@ -111,7 +110,7 @@ import {
111 110
 } from "../element/binding";
112 111
 import { LinearElementEditor } from "../element/linearElementEditor";
113 112
 import { mutateElement } from "../element/mutateElement";
114
-import { deepCopyElement } from "../element/newElement";
113
+import { deepCopyElement, newFreeDrawElement } from "../element/newElement";
115 114
 import { MaybeTransformHandleType } from "../element/transformHandles";
116 115
 import {
117 116
   isBindingElement,
@@ -122,6 +121,7 @@ import {
122 121
 import {
123 122
   ExcalidrawBindableElement,
124 123
   ExcalidrawElement,
124
+  ExcalidrawFreeDrawElement,
125 125
   ExcalidrawGenericElement,
126 126
   ExcalidrawLinearElement,
127 127
   ExcalidrawTextElement,
@@ -1266,7 +1266,7 @@ class App extends React.Component<AppProps, AppState> {
1266 1266
         });
1267 1267
       } else if (data.elements) {
1268 1268
         this.addElementsFromPasteOrLibrary({
1269
-          elements: data.elements,
1269
+          elements: restoreElements(data.elements),
1270 1270
           position: "cursor",
1271 1271
         });
1272 1272
       } else if (data.text) {
@@ -2341,7 +2341,6 @@ class App extends React.Component<AppProps, AppState> {
2341 2341
       return;
2342 2342
     } else if (
2343 2343
       this.state.elementType === "arrow" ||
2344
-      this.state.elementType === "draw" ||
2345 2344
       this.state.elementType === "line"
2346 2345
     ) {
2347 2346
       this.handleLinearElementOnPointerDown(
@@ -2349,6 +2348,12 @@ class App extends React.Component<AppProps, AppState> {
2349 2348
         this.state.elementType,
2350 2349
         pointerDownState,
2351 2350
       );
2351
+    } else if (this.state.elementType === "freedraw") {
2352
+      this.handleFreeDrawElementOnPointerDown(
2353
+        event,
2354
+        this.state.elementType,
2355
+        pointerDownState,
2356
+      );
2352 2357
     } else {
2353 2358
       this.createGenericElementOnPointerDown(
2354 2359
         this.state.elementType,
@@ -2845,6 +2850,65 @@ class App extends React.Component<AppProps, AppState> {
2845 2850
     }
2846 2851
   };
2847 2852
 
2853
+  private handleFreeDrawElementOnPointerDown = (
2854
+    event: React.PointerEvent<HTMLCanvasElement>,
2855
+    elementType: ExcalidrawFreeDrawElement["type"],
2856
+    pointerDownState: PointerDownState,
2857
+  ) => {
2858
+    // Begin a mark capture. This does not have to update state yet.
2859
+    const [gridX, gridY] = getGridPoint(
2860
+      pointerDownState.origin.x,
2861
+      pointerDownState.origin.y,
2862
+      null,
2863
+    );
2864
+
2865
+    const element = newFreeDrawElement({
2866
+      type: elementType,
2867
+      x: gridX,
2868
+      y: gridY,
2869
+      strokeColor: this.state.currentItemStrokeColor,
2870
+      backgroundColor: this.state.currentItemBackgroundColor,
2871
+      fillStyle: this.state.currentItemFillStyle,
2872
+      strokeWidth: this.state.currentItemStrokeWidth,
2873
+      strokeStyle: this.state.currentItemStrokeStyle,
2874
+      roughness: this.state.currentItemRoughness,
2875
+      opacity: this.state.currentItemOpacity,
2876
+      strokeSharpness: this.state.currentItemLinearStrokeSharpness,
2877
+      simulatePressure: event.pressure === 0.5,
2878
+    });
2879
+
2880
+    this.setState((prevState) => ({
2881
+      selectedElementIds: {
2882
+        ...prevState.selectedElementIds,
2883
+        [element.id]: false,
2884
+      },
2885
+    }));
2886
+
2887
+    const pressures = element.simulatePressure
2888
+      ? element.pressures
2889
+      : [...element.pressures, event.pressure];
2890
+
2891
+    mutateElement(element, {
2892
+      points: [[0, 0]],
2893
+      pressures,
2894
+    });
2895
+
2896
+    const boundElement = getHoveredElementForBinding(
2897
+      pointerDownState.origin,
2898
+      this.scene,
2899
+    );
2900
+    this.scene.replaceAllElements([
2901
+      ...this.scene.getElementsIncludingDeleted(),
2902
+      element,
2903
+    ]);
2904
+    this.setState({
2905
+      draggingElement: element,
2906
+      editingElement: element,
2907
+      startBoundElement: boundElement,
2908
+      suggestedBindings: [],
2909
+    });
2910
+  };
2911
+
2848 2912
   private handleLinearElementOnPointerDown = (
2849 2913
     event: React.PointerEvent<HTMLCanvasElement>,
2850 2914
     elementType: ExcalidrawLinearElement["type"],
@@ -2899,7 +2963,7 @@ class App extends React.Component<AppProps, AppState> {
2899 2963
       const [gridX, gridY] = getGridPoint(
2900 2964
         pointerDownState.origin.x,
2901 2965
         pointerDownState.origin.y,
2902
-        elementType === "draw" ? null : this.state.gridSize,
2966
+        this.state.gridSize,
2903 2967
       );
2904 2968
 
2905 2969
       /* If arrow is pre-arrowheads, it will have undefined for both start and end arrowheads.
@@ -3107,6 +3171,7 @@ class App extends React.Component<AppProps, AppState> {
3107 3171
       const hasHitASelectedElement = pointerDownState.hit.allHitElements.some(
3108 3172
         (element) => this.isASelectedElement(element),
3109 3173
       );
3174
+
3110 3175
       if (
3111 3176
         hasHitASelectedElement ||
3112 3177
         pointerDownState.hit.hasHitCommonBoundingBoxOfSelectedElements
@@ -3207,18 +3272,24 @@ class App extends React.Component<AppProps, AppState> {
3207 3272
         return;
3208 3273
       }
3209 3274
 
3210
-      if (isLinearElement(draggingElement)) {
3275
+      if (draggingElement.type === "freedraw") {
3276
+        const points = draggingElement.points;
3277
+        const dx = pointerCoords.x - draggingElement.x;
3278
+        const dy = pointerCoords.y - draggingElement.y;
3279
+
3280
+        const pressures = draggingElement.simulatePressure
3281
+          ? draggingElement.pressures
3282
+          : [...draggingElement.pressures, event.pressure];
3283
+
3284
+        mutateElement(draggingElement, {
3285
+          points: [...points, [dx, dy]],
3286
+          pressures,
3287
+        });
3288
+      } else if (isLinearElement(draggingElement)) {
3211 3289
         pointerDownState.drag.hasOccurred = true;
3212 3290
         const points = draggingElement.points;
3213
-        let dx: number;
3214
-        let dy: number;
3215
-        if (draggingElement.type === "draw") {
3216
-          dx = pointerCoords.x - draggingElement.x;
3217
-          dy = pointerCoords.y - draggingElement.y;
3218
-        } else {
3219
-          dx = gridX - draggingElement.x;
3220
-          dy = gridY - draggingElement.y;
3221
-        }
3291
+        let dx = gridX - draggingElement.x;
3292
+        let dy = gridY - draggingElement.y;
3222 3293
 
3223 3294
         if (getRotateWithDiscreteAngleKey(event) && points.length === 2) {
3224 3295
           ({ width: dx, height: dy } = getPerfectElementSize(
@@ -3231,19 +3302,11 @@ class App extends React.Component<AppProps, AppState> {
3231 3302
         if (points.length === 1) {
3232 3303
           mutateElement(draggingElement, { points: [...points, [dx, dy]] });
3233 3304
         } else if (points.length > 1) {
3234
-          if (draggingElement.type === "draw") {
3235
-            mutateElement(draggingElement, {
3236
-              points: simplify(
3237
-                [...(points as Point[]), [dx, dy]],
3238
-                0.7 / this.state.zoom.value,
3239
-              ),
3240
-            });
3241
-          } else {
3242
-            mutateElement(draggingElement, {
3243
-              points: [...points.slice(0, -1), [dx, dy]],
3244
-            });
3245
-          }
3305
+          mutateElement(draggingElement, {
3306
+            points: [...points.slice(0, -1), [dx, dy]],
3307
+          });
3246 3308
         }
3309
+
3247 3310
         if (isBindingElement(draggingElement)) {
3248 3311
           // When creating a linear element by dragging
3249 3312
           this.maybeSuggestBindingForLinearElementAtCursor(
@@ -3383,8 +3446,33 @@ class App extends React.Component<AppProps, AppState> {
3383 3446
         pointerDownState.eventListeners.onKeyUp!,
3384 3447
       );
3385 3448
 
3386
-      if (draggingElement?.type === "draw") {
3449
+      if (draggingElement?.type === "freedraw") {
3450
+        const pointerCoords = viewportCoordsToSceneCoords(
3451
+          childEvent,
3452
+          this.state,
3453
+        );
3454
+
3455
+        const points = draggingElement.points;
3456
+        let dx = pointerCoords.x - draggingElement.x;
3457
+        let dy = pointerCoords.y - draggingElement.y;
3458
+
3459
+        // Allows dots to avoid being flagged as infinitely small
3460
+        if (dx === points[0][0] && dy === points[0][1]) {
3461
+          dy += 0.0001;
3462
+          dx += 0.0001;
3463
+        }
3464
+
3465
+        const pressures = draggingElement.simulatePressure
3466
+          ? []
3467
+          : [...draggingElement.pressures, childEvent.pressure];
3468
+
3469
+        mutateElement(draggingElement, {
3470
+          points: [...points, [dx, dy]],
3471
+          pressures,
3472
+        });
3473
+
3387 3474
         this.actionManager.executeAction(actionFinalize);
3475
+
3388 3476
         return;
3389 3477
       }
3390 3478
 
@@ -3428,7 +3516,7 @@ class App extends React.Component<AppProps, AppState> {
3428 3516
             );
3429 3517
           }
3430 3518
           this.setState({ suggestedBindings: [], startBoundElement: null });
3431
-          if (!elementLocked && elementType !== "draw") {
3519
+          if (!elementLocked) {
3432 3520
             resetCursor(this.canvas);
3433 3521
             this.setState((prevState) => ({
3434 3522
               draggingElement: null,
@@ -3575,7 +3663,7 @@ class App extends React.Component<AppProps, AppState> {
3575 3663
         return;
3576 3664
       }
3577 3665
 
3578
-      if (!elementLocked && elementType !== "draw" && draggingElement) {
3666
+      if (!elementLocked && elementType !== "freedraw" && draggingElement) {
3579 3667
         this.setState((prevState) => ({
3580 3668
           selectedElementIds: {
3581 3669
             ...prevState.selectedElementIds,
@@ -3599,7 +3687,7 @@ class App extends React.Component<AppProps, AppState> {
3599 3687
         );
3600 3688
       }
3601 3689
 
3602
-      if (!elementLocked && elementType !== "draw") {
3690
+      if (!elementLocked && elementType !== "freedraw") {
3603 3691
         resetCursor(this.canvas);
3604 3692
         this.setState({
3605 3693
           draggingElement: null,

+ 1
- 1
src/components/HelpDialog.tsx Vedi File

@@ -153,7 +153,7 @@ export const HelpDialog = ({ onClose }: { onClose?: () => void }) => {
153 153
                 <Shortcut label={t("toolBar.arrow")} shortcuts={["A", "5"]} />
154 154
                 <Shortcut label={t("toolBar.line")} shortcuts={["P", "6"]} />
155 155
                 <Shortcut
156
-                  label={t("toolBar.draw")}
156
+                  label={t("toolBar.freedraw")}
157 157
                   shortcuts={["Shift+P", "7"]}
158 158
                 />
159 159
                 <Shortcut label={t("toolBar.text")} shortcuts={["T", "8"]} />

+ 1
- 1
src/components/HintViewer.tsx Vedi File

@@ -23,7 +23,7 @@ const getHints = ({ appState, elements }: Hint) => {
23 23
     return t("hints.linearElementMulti");
24 24
   }
25 25
 
26
-  if (elementType === "draw") {
26
+  if (elementType === "freedraw") {
27 27
     return t("hints.freeDraw");
28 28
   }
29 29
 

+ 13
- 2
src/data/restore.ts Vedi File

@@ -37,10 +37,12 @@ const getFontFamilyByName = (fontFamilyName: string): FontFamily => {
37 37
 
38 38
 const restoreElementWithProperties = <T extends ExcalidrawElement>(
39 39
   element: Required<T>,
40
-  extra: Omit<Required<T>, keyof ExcalidrawElement>,
40
+  extra: Omit<Required<T>, keyof ExcalidrawElement> & {
41
+    type?: ExcalidrawElement["type"];
42
+  },
41 43
 ): T => {
42 44
   const base: Pick<T, keyof ExcalidrawElement> = {
43
-    type: element.type,
45
+    type: extra.type || element.type,
44 46
     // all elements must have version > 0 so getSceneVersion() will pick up
45 47
     // newly added elements
46 48
     version: element.version || 1,
@@ -97,6 +99,14 @@ const restoreElement = (
97 99
         textAlign: element.textAlign || DEFAULT_TEXT_ALIGN,
98 100
         verticalAlign: element.verticalAlign || DEFAULT_VERTICAL_ALIGN,
99 101
       });
102
+    case "freedraw": {
103
+      return restoreElementWithProperties(element, {
104
+        points: element.points,
105
+        lastCommittedPoint: null,
106
+        simulatePressure: element.simulatePressure,
107
+        pressures: element.pressures,
108
+      });
109
+    }
100 110
     case "draw":
101 111
     case "line":
102 112
     case "arrow": {
@@ -106,6 +116,7 @@ const restoreElement = (
106 116
       } = element;
107 117
 
108 118
       return restoreElementWithProperties(element, {
119
+        type: element.type === "draw" ? "line" : element.type,
109 120
         startBinding: element.startBinding,
110 121
         endBinding: element.endBinding,
111 122
         points:

+ 116
- 44
src/element/bounds.ts Vedi File

@@ -1,4 +1,9 @@
1
-import { ExcalidrawElement, ExcalidrawLinearElement, Arrowhead } from "./types";
1
+import {
2
+  ExcalidrawElement,
3
+  ExcalidrawLinearElement,
4
+  Arrowhead,
5
+  ExcalidrawFreeDrawElement,
6
+} from "./types";
2 7
 import { distance2d, rotate } from "../math";
3 8
 import rough from "roughjs/bin/rough";
4 9
 import { Drawable, Op } from "roughjs/bin/core";
@@ -7,7 +12,7 @@ import {
7 12
   getShapeForElement,
8 13
   generateRoughOptions,
9 14
 } from "../renderer/renderElement";
10
-import { isLinearElement } from "./typeChecks";
15
+import { isFreeDrawElement, isLinearElement } from "./typeChecks";
11 16
 import { rescalePoints } from "../points";
12 17
 
13 18
 // x and y position of top left corner, x and y position of bottom right corner
@@ -18,7 +23,9 @@ export type Bounds = readonly [number, number, number, number];
18 23
 export const getElementAbsoluteCoords = (
19 24
   element: ExcalidrawElement,
20 25
 ): Bounds => {
21
-  if (isLinearElement(element)) {
26
+  if (isFreeDrawElement(element)) {
27
+    return getFreeDrawElementAbsoluteCoords(element);
28
+  } else if (isLinearElement(element)) {
22 29
     return getLinearElementAbsoluteCoords(element);
23 30
   }
24 31
   return [
@@ -120,9 +127,42 @@ const getMinMaxXYFromCurvePathOps = (
120 127
   return [minX, minY, maxX, maxY];
121 128
 };
122 129
 
130
+const getBoundsFromPoints = (
131
+  points: ExcalidrawFreeDrawElement["points"],
132
+): [number, number, number, number] => {
133
+  let minX = Infinity;
134
+  let minY = Infinity;
135
+  let maxX = -Infinity;
136
+  let maxY = -Infinity;
137
+
138
+  for (const [x, y] of points) {
139
+    minX = Math.min(minX, x);
140
+    minY = Math.min(minY, y);
141
+    maxX = Math.max(maxX, x);
142
+    maxY = Math.max(maxY, y);
143
+  }
144
+
145
+  return [minX, minY, maxX, maxY];
146
+};
147
+
148
+const getFreeDrawElementAbsoluteCoords = (
149
+  element: ExcalidrawFreeDrawElement,
150
+): [number, number, number, number] => {
151
+  const [minX, minY, maxX, maxY] = getBoundsFromPoints(element.points);
152
+
153
+  return [
154
+    minX + element.x,
155
+    minY + element.y,
156
+    maxX + element.x,
157
+    maxY + element.y,
158
+  ];
159
+};
160
+
123 161
 const getLinearElementAbsoluteCoords = (
124 162
   element: ExcalidrawLinearElement,
125 163
 ): [number, number, number, number] => {
164
+  let coords: [number, number, number, number];
165
+
126 166
   if (element.points.length < 2 || !getShapeForElement(element)) {
127 167
     // XXX this is just a poor estimate and not very useful
128 168
     const { minX, minY, maxX, maxY } = element.points.reduce(
@@ -137,27 +177,29 @@ const getLinearElementAbsoluteCoords = (
137 177
       },
138 178
       { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity },
139 179
     );
140
-    return [
180
+    coords = [
141 181
       minX + element.x,
142 182
       minY + element.y,
143 183
       maxX + element.x,
144 184
       maxY + element.y,
145 185
     ];
146
-  }
186
+  } else {
187
+    const shape = getShapeForElement(element) as Drawable[];
147 188
 
148
-  const shape = getShapeForElement(element) as Drawable[];
189
+    // first element is always the curve
190
+    const ops = getCurvePathOps(shape[0]);
149 191
 
150
-  // first element is always the curve
151
-  const ops = getCurvePathOps(shape[0]);
192
+    const [minX, minY, maxX, maxY] = getMinMaxXYFromCurvePathOps(ops);
152 193
 
153
-  const [minX, minY, maxX, maxY] = getMinMaxXYFromCurvePathOps(ops);
194
+    coords = [
195
+      minX + element.x,
196
+      minY + element.y,
197
+      maxX + element.x,
198
+      maxY + element.y,
199
+    ];
200
+  }
154 201
 
155
-  return [
156
-    minX + element.x,
157
-    minY + element.y,
158
-    maxX + element.x,
159
-    maxY + element.y,
160
-  ];
202
+  return coords;
161 203
 };
162 204
 
163 205
 export const getArrowheadPoints = (
@@ -231,7 +273,7 @@ export const getArrowheadPoints = (
231 273
   const ys = y2 - ny * minSize;
232 274
 
233 275
   if (arrowhead === "dot") {
234
-    const r = Math.hypot(ys - y2, xs - x2);
276
+    const r = Math.hypot(ys - y2, xs - x2) + element.strokeWidth;
235 277
     return [x2, y2, r];
236 278
   }
237 279
 
@@ -277,16 +319,31 @@ const getLinearElementRotatedBounds = (
277 319
   return getMinMaxXYFromCurvePathOps(ops, transformXY);
278 320
 };
279 321
 
322
+// We could cache this stuff
280 323
 export const getElementBounds = (
281 324
   element: ExcalidrawElement,
282 325
 ): [number, number, number, number] => {
326
+  let bounds: [number, number, number, number];
327
+
283 328
   const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
284 329
   const cx = (x1 + x2) / 2;
285 330
   const cy = (y1 + y2) / 2;
286
-  if (isLinearElement(element)) {
287
-    return getLinearElementRotatedBounds(element, cx, cy);
288
-  }
289
-  if (element.type === "diamond") {
331
+  if (isFreeDrawElement(element)) {
332
+    const [minX, minY, maxX, maxY] = getBoundsFromPoints(
333
+      element.points.map(([x, y]) =>
334
+        rotate(x, y, cx - element.x, cy - element.y, element.angle),
335
+      ),
336
+    );
337
+
338
+    return [
339
+      minX + element.x,
340
+      minY + element.y,
341
+      maxX + element.x,
342
+      maxY + element.y,
343
+    ];
344
+  } else if (isLinearElement(element)) {
345
+    bounds = getLinearElementRotatedBounds(element, cx, cy);
346
+  } else if (element.type === "diamond") {
290 347
     const [x11, y11] = rotate(cx, y1, cx, cy, element.angle);
291 348
     const [x12, y12] = rotate(cx, y2, cx, cy, element.angle);
292 349
     const [x22, y22] = rotate(x1, cy, cx, cy, element.angle);
@@ -295,26 +352,28 @@ export const getElementBounds = (
295 352
     const minY = Math.min(y11, y12, y22, y21);
296 353
     const maxX = Math.max(x11, x12, x22, x21);
297 354
     const maxY = Math.max(y11, y12, y22, y21);
298
-    return [minX, minY, maxX, maxY];
299
-  }
300
-  if (element.type === "ellipse") {
355
+    bounds = [minX, minY, maxX, maxY];
356
+  } else if (element.type === "ellipse") {
301 357
     const w = (x2 - x1) / 2;
302 358
     const h = (y2 - y1) / 2;
303 359
     const cos = Math.cos(element.angle);
304 360
     const sin = Math.sin(element.angle);
305 361
     const ww = Math.hypot(w * cos, h * sin);
306 362
     const hh = Math.hypot(h * cos, w * sin);
307
-    return [cx - ww, cy - hh, cx + ww, cy + hh];
363
+    bounds = [cx - ww, cy - hh, cx + ww, cy + hh];
364
+  } else {
365
+    const [x11, y11] = rotate(x1, y1, cx, cy, element.angle);
366
+    const [x12, y12] = rotate(x1, y2, cx, cy, element.angle);
367
+    const [x22, y22] = rotate(x2, y2, cx, cy, element.angle);
368
+    const [x21, y21] = rotate(x2, y1, cx, cy, element.angle);
369
+    const minX = Math.min(x11, x12, x22, x21);
370
+    const minY = Math.min(y11, y12, y22, y21);
371
+    const maxX = Math.max(x11, x12, x22, x21);
372
+    const maxY = Math.max(y11, y12, y22, y21);
373
+    bounds = [minX, minY, maxX, maxY];
308 374
   }
309
-  const [x11, y11] = rotate(x1, y1, cx, cy, element.angle);
310
-  const [x12, y12] = rotate(x1, y2, cx, cy, element.angle);
311
-  const [x22, y22] = rotate(x2, y2, cx, cy, element.angle);
312
-  const [x21, y21] = rotate(x2, y1, cx, cy, element.angle);
313
-  const minX = Math.min(x11, x12, x22, x21);
314
-  const minY = Math.min(y11, y12, y22, y21);
315
-  const maxX = Math.max(x11, x12, x22, x21);
316
-  const maxY = Math.max(y11, y12, y22, y21);
317
-  return [minX, minY, maxX, maxY];
375
+
376
+  return bounds;
318 377
 };
319 378
 
320 379
 export const getCommonBounds = (
@@ -345,7 +404,7 @@ export const getResizedElementAbsoluteCoords = (
345 404
   nextWidth: number,
346 405
   nextHeight: number,
347 406
 ): [number, number, number, number] => {
348
-  if (!isLinearElement(element)) {
407
+  if (!(isLinearElement(element) || isFreeDrawElement(element))) {
349 408
     return [
350 409
       element.x,
351 410
       element.y,
@@ -360,16 +419,29 @@ export const getResizedElementAbsoluteCoords = (
360 419
     rescalePoints(1, nextHeight, element.points),
361 420
   );
362 421
 
363
-  const gen = rough.generator();
364
-  const curve =
365
-    element.strokeSharpness === "sharp"
366
-      ? gen.linearPath(
367
-          points as [number, number][],
368
-          generateRoughOptions(element),
369
-        )
370
-      : gen.curve(points as [number, number][], generateRoughOptions(element));
371
-  const ops = getCurvePathOps(curve);
372
-  const [minX, minY, maxX, maxY] = getMinMaxXYFromCurvePathOps(ops);
422
+  let bounds: [number, number, number, number];
423
+
424
+  if (isFreeDrawElement(element)) {
425
+    // Free Draw
426
+    bounds = getBoundsFromPoints(points);
427
+  } else {
428
+    // Line
429
+    const gen = rough.generator();
430
+    const curve =
431
+      element.strokeSharpness === "sharp"
432
+        ? gen.linearPath(
433
+            points as [number, number][],
434
+            generateRoughOptions(element),
435
+          )
436
+        : gen.curve(
437
+            points as [number, number][],
438
+            generateRoughOptions(element),
439
+          );
440
+    const ops = getCurvePathOps(curve);
441
+    bounds = getMinMaxXYFromCurvePathOps(ops);
442
+  }
443
+
444
+  const [minX, minY, maxX, maxY] = bounds;
373 445
   return [
374 446
     minX + element.x,
375 447
     minY + element.y,

+ 98
- 3
src/element/collision.ts Vedi File

@@ -4,7 +4,13 @@ import * as GADirection from "../gadirections";
4 4
 import * as GALine from "../galines";
5 5
 import * as GATransform from "../gatransforms";
6 6
 
7
-import { isPathALoop, isPointInPolygon, rotate } from "../math";
7
+import {
8
+  distance2d,
9
+  rotatePoint,
10
+  isPathALoop,
11
+  isPointInPolygon,
12
+  rotate,
13
+} from "../math";
8 14
 import { pointsOnBezierCurves } from "points-on-curve";
9 15
 
10 16
 import {
@@ -16,6 +22,7 @@ import {
16 22
   ExcalidrawTextElement,
17 23
   ExcalidrawEllipseElement,
18 24
   NonDeleted,
25
+  ExcalidrawFreeDrawElement,
19 26
 } from "./types";
20 27
 
21 28
 import { getElementAbsoluteCoords, getCurvePathOps, Bounds } from "./bounds";
@@ -30,10 +37,17 @@ const isElementDraggableFromInside = (
30 37
   if (element.type === "arrow") {
31 38
     return false;
32 39
   }
40
+
41
+  if (element.type === "freedraw") {
42
+    return true;
43
+  }
44
+
33 45
   const isDraggableFromInside = element.backgroundColor !== "transparent";
34
-  if (element.type === "line" || element.type === "draw") {
46
+
47
+  if (element.type === "line") {
35 48
     return isDraggableFromInside && isPathALoop(element.points);
36 49
   }
50
+
37 51
   return isDraggableFromInside;
38 52
 };
39 53
 
@@ -81,6 +95,7 @@ const isHittingElementNotConsideringBoundingBox = (
81 95
       : isElementDraggableFromInside(element)
82 96
       ? isInsideCheck
83 97
       : isNearCheck;
98
+
84 99
   return hitTestPointAgainstElement({ element, point, threshold, check });
85 100
 };
86 101
 
@@ -151,6 +166,18 @@ const hitTestPointAgainstElement = (args: HitTestArgs): boolean => {
151 166
     case "ellipse":
152 167
       const distance = distanceToBindableElement(args.element, args.point);
153 168
       return args.check(distance, args.threshold);
169
+    case "freedraw": {
170
+      if (
171
+        !args.check(
172
+          distanceToRectangle(args.element, args.point),
173
+          args.threshold,
174
+        )
175
+      ) {
176
+        return false;
177
+      }
178
+
179
+      return hitTestFreeDrawElement(args.element, args.point, args.threshold);
180
+    }
154 181
     case "arrow":
155 182
     case "line":
156 183
     case "draw":
@@ -195,7 +222,10 @@ const isOutsideCheck = (distance: number, threshold: number): boolean => {
195 222
 };
196 223
 
197 224
 const distanceToRectangle = (
198
-  element: ExcalidrawRectangleElement | ExcalidrawTextElement,
225
+  element:
226
+    | ExcalidrawRectangleElement
227
+    | ExcalidrawTextElement
228
+    | ExcalidrawFreeDrawElement,
199 229
   point: Point,
200 230
 ): number => {
201 231
   const [, pointRel, hwidth, hheight] = pointRelativeToElement(element, point);
@@ -267,6 +297,71 @@ const ellipseParamsForTest = (
267 297
   return [pointRel, tangent];
268 298
 };
269 299
 
300
+const hitTestFreeDrawElement = (
301
+  element: ExcalidrawFreeDrawElement,
302
+  point: Point,
303
+  threshold: number,
304
+): boolean => {
305
+  // Check point-distance-to-line-segment for every segment in the
306
+  // element's points (its input points, not its outline points).
307
+  // This is... okay? It's plenty fast, but the GA library may
308
+  // have a faster option.
309
+
310
+  let x: number;
311
+  let y: number;
312
+
313
+  if (element.angle === 0) {
314
+    x = point[0] - element.x;
315
+    y = point[1] - element.y;
316
+  } else {
317
+    // Counter-rotate the point around center before testing
318
+    const [minX, minY, maxX, maxY] = getElementAbsoluteCoords(element);
319
+    const rotatedPoint = rotatePoint(
320
+      point,
321
+      [minX + (maxX - minX) / 2, minY + (maxY - minY) / 2],
322
+      -element.angle,
323
+    );
324
+    x = rotatedPoint[0] - element.x;
325
+    y = rotatedPoint[1] - element.y;
326
+  }
327
+
328
+  let [A, B] = element.points;
329
+  let P: readonly [number, number];
330
+
331
+  // For freedraw dots
332
+  if (element.points.length === 2) {
333
+    return (
334
+      distance2d(A[0], A[1], x, y) < threshold ||
335
+      distance2d(B[0], B[1], x, y) < threshold
336
+    );
337
+  }
338
+
339
+  // For freedraw lines
340
+  for (let i = 1; i < element.points.length - 1; i++) {
341
+    const delta = [B[0] - A[0], B[1] - A[1]];
342
+    const length = Math.hypot(delta[1], delta[0]);
343
+
344
+    const U = [delta[0] / length, delta[1] / length];
345
+    const C = [x - A[0], y - A[1]];
346
+    const d = (C[0] * U[0] + C[1] * U[1]) / Math.hypot(U[1], U[0]);
347
+    P = [A[0] + U[0] * d, A[1] + U[1] * d];
348
+
349
+    const da = distance2d(P[0], P[1], A[0], A[1]);
350
+    const db = distance2d(P[0], P[1], B[0], B[1]);
351
+
352
+    P = db < da && da > length ? B : da < db && db > length ? A : P;
353
+
354
+    if (Math.hypot(y - P[1], x - P[0]) < threshold) {
355
+      return true;
356
+    }
357
+
358
+    A = B;
359
+    B = element.points[i + 1];
360
+  }
361
+
362
+  return false;
363
+};
364
+
270 365
 const hitTestLinear = (args: HitTestArgs): boolean => {
271 366
   const { element, threshold } = args;
272 367
   if (!getShapeForElement(element)) {

+ 17
- 0
src/element/newElement.ts Vedi File

@@ -9,6 +9,7 @@ import {
9 9
   GroupId,
10 10
   VerticalAlign,
11 11
   Arrowhead,
12
+  ExcalidrawFreeDrawElement,
12 13
 } from "../element/types";
13 14
 import { measureText, getFontString } from "../utils";
14 15
 import { randomInteger, randomId } from "../random";
@@ -212,6 +213,22 @@ export const updateTextElement = (
212 213
   });
213 214
 };
214 215
 
216
+export const newFreeDrawElement = (
217
+  opts: {
218
+    type: "freedraw";
219
+    points?: ExcalidrawFreeDrawElement["points"];
220
+    simulatePressure: boolean;
221
+  } & ElementConstructorOpts,
222
+): NonDeleted<ExcalidrawFreeDrawElement> => {
223
+  return {
224
+    ..._newElementBase<ExcalidrawFreeDrawElement>(opts.type, opts),
225
+    points: opts.points || [],
226
+    pressures: [],
227
+    simulatePressure: opts.simulatePressure,
228
+    lastCommittedPoint: null,
229
+  };
230
+};
231
+
215 232
 export const newLinearElement = (
216 233
   opts: {
217 234
     type: ExcalidrawLinearElement["type"];

+ 11
- 3
src/element/resizeElements.ts Vedi File

@@ -18,7 +18,11 @@ import {
18 18
   getCommonBounds,
19 19
   getResizedElementAbsoluteCoords,
20 20
 } from "./bounds";
21
-import { isLinearElement, isTextElement } from "./typeChecks";
21
+import {
22
+  isFreeDrawElement,
23
+  isLinearElement,
24
+  isTextElement,
25
+} from "./typeChecks";
22 26
 import { mutateElement } from "./mutateElement";
23 27
 import { getPerfectElementSize } from "./sizeHelpers";
24 28
 import { measureText, getFontString } from "../utils";
@@ -244,7 +248,7 @@ const rescalePointsInElement = (
244 248
   width: number,
245 249
   height: number,
246 250
 ) =>
247
-  isLinearElement(element)
251
+  isLinearElement(element) || isFreeDrawElement(element)
248 252
     ? {
249 253
         points: rescalePoints(
250 254
           0,
@@ -404,7 +408,7 @@ export const resizeSingleElement = (
404 408
     -stateAtResizeStart.angle,
405 409
   );
406 410
 
407
-  //Get bounds corners rendered on screen
411
+  // Get bounds corners rendered on screen
408 412
   const [esx1, esy1, esx2, esy2] = getResizedElementAbsoluteCoords(
409 413
     element,
410 414
     element.width,
@@ -644,11 +648,14 @@ const resizeMultipleElements = (
644 648
           font = { fontSize: nextFont.size, baseline: nextFont.baseline };
645 649
         }
646 650
         const origCoords = getElementAbsoluteCoords(element);
651
+
647 652
         const rescaledPoints = rescalePointsInElement(element, width, height);
653
+
648 654
         updateBoundElements(element, {
649 655
           newSize: { width, height },
650 656
           simultaneouslyUpdated: elements,
651 657
         });
658
+
652 659
         const finalCoords = getResizedElementAbsoluteCoords(
653 660
           {
654 661
             ...element,
@@ -657,6 +664,7 @@ const resizeMultipleElements = (
657 664
           width,
658 665
           height,
659 666
         );
667
+
660 668
         const { x, y } = getNextXY(element, origCoords, finalCoords);
661 669
         return [...prev, { width, height, x, y, ...rescaledPoints, ...font }];
662 670
       },

+ 3
- 3
src/element/sizeHelpers.ts Vedi File

@@ -1,12 +1,12 @@
1 1
 import { ExcalidrawElement } from "./types";
2 2
 import { mutateElement } from "./mutateElement";
3
-import { isLinearElement } from "./typeChecks";
3
+import { isFreeDrawElement, isLinearElement } from "./typeChecks";
4 4
 import { SHIFT_LOCKING_ANGLE } from "../constants";
5 5
 
6 6
 export const isInvisiblySmallElement = (
7 7
   element: ExcalidrawElement,
8 8
 ): boolean => {
9
-  if (isLinearElement(element)) {
9
+  if (isLinearElement(element) || isFreeDrawElement(element)) {
10 10
     return element.points.length < 2;
11 11
   }
12 12
   return element.width === 0 && element.height === 0;
@@ -26,7 +26,7 @@ export const getPerfectElementSize = (
26 26
   if (
27 27
     elementType === "line" ||
28 28
     elementType === "arrow" ||
29
-    elementType === "draw"
29
+    elementType === "freedraw"
30 30
   ) {
31 31
     const lockedAngle =
32 32
       Math.round(Math.atan(absHeight / absWidth) / SHIFT_LOCKING_ANGLE) *

+ 1
- 1
src/element/transformHandles.ts Vedi File

@@ -225,7 +225,7 @@ export const getTransformHandles = (
225 225
   if (
226 226
     element.type === "arrow" ||
227 227
     element.type === "line" ||
228
-    element.type === "draw"
228
+    element.type === "freedraw"
229 229
   ) {
230 230
     if (element.points.length === 2) {
231 231
       // only check the last point because starting point is always (0,0)

+ 15
- 2
src/element/typeChecks.ts Vedi File

@@ -4,6 +4,7 @@ import {
4 4
   ExcalidrawLinearElement,
5 5
   ExcalidrawBindableElement,
6 6
   ExcalidrawGenericElement,
7
+  ExcalidrawFreeDrawElement,
7 8
 } from "./types";
8 9
 
9 10
 export const isGenericElement = (
@@ -24,6 +25,18 @@ export const isTextElement = (
24 25
   return element != null && element.type === "text";
25 26
 };
26 27
 
28
+export const isFreeDrawElement = (
29
+  element?: ExcalidrawElement | null,
30
+): element is ExcalidrawFreeDrawElement => {
31
+  return element != null && isFreeDrawElementType(element.type);
32
+};
33
+
34
+export const isFreeDrawElementType = (
35
+  elementType: ExcalidrawElement["type"],
36
+): boolean => {
37
+  return elementType === "freedraw";
38
+};
39
+
27 40
 export const isLinearElement = (
28 41
   element?: ExcalidrawElement | null,
29 42
 ): element is ExcalidrawLinearElement => {
@@ -34,7 +47,7 @@ export const isLinearElementType = (
34 47
   elementType: ExcalidrawElement["type"],
35 48
 ): boolean => {
36 49
   return (
37
-    elementType === "arrow" || elementType === "line" || elementType === "draw"
50
+    elementType === "arrow" || elementType === "line" // || elementType === "freedraw"
38 51
   );
39 52
 };
40 53
 
@@ -69,7 +82,7 @@ export const isExcalidrawElement = (element: any): boolean => {
69 82
     element?.type === "rectangle" ||
70 83
     element?.type === "ellipse" ||
71 84
     element?.type === "arrow" ||
72
-    element?.type === "draw" ||
85
+    element?.type === "freedraw" ||
73 86
     element?.type === "line"
74 87
   );
75 88
 };

+ 11
- 1
src/element/types.ts Vedi File

@@ -78,7 +78,8 @@ export type ExcalidrawGenericElement =
78 78
 export type ExcalidrawElement =
79 79
   | ExcalidrawGenericElement
80 80
   | ExcalidrawTextElement
81
-  | ExcalidrawLinearElement;
81
+  | ExcalidrawLinearElement
82
+  | ExcalidrawFreeDrawElement;
82 83
 
83 84
 export type NonDeleted<TElement extends ExcalidrawElement> = TElement & {
84 85
   isDeleted: false;
@@ -121,3 +122,12 @@ export type ExcalidrawLinearElement = _ExcalidrawElementBase &
121 122
     startArrowhead: Arrowhead | null;
122 123
     endArrowhead: Arrowhead | null;
123 124
   }>;
125
+
126
+export type ExcalidrawFreeDrawElement = _ExcalidrawElementBase &
127
+  Readonly<{
128
+    type: "freedraw";
129
+    points: readonly Point[];
130
+    pressures: readonly number[];
131
+    simulatePressure: boolean;
132
+    lastCommittedPoint: Point | null;
133
+  }>;

+ 1
- 1
src/locales/ar-SA.json Vedi File

@@ -152,7 +152,7 @@
152 152
   },
153 153
   "toolBar": {
154 154
     "selection": "تحديد",
155
-    "draw": "الكتابة الحرة",
155
+    "freedraw": "الكتابة الحرة",
156 156
     "rectangle": "مستطيل",
157 157
     "diamond": "مضلع",
158 158
     "ellipse": "دائرة",

+ 1
- 1
src/locales/bg-BG.json Vedi File

@@ -152,7 +152,7 @@
152 152
   },
153 153
   "toolBar": {
154 154
     "selection": "Селекция",
155
-    "draw": "Рисуване",
155
+    "freedraw": "Рисуване",
156 156
     "rectangle": "Правоъгълник",
157 157
     "diamond": "Диамант",
158 158
     "ellipse": "Елипс",

+ 1
- 1
src/locales/ca-ES.json Vedi File

@@ -152,7 +152,7 @@
152 152
   },
153 153
   "toolBar": {
154 154
     "selection": "Selecció",
155
-    "draw": "Dibuix lliure",
155
+    "freedraw": "Dibuix lliure",
156 156
     "rectangle": "Rectangle",
157 157
     "diamond": "Rombe",
158 158
     "ellipse": "El·lipse",

+ 1
- 1
src/locales/de-DE.json Vedi File

@@ -152,7 +152,7 @@
152 152
   },
153 153
   "toolBar": {
154 154
     "selection": "Auswahl",
155
-    "draw": "Freies Zeichnen",
155
+    "freedraw": "Freies Zeichnen",
156 156
     "rectangle": "Rechteck",
157 157
     "diamond": "Raute",
158 158
     "ellipse": "Ellipse",

+ 1
- 1
src/locales/el-GR.json Vedi File

@@ -152,7 +152,7 @@
152 152
   },
153 153
   "toolBar": {
154 154
     "selection": "Επιλογή",
155
-    "draw": "Ελεύθερο σχέδιο",
155
+    "freedraw": "Ελεύθερο σχέδιο",
156 156
     "rectangle": "Ορθογώνιο",
157 157
     "diamond": "Ρόμβος",
158 158
     "ellipse": "Έλλειψη",

+ 4
- 1
src/locales/en.json Vedi File

@@ -20,6 +20,10 @@
20 20
     "background": "Background",
21 21
     "fill": "Fill",
22 22
     "strokeWidth": "Stroke width",
23
+    "strokeShape": "Stroke shape",
24
+    "strokeShape_gel": "Gel pen",
25
+    "strokeShape_fountain": "Fountain pen",
26
+    "strokeShape_brush": "Brush pen",
23 27
     "strokeStyle": "Stroke style",
24 28
     "strokeStyle_solid": "Solid",
25 29
     "strokeStyle_dashed": "Dashed",
@@ -153,7 +157,6 @@
153 157
   },
154 158
   "toolBar": {
155 159
     "selection": "Selection",
156
-    "draw": "Free draw",
157 160
     "rectangle": "Rectangle",
158 161
     "diamond": "Diamond",
159 162
     "ellipse": "Ellipse",

+ 1
- 1
src/locales/es-ES.json Vedi File

@@ -152,7 +152,7 @@
152 152
   },
153 153
   "toolBar": {
154 154
     "selection": "Selección",
155
-    "draw": "Dibujo libre",
155
+    "freedraw": "Dibujo libre",
156 156
     "rectangle": "Rectángulo",
157 157
     "diamond": "Diamante",
158 158
     "ellipse": "Elipse",

+ 1
- 1
src/locales/fa-IR.json Vedi File

@@ -152,7 +152,7 @@
152 152
   },
153 153
   "toolBar": {
154 154
     "selection": "گزینش",
155
-    "draw": "طراحی آزاد",
155
+    "freedraw": "طراحی آزاد",
156 156
     "rectangle": "مستطیل",
157 157
     "diamond": "لوزی",
158 158
     "ellipse": "بیضی",

+ 1
- 1
src/locales/fi-FI.json Vedi File

@@ -152,7 +152,7 @@
152 152
   },
153 153
   "toolBar": {
154 154
     "selection": "Valinta",
155
-    "draw": "Vapaa piirto",
155
+    "freedraw": "Vapaa piirto",
156 156
     "rectangle": "Suorakulmio",
157 157
     "diamond": "Vinoneliö",
158 158
     "ellipse": "Soikio",

+ 1
- 1
src/locales/fr-FR.json Vedi File

@@ -152,7 +152,7 @@
152 152
   },
153 153
   "toolBar": {
154 154
     "selection": "Sélection",
155
-    "draw": "Dessin libre",
155
+    "freedraw": "Dessin libre",
156 156
     "rectangle": "Rectangle",
157 157
     "diamond": "Losange",
158 158
     "ellipse": "Ellipse",

+ 1
- 1
src/locales/he-IL.json Vedi File

@@ -152,7 +152,7 @@
152 152
   },
153 153
   "toolBar": {
154 154
     "selection": "בחירה",
155
-    "draw": "ציור חופשי",
155
+    "freedraw": "ציור חופשי",
156 156
     "rectangle": "מרובע",
157 157
     "diamond": "מעוין",
158 158
     "ellipse": "אליפסה",

+ 1
- 1
src/locales/hi-IN.json Vedi File

@@ -152,7 +152,7 @@
152 152
   },
153 153
   "toolBar": {
154 154
     "selection": "चयन",
155
-    "draw": "मुफ्त ड्रा",
155
+    "freedraw": "मुफ्त ड्रा",
156 156
     "rectangle": "आयात",
157 157
     "diamond": "तिर्यग्वर्ग",
158 158
     "ellipse": "दीर्घवृत्त",

+ 1
- 1
src/locales/hu-HU.json Vedi File

@@ -152,7 +152,7 @@
152 152
   },
153 153
   "toolBar": {
154 154
     "selection": "Kijelölés",
155
-    "draw": "Szabadkézi rajz",
155
+    "freedraw": "Szabadkézi rajz",
156 156
     "rectangle": "Téglalap",
157 157
     "diamond": "Rombusz",
158 158
     "ellipse": "Ellipszis",

+ 1
- 1
src/locales/id-ID.json Vedi File

@@ -152,7 +152,7 @@
152 152
   },
153 153
   "toolBar": {
154 154
     "selection": "Pilihan",
155
-    "draw": "Menggambar bebas",
155
+    "freedraw": "Menggambar bebas",
156 156
     "rectangle": "Persegi",
157 157
     "diamond": "Berlian",
158 158
     "ellipse": "Elips",

+ 1
- 1
src/locales/it-IT.json Vedi File

@@ -152,7 +152,7 @@
152 152
   },
153 153
   "toolBar": {
154 154
     "selection": "Selezione",
155
-    "draw": "Disegno libero",
155
+    "freedraw": "Disegno libero",
156 156
     "rectangle": "Rettangolo",
157 157
     "diamond": "Rombo",
158 158
     "ellipse": "Ellisse",

+ 1
- 1
src/locales/ja-JP.json Vedi File

@@ -152,7 +152,7 @@
152 152
   },
153 153
   "toolBar": {
154 154
     "selection": "選択",
155
-    "draw": "手書き",
155
+    "freedraw": "手書き",
156 156
     "rectangle": "矩形",
157 157
     "diamond": "ひし形",
158 158
     "ellipse": "楕円",

+ 1
- 1
src/locales/kab-KAB.json Vedi File

@@ -152,7 +152,7 @@
152 152
   },
153 153
   "toolBar": {
154 154
     "selection": "Tafrayt",
155
-    "draw": "Unuɣ ilelli",
155
+    "freedraw": "Unuɣ ilelli",
156 156
     "rectangle": "Asrem",
157 157
     "diamond": "Ameɣṛun",
158 158
     "ellipse": "Taglayt",

+ 1
- 1
src/locales/ko-KR.json Vedi File

@@ -152,7 +152,7 @@
152 152
   },
153 153
   "toolBar": {
154 154
     "selection": "선택",
155
-    "draw": "자유롭게 그리기",
155
+    "freedraw": "자유롭게 그리기",
156 156
     "rectangle": "사각형",
157 157
     "diamond": "다이아몬드",
158 158
     "ellipse": "타원",

+ 1
- 1
src/locales/my-MM.json Vedi File

@@ -152,7 +152,7 @@
152 152
   },
153 153
   "toolBar": {
154 154
     "selection": "ရွေးချယ်",
155
-    "draw": "အလွတ်ရေးဆွဲ",
155
+    "freedraw": "အလွတ်ရေးဆွဲ",
156 156
     "rectangle": "စတုဂံ",
157 157
     "diamond": "စိန်",
158 158
     "ellipse": "အဝိုင်း",

+ 1
- 1
src/locales/nb-NO.json Vedi File

@@ -152,7 +152,7 @@
152 152
   },
153 153
   "toolBar": {
154 154
     "selection": "Velg",
155
-    "draw": "Frihåndstegning",
155
+    "freedraw": "Frihåndstegning",
156 156
     "rectangle": "Rektangel",
157 157
     "diamond": "Diamant",
158 158
     "ellipse": "Ellipse",

+ 1
- 1
src/locales/nl-NL.json Vedi File

@@ -152,7 +152,7 @@
152 152
   },
153 153
   "toolBar": {
154 154
     "selection": "Selectie",
155
-    "draw": "Vrij tekenen",
155
+    "freedraw": "Vrij tekenen",
156 156
     "rectangle": "Rechthoek",
157 157
     "diamond": "Ruit",
158 158
     "ellipse": "Ovaal",

+ 1
- 1
src/locales/nn-NO.json Vedi File

@@ -152,7 +152,7 @@
152 152
   },
153 153
   "toolBar": {
154 154
     "selection": "Vel",
155
-    "draw": "Frihandsteikning",
155
+    "freedraw": "Frihandsteikning",
156 156
     "rectangle": "Rektangel",
157 157
     "diamond": "Diamant",
158 158
     "ellipse": "Ellipse",

+ 1
- 1
src/locales/oc-FR.json Vedi File

@@ -152,7 +152,7 @@
152 152
   },
153 153
   "toolBar": {
154 154
     "selection": "Seleccion",
155
-    "draw": "Dessenh liure",
155
+    "freedraw": "Dessenh liure",
156 156
     "rectangle": "Rectangle",
157 157
     "diamond": "Lausange",
158 158
     "ellipse": "Ellipsa",

+ 1
- 1
src/locales/pa-IN.json Vedi File

@@ -152,7 +152,7 @@
152 152
   },
153 153
   "toolBar": {
154 154
     "selection": "ਚੋਣਕਾਰ",
155
-    "draw": "ਖੁੱਲ੍ਹੀ ਵਾਹੀ",
155
+    "freedraw": "ਖੁੱਲ੍ਹੀ ਵਾਹੀ",
156 156
     "rectangle": "ਆਇਤ",
157 157
     "diamond": "ਹੀਰਾ",
158 158
     "ellipse": "ਅੰਡਾਕਾਰ",

+ 1
- 1
src/locales/pl-PL.json Vedi File

@@ -152,7 +152,7 @@
152 152
   },
153 153
   "toolBar": {
154 154
     "selection": "Zaznaczenie",
155
-    "draw": "Swobodne rysowanie",
155
+    "freedraw": "Swobodne rysowanie",
156 156
     "rectangle": "Prostokąt",
157 157
     "diamond": "Romb",
158 158
     "ellipse": "Elipsa",

+ 1
- 1
src/locales/pt-BR.json Vedi File

@@ -152,7 +152,7 @@
152 152
   },
153 153
   "toolBar": {
154 154
     "selection": "Seleção",
155
-    "draw": "Desenho livre",
155
+    "freedraw": "Desenho livre",
156 156
     "rectangle": "Retângulo",
157 157
     "diamond": "Losango",
158 158
     "ellipse": "Elipse",

+ 1
- 1
src/locales/pt-PT.json Vedi File

@@ -152,7 +152,7 @@
152 152
   },
153 153
   "toolBar": {
154 154
     "selection": "Seleção",
155
-    "draw": "Desenho livre",
155
+    "freedraw": "Desenho livre",
156 156
     "rectangle": "Retângulo",
157 157
     "diamond": "Losango",
158 158
     "ellipse": "Elipse",

+ 1
- 1
src/locales/ro-RO.json Vedi File

@@ -152,7 +152,7 @@
152 152
   },
153 153
   "toolBar": {
154 154
     "selection": "Selecție",
155
-    "draw": "Desenare liberă",
155
+    "freedraw": "Desenare liberă",
156 156
     "rectangle": "Dreptunghi",
157 157
     "diamond": "Romb",
158 158
     "ellipse": "Elipsă",

+ 1
- 1
src/locales/ru-RU.json Vedi File

@@ -152,7 +152,7 @@
152 152
   },
153 153
   "toolBar": {
154 154
     "selection": "Выделение области",
155
-    "draw": "Свободное рисование",
155
+    "freedraw": "Свободное рисование",
156 156
     "rectangle": "Прямоугольник",
157 157
     "diamond": "Ромб",
158 158
     "ellipse": "Эллипс",

+ 1
- 1
src/locales/sk-SK.json Vedi File

@@ -152,7 +152,7 @@
152 152
   },
153 153
   "toolBar": {
154 154
     "selection": "Výber",
155
-    "draw": "Voľné kreslenie",
155
+    "freedraw": "Voľné kreslenie",
156 156
     "rectangle": "Obdĺžnik",
157 157
     "diamond": "Diamant",
158 158
     "ellipse": "Elipsa",

+ 1
- 1
src/locales/sv-SE.json Vedi File

@@ -152,7 +152,7 @@
152 152
   },
153 153
   "toolBar": {
154 154
     "selection": "Markering",
155
-    "draw": "Frihand",
155
+    "freedraw": "Frihand",
156 156
     "rectangle": "Rektangel",
157 157
     "diamond": "Diamant",
158 158
     "ellipse": "Ellips",

+ 1
- 1
src/locales/tr-TR.json Vedi File

@@ -152,7 +152,7 @@
152 152
   },
153 153
   "toolBar": {
154 154
     "selection": "Seçme",
155
-    "draw": "Serbest çizim",
155
+    "freedraw": "Serbest çizim",
156 156
     "rectangle": "Dikdörtgen",
157 157
     "diamond": "Elmas",
158 158
     "ellipse": "Elips",

+ 1
- 1
src/locales/uk-UA.json Vedi File

@@ -152,7 +152,7 @@
152 152
   },
153 153
   "toolBar": {
154 154
     "selection": "Виділення",
155
-    "draw": "Вільне креслення",
155
+    "freedraw": "Вільне креслення",
156 156
     "rectangle": "Прямокутник",
157 157
     "diamond": "Ромб",
158 158
     "ellipse": "Еліпс",

+ 1
- 1
src/locales/zh-CN.json Vedi File

@@ -152,7 +152,7 @@
152 152
   },
153 153
   "toolBar": {
154 154
     "selection": "选择",
155
-    "draw": "自由书写",
155
+    "freedraw": "自由书写",
156 156
     "rectangle": "矩形",
157 157
     "diamond": "菱形",
158 158
     "ellipse": "椭圆",

+ 1
- 1
src/locales/zh-TW.json Vedi File

@@ -152,7 +152,7 @@
152 152
   },
153 153
   "toolBar": {
154 154
     "selection": "選取",
155
-    "draw": "繪圖",
155
+    "freedraw": "繪圖",
156 156
     "rectangle": "長方形",
157 157
     "diamond": "菱形",
158 158
     "ellipse": "橢圓",

+ 1
- 0
src/math.ts Vedi File

@@ -249,6 +249,7 @@ const doSegmentsIntersect = (p1: Point, q1: Point, p2: Point, q2: Point) => {
249 249
   return false;
250 250
 };
251 251
 
252
+// TODO: Rounding this point causes some shake when free drawing
252 253
 export const getGridPoint = (
253 254
   x: number,
254 255
   y: number,

+ 1
- 0
src/points.ts Vedi File

@@ -8,6 +8,7 @@ export const getSizeFromPoints = (points: readonly Point[]) => {
8 8
     height: Math.max(...ys) - Math.min(...ys),
9 9
   };
10 10
 };
11
+
11 12
 export const rescalePoints = (
12 13
   dimension: 0 | 1,
13 14
   nextDimensionSize: number,

+ 180
- 28
src/renderer/renderElement.ts Vedi File

@@ -4,8 +4,13 @@ import {
4 4
   ExcalidrawTextElement,
5 5
   Arrowhead,
6 6
   NonDeletedExcalidrawElement,
7
+  ExcalidrawFreeDrawElement,
7 8
 } from "../element/types";
8
-import { isTextElement, isLinearElement } from "../element/typeChecks";
9
+import {
10
+  isTextElement,
11
+  isLinearElement,
12
+  isFreeDrawElement,
13
+} from "../element/typeChecks";
9 14
 import {
10 15
   getDiamondPoints,
11 16
   getElementAbsoluteCoords,
@@ -27,14 +32,17 @@ import { isPathALoop } from "../math";
27 32
 import rough from "roughjs/bin/rough";
28 33
 import { Zoom } from "../types";
29 34
 import { getDefaultAppState } from "../appState";
35
+import getFreeDrawShape from "perfect-freehand";
30 36
 
31 37
 const defaultAppState = getDefaultAppState();
32 38
 
33
-const CANVAS_PADDING = 20;
34
-
35 39
 const getDashArrayDashed = (strokeWidth: number) => [8, 8 + strokeWidth];
40
+
36 41
 const getDashArrayDotted = (strokeWidth: number) => [1.5, 6 + strokeWidth];
37 42
 
43
+const getCanvasPadding = (element: ExcalidrawElement) =>
44
+  element.type === "freedraw" ? element.strokeWidth * 12 : 20;
45
+
38 46
 export interface ExcalidrawElementWithCanvas {
39 47
   element: ExcalidrawElement | ExcalidrawTextElement;
40 48
   canvas: HTMLCanvasElement;
@@ -49,18 +57,25 @@ const generateElementCanvas = (
49 57
 ): ExcalidrawElementWithCanvas => {
50 58
   const canvas = document.createElement("canvas");
51 59
   const context = canvas.getContext("2d")!;
60
+  const padding = getCanvasPadding(element);
52 61
 
53 62
   let canvasOffsetX = 0;
54 63
   let canvasOffsetY = 0;
55 64
 
56
-  if (isLinearElement(element)) {
57
-    const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
65
+  if (isLinearElement(element) || isFreeDrawElement(element)) {
66
+    let [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
67
+
68
+    x1 = Math.floor(x1);
69
+    x2 = Math.ceil(x2);
70
+    y1 = Math.floor(y1);
71
+    y2 = Math.ceil(y2);
72
+
58 73
     canvas.width =
59 74
       distance(x1, x2) * window.devicePixelRatio * zoom.value +
60
-      CANVAS_PADDING * zoom.value * 2;
75
+      padding * zoom.value * 2;
61 76
     canvas.height =
62 77
       distance(y1, y2) * window.devicePixelRatio * zoom.value +
63
-      CANVAS_PADDING * zoom.value * 2;
78
+      padding * zoom.value * 2;
64 79
 
65 80
     canvasOffsetX =
66 81
       element.x > x1
@@ -80,13 +95,13 @@ const generateElementCanvas = (
80 95
   } else {
81 96
     canvas.width =
82 97
       element.width * window.devicePixelRatio * zoom.value +
83
-      CANVAS_PADDING * zoom.value * 2;
98
+      padding * zoom.value * 2;
84 99
     canvas.height =
85 100
       element.height * window.devicePixelRatio * zoom.value +
86
-      CANVAS_PADDING * zoom.value * 2;
101
+      padding * zoom.value * 2;
87 102
   }
88 103
 
89
-  context.translate(CANVAS_PADDING * zoom.value, CANVAS_PADDING * zoom.value);
104
+  context.translate(padding * zoom.value, padding * zoom.value);
90 105
 
91 106
   context.scale(
92 107
     window.devicePixelRatio * zoom.value,
@@ -94,11 +109,10 @@ const generateElementCanvas = (
94 109
   );
95 110
 
96 111
   const rc = rough.canvas(canvas);
112
+
97 113
   drawElementOnCanvas(element, rc, context);
98
-  context.translate(
99
-    -(CANVAS_PADDING * zoom.value),
100
-    -(CANVAS_PADDING * zoom.value),
101
-  );
114
+
115
+  context.translate(-(padding * zoom.value), -(padding * zoom.value));
102 116
   context.scale(
103 117
     1 / (window.devicePixelRatio * zoom.value),
104 118
     1 / (window.devicePixelRatio * zoom.value),
@@ -138,6 +152,19 @@ const drawElementOnCanvas = (
138 152
       });
139 153
       break;
140 154
     }
155
+    case "freedraw": {
156
+      // Draw directly to canvas
157
+      context.save();
158
+      context.fillStyle = element.strokeColor;
159
+
160
+      const path = getFreeDrawPath2D(element) as Path2D;
161
+
162
+      context.fillStyle = element.strokeColor;
163
+      context.fill(path);
164
+
165
+      context.restore();
166
+      break;
167
+    }
141 168
     default: {
142 169
       if (isTextElement(element)) {
143 170
         const rtl = isRTL(element.text);
@@ -243,10 +270,8 @@ export const generateRoughOptions = (element: ExcalidrawElement): Options => {
243 270
       }
244 271
       return options;
245 272
     }
246
-    case "line":
247
-    case "draw": {
248
-      // If shape is a line and is a closed shape,
249
-      // fill the shape if a color is set.
273
+    case "draw":
274
+    case "line": {
250 275
       if (isPathALoop(element.points)) {
251 276
         options.fillStyle = element.fillStyle;
252 277
         options.fill =
@@ -256,6 +281,7 @@ export const generateRoughOptions = (element: ExcalidrawElement): Options => {
256 281
       }
257 282
       return options;
258 283
     }
284
+    case "freedraw":
259 285
     case "arrow":
260 286
       return options;
261 287
     default: {
@@ -264,11 +290,17 @@ export const generateRoughOptions = (element: ExcalidrawElement): Options => {
264 290
   }
265 291
 };
266 292
 
293
+/**
294
+ * Generates the element's shape and puts it into the cache.
295
+ * @param element
296
+ * @param generator
297
+ */
267 298
 const generateElementShape = (
268 299
   element: NonDeletedExcalidrawElement,
269 300
   generator: RoughGenerator,
270 301
 ) => {
271 302
   let shape = shapeCache.get(element) || null;
303
+
272 304
   if (!shape) {
273 305
     elementWithCanvasCache.delete(element);
274 306
 
@@ -327,8 +359,8 @@ const generateElementShape = (
327 359
           generateRoughOptions(element),
328 360
         );
329 361
         break;
330
-      case "line":
331 362
       case "draw":
363
+      case "line":
332 364
       case "arrow": {
333 365
         const options = generateRoughOptions(element);
334 366
 
@@ -380,15 +412,18 @@ const generateElementShape = (
380 412
                   ...options,
381 413
                   fill: element.strokeColor,
382 414
                   fillStyle: "solid",
415
+                  stroke: "none",
383 416
                 }),
384 417
               ];
385 418
             }
386 419
 
387 420
             // Arrow arrowheads
388 421
             const [x2, y2, x3, y3, x4, y4] = arrowheadPoints;
422
+
389 423
             if (element.strokeStyle === "dotted") {
390 424
               // for dotted arrows caps, reduce gap to make it more legible
391
-              options.strokeLineDash = [3, 4];
425
+              const dash = getDashArrayDotted(element.strokeWidth - 1);
426
+              options.strokeLineDash = [dash[0], dash[1] - 1];
392 427
             } else {
393 428
               // for solid/dashed, keep solid arrow cap
394 429
               delete options.strokeLineDash;
@@ -423,6 +458,12 @@ const generateElementShape = (
423 458
             shape.push(...shapes);
424 459
           }
425 460
         }
461
+
462
+        break;
463
+      }
464
+      case "freedraw": {
465
+        generateFreeDrawShape(element);
466
+        shape = [];
426 467
         break;
427 468
       }
428 469
       case "text": {
@@ -447,7 +488,9 @@ const generateElementWithCanvas = (
447 488
     !sceneState?.shouldCacheIgnoreZoom;
448 489
   if (!prevElementWithCanvas || shouldRegenerateBecauseZoom) {
449 490
     const elementWithCanvas = generateElementCanvas(element, zoom);
491
+
450 492
     elementWithCanvasCache.set(element, elementWithCanvas);
493
+
451 494
     return elementWithCanvas;
452 495
   }
453 496
   return prevElementWithCanvas;
@@ -460,20 +503,29 @@ const drawElementFromCanvas = (
460 503
   sceneState: SceneState,
461 504
 ) => {
462 505
   const element = elementWithCanvas.element;
463
-  const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
506
+  const padding = getCanvasPadding(element);
507
+  let [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
508
+
509
+  // Free draw elements will otherwise "shuffle" as the min x and y change
510
+  if (isFreeDrawElement(element)) {
511
+    x1 = Math.floor(x1);
512
+    x2 = Math.ceil(x2);
513
+    y1 = Math.floor(y1);
514
+    y2 = Math.ceil(y2);
515
+  }
516
+
464 517
   const cx = ((x1 + x2) / 2 + sceneState.scrollX) * window.devicePixelRatio;
465 518
   const cy = ((y1 + y2) / 2 + sceneState.scrollY) * window.devicePixelRatio;
466 519
   context.scale(1 / window.devicePixelRatio, 1 / window.devicePixelRatio);
467 520
   context.translate(cx, cy);
468 521
   context.rotate(element.angle);
522
+
469 523
   context.drawImage(
470 524
     elementWithCanvas.canvas!,
471 525
     (-(x2 - x1) / 2) * window.devicePixelRatio -
472
-      (CANVAS_PADDING * elementWithCanvas.canvasZoom) /
473
-        elementWithCanvas.canvasZoom,
526
+      (padding * elementWithCanvas.canvasZoom) / elementWithCanvas.canvasZoom,
474 527
     (-(y2 - y1) / 2) * window.devicePixelRatio -
475
-      (CANVAS_PADDING * elementWithCanvas.canvasZoom) /
476
-        elementWithCanvas.canvasZoom,
528
+      (padding * elementWithCanvas.canvasZoom) / elementWithCanvas.canvasZoom,
477 529
     elementWithCanvas.canvas!.width / elementWithCanvas.canvasZoom,
478 530
     elementWithCanvas.canvas!.height / elementWithCanvas.canvasZoom,
479 531
   );
@@ -508,11 +560,37 @@ export const renderElement = (
508 560
       );
509 561
       break;
510 562
     }
563
+    case "freedraw": {
564
+      generateElementShape(element, generator);
565
+
566
+      if (renderOptimizations) {
567
+        const elementWithCanvas = generateElementWithCanvas(
568
+          element,
569
+          sceneState,
570
+        );
571
+        drawElementFromCanvas(elementWithCanvas, rc, context, sceneState);
572
+      } else {
573
+        const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
574
+        const cx = (x1 + x2) / 2 + sceneState.scrollX;
575
+        const cy = (y1 + y2) / 2 + sceneState.scrollY;
576
+        const shiftX = (x2 - x1) / 2 - (element.x - x1);
577
+        const shiftY = (y2 - y1) / 2 - (element.y - y1);
578
+        context.translate(cx, cy);
579
+        context.rotate(element.angle);
580
+        context.translate(-shiftX, -shiftY);
581
+        drawElementOnCanvas(element, rc, context);
582
+        context.translate(shiftX, shiftY);
583
+        context.rotate(-element.angle);
584
+        context.translate(-cx, -cy);
585
+      }
586
+
587
+      break;
588
+    }
511 589
     case "rectangle":
512 590
     case "diamond":
513 591
     case "ellipse":
514
-    case "line":
515 592
     case "draw":
593
+    case "line":
516 594
     case "arrow":
517 595
     case "text": {
518 596
       generateElementShape(element, generator);
@@ -583,8 +661,8 @@ export const renderElementToSvg = (
583 661
       svgRoot.appendChild(node);
584 662
       break;
585 663
     }
586
-    case "line":
587 664
     case "draw":
665
+    case "line":
588 666
     case "arrow": {
589 667
       generateElementShape(element, generator);
590 668
       const group = svgRoot.ownerDocument!.createElementNS(SVG_NS, "g");
@@ -604,7 +682,7 @@ export const renderElementToSvg = (
604 682
           }) rotate(${degree} ${cx} ${cy})`,
605 683
         );
606 684
         if (
607
-          (element.type === "line" || element.type === "draw") &&
685
+          element.type === "line" &&
608 686
           isPathALoop(element.points) &&
609 687
           element.backgroundColor !== "transparent"
610 688
         ) {
@@ -615,6 +693,28 @@ export const renderElementToSvg = (
615 693
       svgRoot.appendChild(group);
616 694
       break;
617 695
     }
696
+    case "freedraw": {
697
+      generateFreeDrawShape(element);
698
+      const opacity = element.opacity / 100;
699
+      const node = svgRoot.ownerDocument!.createElementNS(SVG_NS, "g");
700
+      if (opacity !== 1) {
701
+        node.setAttribute("stroke-opacity", `${opacity}`);
702
+        node.setAttribute("fill-opacity", `${opacity}`);
703
+      }
704
+      node.setAttribute(
705
+        "transform",
706
+        `translate(${offsetX || 0} ${
707
+          offsetY || 0
708
+        }) rotate(${degree} ${cx} ${cy})`,
709
+      );
710
+      const path = svgRoot.ownerDocument!.createElementNS(SVG_NS, "path");
711
+      node.setAttribute("stroke", "none");
712
+      node.setAttribute("fill", element.strokeStyle);
713
+      path.setAttribute("d", getFreeDrawSvgPath(element));
714
+      node.appendChild(path);
715
+      svgRoot.appendChild(node);
716
+      break;
717
+    }
618 718
     default: {
619 719
       if (isTextElement(element)) {
620 720
         const opacity = element.opacity / 100;
@@ -666,3 +766,55 @@ export const renderElementToSvg = (
666 766
     }
667 767
   }
668 768
 };
769
+
770
+export const pathsCache = new WeakMap<ExcalidrawFreeDrawElement, Path2D>([]);
771
+
772
+export function generateFreeDrawShape(element: ExcalidrawFreeDrawElement) {
773
+  const svgPathData = getFreeDrawSvgPath(element);
774
+  const path = new Path2D(svgPathData);
775
+  pathsCache.set(element, path);
776
+  return path;
777
+}
778
+
779
+export function getFreeDrawPath2D(element: ExcalidrawFreeDrawElement) {
780
+  return pathsCache.get(element);
781
+}
782
+
783
+export function getFreeDrawSvgPath(element: ExcalidrawFreeDrawElement) {
784
+  const inputPoints = element.simulatePressure
785
+    ? element.points
786
+    : element.points.length
787
+    ? element.points.map(([x, y], i) => [x, y, element.pressures[i]])
788
+    : [[0, 0, 0]];
789
+
790
+  // Consider changing the options for simulated pressure vs real pressure
791
+  const options = {
792
+    simulatePressure: element.simulatePressure,
793
+    size: element.strokeWidth * 6,
794
+    thinning: 0.5,
795
+    smoothing: 0.5,
796
+    streamline: 0.5,
797
+    easing: (t: number) => t * (2 - t),
798
+    last: true,
799
+  };
800
+
801
+  const points = getFreeDrawShape(inputPoints as number[][], options);
802
+  const d: (string | number)[] = [];
803
+
804
+  let [p0, p1] = points;
805
+
806
+  d.push("M", p0[0], p0[1], "Q");
807
+
808
+  for (let i = 0; i < points.length; i++) {
809
+    d.push(p0[0], p0[1], (p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2);
810
+    p0 = p1;
811
+    p1 = points[i];
812
+  }
813
+
814
+  p1 = points[0];
815
+  d.push(p0[0], p0[1], (p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2);
816
+
817
+  d.push("Z");
818
+
819
+  return d.join(" ");
820
+}

+ 2
- 1
src/renderer/renderScene.ts Vedi File

@@ -201,11 +201,12 @@ export const renderScene = (
201 201
     renderGrid?: boolean;
202 202
   } = {},
203 203
 ) => {
204
-  if (!canvas) {
204
+  if (canvas === null) {
205 205
     return { atLeastOneVisibleElement: false };
206 206
   }
207 207
 
208 208
   const context = canvas.getContext("2d")!;
209
+
209 210
   context.scale(scale, scale);
210 211
 
211 212
   // When doing calculations based on canvas width we should used normalized one

+ 8
- 5
src/scene/comparisons.ts Vedi File

@@ -9,23 +9,26 @@ export const hasBackground = (type: string) =>
9 9
   type === "rectangle" ||
10 10
   type === "ellipse" ||
11 11
   type === "diamond" ||
12
-  type === "draw" ||
13 12
   type === "line";
14 13
 
15
-export const hasStroke = (type: string) =>
14
+export const hasStrokeWidth = (type: string) =>
16 15
   type === "rectangle" ||
17 16
   type === "ellipse" ||
18 17
   type === "diamond" ||
18
+  type === "freedraw" ||
19 19
   type === "arrow" ||
20
-  type === "draw" ||
21 20
   type === "line";
22 21
 
23
-export const canChangeSharpness = (type: string) =>
22
+export const hasStrokeStyle = (type: string) =>
24 23
   type === "rectangle" ||
24
+  type === "ellipse" ||
25
+  type === "diamond" ||
25 26
   type === "arrow" ||
26
-  type === "draw" ||
27 27
   type === "line";
28 28
 
29
+export const canChangeSharpness = (type: string) =>
30
+  type === "rectangle" || type === "arrow" || type === "line";
31
+
29 32
 export const hasText = (type: string) => type === "text";
30 33
 
31 34
 export const canHaveArrowheads = (type: string) => type === "arrow";

+ 2
- 1
src/scene/index.ts Vedi File

@@ -9,7 +9,8 @@ export {
9 9
 export { calculateScrollCenter } from "./scroll";
10 10
 export {
11 11
   hasBackground,
12
-  hasStroke,
12
+  hasStrokeWidth,
13
+  hasStrokeStyle,
13 14
   canHaveArrowheads,
14 15
   canChangeSharpness,
15 16
   getElementAtPosition,

+ 1
- 1
src/shapes.tsx Vedi File

@@ -80,7 +80,7 @@ export const SHAPES = [
80 80
         ></path>
81 81
       </svg>
82 82
     ),
83
-    value: "draw",
83
+    value: "freedraw",
84 84
     key: KEYS.X,
85 85
   },
86 86
   {

+ 91
- 55
src/tests/__snapshots__/regressionTests.test.tsx.snap Vedi File

@@ -6280,7 +6280,7 @@ Object {
6280 6280
   "editingGroupId": null,
6281 6281
   "editingLinearElement": null,
6282 6282
   "elementLocked": false,
6283
-  "elementType": "draw",
6283
+  "elementType": "freedraw",
6284 6284
   "errorMessage": null,
6285 6285
   "exportBackground": true,
6286 6286
   "exportEmbedScene": false,
@@ -6596,8 +6596,6 @@ Object {
6596 6596
   "angle": 0,
6597 6597
   "backgroundColor": "transparent",
6598 6598
   "boundElementIds": null,
6599
-  "endArrowhead": null,
6600
-  "endBinding": null,
6601 6599
   "fillStyle": "hachure",
6602 6600
   "groupIds": Array [],
6603 6601
   "height": 10,
@@ -6614,18 +6612,26 @@ Object {
6614 6612
       50,
6615 6613
       10,
6616 6614
     ],
6615
+    Array [
6616
+      50,
6617
+      10,
6618
+    ],
6619
+  ],
6620
+  "pressures": Array [
6621
+    0,
6622
+    0,
6623
+    0,
6617 6624
   ],
6618 6625
   "roughness": 1,
6619 6626
   "seed": 941653321,
6620
-  "startArrowhead": null,
6621
-  "startBinding": null,
6627
+  "simulatePressure": false,
6622 6628
   "strokeColor": "#000000",
6623 6629
   "strokeSharpness": "round",
6624 6630
   "strokeStyle": "solid",
6625 6631
   "strokeWidth": 1,
6626
-  "type": "draw",
6627
-  "version": 3,
6628
-  "versionNonce": 1402203177,
6632
+  "type": "freedraw",
6633
+  "version": 4,
6634
+  "versionNonce": 1359939303,
6629 6635
   "width": 50,
6630 6636
   "x": 550,
6631 6637
   "y": -10,
@@ -8246,8 +8252,6 @@ Object {
8246 8252
           "angle": 0,
8247 8253
           "backgroundColor": "transparent",
8248 8254
           "boundElementIds": null,
8249
-          "endArrowhead": null,
8250
-          "endBinding": null,
8251 8255
           "fillStyle": "hachure",
8252 8256
           "groupIds": Array [],
8253 8257
           "height": 10,
@@ -8264,18 +8268,26 @@ Object {
8264 8268
               50,
8265 8269
               10,
8266 8270
             ],
8271
+            Array [
8272
+              50,
8273
+              10,
8274
+            ],
8275
+          ],
8276
+          "pressures": Array [
8277
+            0,
8278
+            0,
8279
+            0,
8267 8280
           ],
8268 8281
           "roughness": 1,
8269 8282
           "seed": 941653321,
8270
-          "startArrowhead": null,
8271
-          "startBinding": null,
8283
+          "simulatePressure": false,
8272 8284
           "strokeColor": "#000000",
8273 8285
           "strokeSharpness": "round",
8274 8286
           "strokeStyle": "solid",
8275 8287
           "strokeWidth": 1,
8276
-          "type": "draw",
8277
-          "version": 3,
8278
-          "versionNonce": 1402203177,
8288
+          "type": "freedraw",
8289
+          "version": 4,
8290
+          "versionNonce": 1359939303,
8279 8291
           "width": 50,
8280 8292
           "x": 550,
8281 8293
           "y": -10,
@@ -10355,7 +10367,7 @@ exports[`regression tests key 6 selects line tool: [end of test] number of eleme
10355 10367
 
10356 10368
 exports[`regression tests key 6 selects line tool: [end of test] number of renders 1`] = `8`;
10357 10369
 
10358
-exports[`regression tests key 7 selects draw tool: [end of test] appState 1`] = `
10370
+exports[`regression tests key 7 selects freedraw tool: [end of test] appState 1`] = `
10359 10371
 Object {
10360 10372
   "collaborators": Map {},
10361 10373
   "currentChartType": "bar",
@@ -10379,7 +10391,7 @@ Object {
10379 10391
   "editingGroupId": null,
10380 10392
   "editingLinearElement": null,
10381 10393
   "elementLocked": false,
10382
-  "elementType": "draw",
10394
+  "elementType": "freedraw",
10383 10395
   "errorMessage": null,
10384 10396
   "exportBackground": true,
10385 10397
   "exportEmbedScene": false,
@@ -10434,13 +10446,11 @@ Object {
10434 10446
 }
10435 10447
 `;
10436 10448
 
10437
-exports[`regression tests key 7 selects draw tool: [end of test] element 0 1`] = `
10449
+exports[`regression tests key 7 selects freedraw tool: [end of test] element 0 1`] = `
10438 10450
 Object {
10439 10451
   "angle": 0,
10440 10452
   "backgroundColor": "transparent",
10441 10453
   "boundElementIds": null,
10442
-  "endArrowhead": null,
10443
-  "endBinding": null,
10444 10454
   "fillStyle": "hachure",
10445 10455
   "groupIds": Array [],
10446 10456
   "height": 10,
@@ -10457,25 +10467,33 @@ Object {
10457 10467
       10,
10458 10468
       10,
10459 10469
     ],
10470
+    Array [
10471
+      10,
10472
+      10,
10473
+    ],
10474
+  ],
10475
+  "pressures": Array [
10476
+    0,
10477
+    0,
10478
+    0,
10460 10479
   ],
10461 10480
   "roughness": 1,
10462 10481
   "seed": 337897,
10463
-  "startArrowhead": null,
10464
-  "startBinding": null,
10482
+  "simulatePressure": false,
10465 10483
   "strokeColor": "#000000",
10466 10484
   "strokeSharpness": "round",
10467 10485
   "strokeStyle": "solid",
10468 10486
   "strokeWidth": 1,
10469
-  "type": "draw",
10470
-  "version": 3,
10471
-  "versionNonce": 449462985,
10487
+  "type": "freedraw",
10488
+  "version": 4,
10489
+  "versionNonce": 453191,
10472 10490
   "width": 10,
10473 10491
   "x": 10,
10474 10492
   "y": 10,
10475 10493
 }
10476 10494
 `;
10477 10495
 
10478
-exports[`regression tests key 7 selects draw tool: [end of test] history 1`] = `
10496
+exports[`regression tests key 7 selects freedraw tool: [end of test] history 1`] = `
10479 10497
 Object {
10480 10498
   "recording": false,
10481 10499
   "redoStack": Array [],
@@ -10505,8 +10523,6 @@ Object {
10505 10523
           "angle": 0,
10506 10524
           "backgroundColor": "transparent",
10507 10525
           "boundElementIds": null,
10508
-          "endArrowhead": null,
10509
-          "endBinding": null,
10510 10526
           "fillStyle": "hachure",
10511 10527
           "groupIds": Array [],
10512 10528
           "height": 10,
@@ -10523,18 +10539,26 @@ Object {
10523 10539
               10,
10524 10540
               10,
10525 10541
             ],
10542
+            Array [
10543
+              10,
10544
+              10,
10545
+            ],
10546
+          ],
10547
+          "pressures": Array [
10548
+            0,
10549
+            0,
10550
+            0,
10526 10551
           ],
10527 10552
           "roughness": 1,
10528 10553
           "seed": 337897,
10529
-          "startArrowhead": null,
10530
-          "startBinding": null,
10554
+          "simulatePressure": false,
10531 10555
           "strokeColor": "#000000",
10532 10556
           "strokeSharpness": "round",
10533 10557
           "strokeStyle": "solid",
10534 10558
           "strokeWidth": 1,
10535
-          "type": "draw",
10536
-          "version": 3,
10537
-          "versionNonce": 449462985,
10559
+          "type": "freedraw",
10560
+          "version": 4,
10561
+          "versionNonce": 453191,
10538 10562
           "width": 10,
10539 10563
           "x": 10,
10540 10564
           "y": 10,
@@ -10545,9 +10569,9 @@ Object {
10545 10569
 }
10546 10570
 `;
10547 10571
 
10548
-exports[`regression tests key 7 selects draw tool: [end of test] number of elements 1`] = `1`;
10572
+exports[`regression tests key 7 selects freedraw tool: [end of test] number of elements 1`] = `1`;
10549 10573
 
10550
-exports[`regression tests key 7 selects draw tool: [end of test] number of renders 1`] = `8`;
10574
+exports[`regression tests key 7 selects freedraw tool: [end of test] number of renders 1`] = `8`;
10551 10575
 
10552 10576
 exports[`regression tests key a selects arrow tool: [end of test] appState 1`] = `
10553 10577
 Object {
@@ -11429,7 +11453,7 @@ exports[`regression tests key r selects rectangle tool: [end of test] number of
11429 11453
 
11430 11454
 exports[`regression tests key r selects rectangle tool: [end of test] number of renders 1`] = `8`;
11431 11455
 
11432
-exports[`regression tests key x selects draw tool: [end of test] appState 1`] = `
11456
+exports[`regression tests key x selects freedraw tool: [end of test] appState 1`] = `
11433 11457
 Object {
11434 11458
   "collaborators": Map {},
11435 11459
   "currentChartType": "bar",
@@ -11453,7 +11477,7 @@ Object {
11453 11477
   "editingGroupId": null,
11454 11478
   "editingLinearElement": null,
11455 11479
   "elementLocked": false,
11456
-  "elementType": "draw",
11480
+  "elementType": "freedraw",
11457 11481
   "errorMessage": null,
11458 11482
   "exportBackground": true,
11459 11483
   "exportEmbedScene": false,
@@ -11508,13 +11532,11 @@ Object {
11508 11532
 }
11509 11533
 `;
11510 11534
 
11511
-exports[`regression tests key x selects draw tool: [end of test] element 0 1`] = `
11535
+exports[`regression tests key x selects freedraw tool: [end of test] element 0 1`] = `
11512 11536
 Object {
11513 11537
   "angle": 0,
11514 11538
   "backgroundColor": "transparent",
11515 11539
   "boundElementIds": null,
11516
-  "endArrowhead": null,
11517
-  "endBinding": null,
11518 11540
   "fillStyle": "hachure",
11519 11541
   "groupIds": Array [],
11520 11542
   "height": 10,
@@ -11531,25 +11553,33 @@ Object {
11531 11553
       10,
11532 11554
       10,
11533 11555
     ],
11556
+    Array [
11557
+      10,
11558
+      10,
11559
+    ],
11560
+  ],
11561
+  "pressures": Array [
11562
+    0,
11563
+    0,
11564
+    0,
11534 11565
   ],
11535 11566
   "roughness": 1,
11536 11567
   "seed": 337897,
11537
-  "startArrowhead": null,
11538
-  "startBinding": null,
11568
+  "simulatePressure": false,
11539 11569
   "strokeColor": "#000000",
11540 11570
   "strokeSharpness": "round",
11541 11571
   "strokeStyle": "solid",
11542 11572
   "strokeWidth": 1,
11543
-  "type": "draw",
11544
-  "version": 3,
11545
-  "versionNonce": 449462985,
11573
+  "type": "freedraw",
11574
+  "version": 4,
11575
+  "versionNonce": 453191,
11546 11576
   "width": 10,
11547 11577
   "x": 10,
11548 11578
   "y": 10,
11549 11579
 }
11550 11580
 `;
11551 11581
 
11552
-exports[`regression tests key x selects draw tool: [end of test] history 1`] = `
11582
+exports[`regression tests key x selects freedraw tool: [end of test] history 1`] = `
11553 11583
 Object {
11554 11584
   "recording": false,
11555 11585
   "redoStack": Array [],
@@ -11579,8 +11609,6 @@ Object {
11579 11609
           "angle": 0,
11580 11610
           "backgroundColor": "transparent",
11581 11611
           "boundElementIds": null,
11582
-          "endArrowhead": null,
11583
-          "endBinding": null,
11584 11612
           "fillStyle": "hachure",
11585 11613
           "groupIds": Array [],
11586 11614
           "height": 10,
@@ -11597,18 +11625,26 @@ Object {
11597 11625
               10,
11598 11626
               10,
11599 11627
             ],
11628
+            Array [
11629
+              10,
11630
+              10,
11631
+            ],
11632
+          ],
11633
+          "pressures": Array [
11634
+            0,
11635
+            0,
11636
+            0,
11600 11637
           ],
11601 11638
           "roughness": 1,
11602 11639
           "seed": 337897,
11603
-          "startArrowhead": null,
11604
-          "startBinding": null,
11640
+          "simulatePressure": false,
11605 11641
           "strokeColor": "#000000",
11606 11642
           "strokeSharpness": "round",
11607 11643
           "strokeStyle": "solid",
11608 11644
           "strokeWidth": 1,
11609
-          "type": "draw",
11610
-          "version": 3,
11611
-          "versionNonce": 449462985,
11645
+          "type": "freedraw",
11646
+          "version": 4,
11647
+          "versionNonce": 453191,
11612 11648
           "width": 10,
11613 11649
           "x": 10,
11614 11650
           "y": 10,
@@ -11619,9 +11655,9 @@ Object {
11619 11655
 }
11620 11656
 `;
11621 11657
 
11622
-exports[`regression tests key x selects draw tool: [end of test] number of elements 1`] = `1`;
11658
+exports[`regression tests key x selects freedraw tool: [end of test] number of elements 1`] = `1`;
11623 11659
 
11624
-exports[`regression tests key x selects draw tool: [end of test] number of renders 1`] = `8`;
11660
+exports[`regression tests key x selects freedraw tool: [end of test] number of renders 1`] = `8`;
11625 11661
 
11626 11662
 exports[`regression tests make a group and duplicate it: [end of test] appState 1`] = `
11627 11663
 Object {

+ 1
- 1
src/tests/flip.test.tsx Vedi File

@@ -71,7 +71,7 @@ const createAndSelectOneLine = (angle: number = 0) => {
71 71
 };
72 72
 
73 73
 const createAndReturnOneDraw = (angle: number = 0) => {
74
-  return UI.createElement("draw", {
74
+  return UI.createElement("freedraw", {
75 75
     x: 0,
76 76
     y: 0,
77 77
     width: 50,

+ 13
- 3
src/tests/helpers/api.ts Vedi File

@@ -3,6 +3,7 @@ import {
3 3
   ExcalidrawGenericElement,
4 4
   ExcalidrawTextElement,
5 5
   ExcalidrawLinearElement,
6
+  ExcalidrawFreeDrawElement,
6 7
 } from "../../element/types";
7 8
 import { newElement, newTextElement, newLinearElement } from "../../element";
8 9
 import { DEFAULT_VERTICAL_ALIGN } from "../../constants";
@@ -12,6 +13,7 @@ import fs from "fs";
12 13
 import util from "util";
13 14
 import path from "path";
14 15
 import { getMimeType } from "../../data/blob";
16
+import { newFreeDrawElement } from "../../element/newElement";
15 17
 
16 18
 const readFile = util.promisify(fs.readFile);
17 19
 
@@ -81,8 +83,10 @@ export class API {
81 83
     verticalAlign?: T extends "text"
82 84
       ? ExcalidrawTextElement["verticalAlign"]
83 85
       : never;
84
-  }): T extends "arrow" | "line" | "draw"
86
+  }): T extends "arrow" | "line"
85 87
     ? ExcalidrawLinearElement
88
+    : T extends "freedraw"
89
+    ? ExcalidrawFreeDrawElement
86 90
     : T extends "text"
87 91
     ? ExcalidrawTextElement
88 92
     : ExcalidrawGenericElement => {
@@ -125,11 +129,17 @@ export class API {
125 129
           verticalAlign: rest.verticalAlign ?? DEFAULT_VERTICAL_ALIGN,
126 130
         });
127 131
         break;
132
+      case "freedraw":
133
+        element = newFreeDrawElement({
134
+          type: type as "freedraw",
135
+          simulatePressure: true,
136
+          ...base,
137
+        });
138
+        break;
128 139
       case "arrow":
129 140
       case "line":
130
-      case "draw":
131 141
         element = newLinearElement({
132
-          type: type as "arrow" | "line" | "draw",
142
+          type: type as "arrow" | "line",
133 143
           startArrowhead: null,
134 144
           endArrowhead: null,
135 145
           ...base,

+ 2
- 2
src/tests/helpers/ui.ts Vedi File

@@ -213,14 +213,14 @@ export class UI {
213 213
       height?: number;
214 214
       angle?: number;
215 215
     } = {},
216
-  ): (T extends "arrow" | "line" | "draw"
216
+  ): (T extends "arrow" | "line" | "freedraw"
217 217
     ? ExcalidrawLinearElement
218 218
     : T extends "text"
219 219
     ? ExcalidrawTextElement
220 220
     : ExcalidrawElement) & {
221 221
     /** Returns the actual, current element from the elements array, instead
222 222
         of the proxy */
223
-    get(): T extends "arrow" | "line" | "draw"
223
+    get(): T extends "arrow" | "line" | "freedraw"
224 224
       ? ExcalidrawLinearElement
225 225
       : T extends "text"
226 226
       ? ExcalidrawTextElement

+ 1
- 1
src/tests/queries/toolQueries.ts Vedi File

@@ -7,7 +7,7 @@ const toolMap = {
7 7
   ellipse: "ellipse",
8 8
   arrow: "arrow",
9 9
   line: "line",
10
-  draw: "draw",
10
+  freedraw: "freedraw",
11 11
   text: "text",
12 12
 };
13 13
 

+ 3
- 3
src/tests/regressionTests.test.tsx Vedi File

@@ -106,7 +106,7 @@ describe("regression tests", () => {
106 106
     mouse.click(30, 10);
107 107
     Keyboard.keyPress(KEYS.ENTER);
108 108
 
109
-    UI.clickTool("draw");
109
+    UI.clickTool("freedraw");
110 110
     mouse.down(40, -20);
111 111
     mouse.up(50, 10);
112 112
 
@@ -118,7 +118,7 @@ describe("regression tests", () => {
118 118
       "line",
119 119
       "arrow",
120 120
       "line",
121
-      "draw",
121
+      "freedraw",
122 122
     ]);
123 123
   });
124 124
 
@@ -146,7 +146,7 @@ describe("regression tests", () => {
146 146
     [`4${KEYS.E}`, "ellipse", true],
147 147
     [`5${KEYS.A}`, "arrow", true],
148 148
     [`6${KEYS.L}`, "line", true],
149
-    [`7${KEYS.X}`, "draw", false],
149
+    [`7${KEYS.X}`, "freedraw", false],
150 150
   ] as [string, ExcalidrawElement["type"], boolean][]) {
151 151
     for (const key of keys) {
152 152
       it(`key ${key} selects ${shape} tool`, () => {

+ 5
- 0
yarn.lock Vedi File

@@ -9249,6 +9249,11 @@ pepjs@0.5.3:
9249 9249
   version "0.5.3"
9250 9250
   resolved "https://registry.npmjs.org/pepjs/-/pepjs-0.5.3.tgz"
9251 9251
 
9252
+perfect-freehand@0.4.7:
9253
+  version "0.4.7"
9254
+  resolved "https://registry.yarnpkg.com/perfect-freehand/-/perfect-freehand-0.4.7.tgz#4d85fd64881ba81b2a4eaa6ac4e8983ccb21dd43"
9255
+  integrity sha512-SSSFL8VzXiOHQdUTyNyOb0JC+btVZRy9bi6jos7Nb7PBTI0PHX5jM6RgCTSrubQ8Ul9qOYWmWgJBrwVGHwyJZQ==
9256
+
9252 9257
 performance-now@^2.1.0:
9253 9258
   version "2.1.0"
9254 9259
   resolved "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz"

Loading…
Annulla
Salva