js-draw 0.20.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +4 -4
  3. package/dist/bundle.js +2 -2
  4. package/dist/bundledStyles.js +1 -1
  5. package/dist/cjs/src/Editor.d.ts +4 -1
  6. package/dist/cjs/src/Editor.js +25 -7
  7. package/dist/cjs/src/components/AbstractComponent.d.ts +13 -1
  8. package/dist/cjs/src/components/AbstractComponent.js +19 -9
  9. package/dist/cjs/src/components/Stroke.d.ts +1 -0
  10. package/dist/cjs/src/components/Stroke.js +14 -1
  11. package/dist/cjs/src/components/util/StrokeSmoother.js +12 -14
  12. package/dist/cjs/src/math/LineSegment2.d.ts +2 -0
  13. package/dist/cjs/src/math/LineSegment2.js +4 -0
  14. package/dist/cjs/src/math/Path.d.ts +24 -3
  15. package/dist/cjs/src/math/Path.js +224 -3
  16. package/dist/cjs/src/math/Rect2.js +4 -3
  17. package/dist/cjs/src/math/polynomial/QuadraticBezier.d.ts +1 -1
  18. package/dist/cjs/src/math/polynomial/QuadraticBezier.js +3 -4
  19. package/dist/cjs/src/toolbar/HTMLToolbar.js +7 -0
  20. package/dist/mjs/src/Editor.d.ts +4 -1
  21. package/dist/mjs/src/Editor.mjs +25 -7
  22. package/dist/mjs/src/components/AbstractComponent.d.ts +13 -1
  23. package/dist/mjs/src/components/AbstractComponent.mjs +19 -9
  24. package/dist/mjs/src/components/Stroke.d.ts +1 -0
  25. package/dist/mjs/src/components/Stroke.mjs +14 -1
  26. package/dist/mjs/src/components/util/StrokeSmoother.mjs +12 -14
  27. package/dist/mjs/src/math/LineSegment2.d.ts +2 -0
  28. package/dist/mjs/src/math/LineSegment2.mjs +4 -0
  29. package/dist/mjs/src/math/Path.d.ts +24 -3
  30. package/dist/mjs/src/math/Path.mjs +224 -3
  31. package/dist/mjs/src/math/Rect2.mjs +4 -3
  32. package/dist/mjs/src/math/polynomial/QuadraticBezier.d.ts +1 -1
  33. package/dist/mjs/src/math/polynomial/QuadraticBezier.mjs +3 -4
  34. package/dist/mjs/src/toolbar/HTMLToolbar.mjs +8 -1
  35. package/package.json +1 -1
  36. package/src/Coloris.css +52 -0
  37. package/src/Editor.css +12 -0
  38. package/src/toolbar/toolbar.css +9 -0
@@ -4,6 +4,7 @@ import LineSegment2 from './LineSegment2.mjs';
4
4
  import Mat33 from './Mat33.mjs';
5
5
  import Rect2 from './Rect2.mjs';
6
6
  import { Vec2 } from './Vec2.mjs';
7
+ import Vec3 from './Vec3.mjs';
7
8
  export var PathCommandType;
8
9
  (function (PathCommandType) {
9
10
  PathCommandType[PathCommandType["LineTo"] = 0] = "LineTo";
@@ -11,6 +12,23 @@ export var PathCommandType;
11
12
  PathCommandType[PathCommandType["CubicBezierTo"] = 2] = "CubicBezierTo";
12
13
  PathCommandType[PathCommandType["QuadraticBezierTo"] = 3] = "QuadraticBezierTo";
13
14
  })(PathCommandType || (PathCommandType = {}));
15
+ // Returns the bounding box of one path segment.
16
+ const getPartBBox = (part) => {
17
+ let partBBox;
18
+ if (part instanceof LineSegment2) {
19
+ partBBox = part.bbox;
20
+ }
21
+ else if (part instanceof Bezier) {
22
+ const bbox = part.bbox();
23
+ const width = bbox.x.max - bbox.x.min;
24
+ const height = bbox.y.max - bbox.y.min;
25
+ partBBox = new Rect2(bbox.x.min, bbox.y.min, width, height);
26
+ }
27
+ else {
28
+ partBBox = new Rect2(part.x, part.y, 0, 0);
29
+ }
30
+ return partBBox;
31
+ };
14
32
  export default class Path {
15
33
  constructor(startPoint, parts) {
16
34
  this.startPoint = startPoint;
@@ -26,6 +44,13 @@ export default class Path {
26
44
  this.bbox = this.bbox.union(Path.computeBBoxForSegment(startPoint, part));
27
45
  }
28
46
  }
47
+ getExactBBox() {
48
+ const bboxes = [];
49
+ for (const part of this.geometry) {
50
+ bboxes.push(getPartBBox(part));
51
+ }
52
+ return Rect2.union(...bboxes);
53
+ }
29
54
  // Lazy-loads and returns this path's geometry
30
55
  get geometry() {
31
56
  if (this.cachedGeometry) {
@@ -48,6 +73,7 @@ export default class Path {
48
73
  startPoint = part.point;
49
74
  break;
50
75
  case PathCommandType.MoveTo:
76
+ geometry.push(part.point);
51
77
  startPoint = part.point;
52
78
  break;
53
79
  }
@@ -103,11 +129,197 @@ export default class Path {
103
129
  }
104
130
  return Rect2.bboxOf(points);
105
131
  }
106
- intersection(line) {
107
- if (!line.bbox.intersects(this.bbox)) {
132
+ /**
133
+ * Let `S` be a closed path a distance `strokeRadius` from this path.
134
+ *
135
+ * @returns Approximate intersections of `line` with `S` using ray marching, starting from
136
+ * both end points of `line` and each point in `additionalRaymarchStartPoints`.
137
+ */
138
+ raymarchIntersectionWith(line, strokeRadius, additionalRaymarchStartPoints = []) {
139
+ var _a, _b;
140
+ // No intersection between bounding boxes: No possible intersection
141
+ // of the interior.
142
+ if (!line.bbox.intersects(this.bbox.grownBy(strokeRadius))) {
143
+ return [];
144
+ }
145
+ const lineLength = line.length;
146
+ const partDistFunctionRecords = [];
147
+ // Determine distance functions for all parts that the given line could possibly intersect with
148
+ for (const part of this.geometry) {
149
+ const bbox = getPartBBox(part).grownBy(strokeRadius);
150
+ if (!bbox.intersects(line.bbox)) {
151
+ continue;
152
+ }
153
+ // Signed distance function
154
+ let partDist;
155
+ if (part instanceof LineSegment2) {
156
+ partDist = (point) => part.distance(point);
157
+ }
158
+ else if (part instanceof Vec3) {
159
+ partDist = (point) => part.minus(point).magnitude();
160
+ }
161
+ else {
162
+ partDist = (point) => {
163
+ return part.project(point).d;
164
+ };
165
+ }
166
+ // Part signed distance function (negative result implies `point` is
167
+ // inside the shape).
168
+ const partSdf = (point) => partDist(point) - strokeRadius;
169
+ // If the line can't possibly intersect the part,
170
+ if (partSdf(line.p1) > lineLength && partSdf(line.p2) > lineLength) {
171
+ continue;
172
+ }
173
+ partDistFunctionRecords.push({
174
+ part,
175
+ distFn: partDist,
176
+ bbox,
177
+ });
178
+ }
179
+ // If no distance functions, there are no intersections.
180
+ if (partDistFunctionRecords.length === 0) {
108
181
  return [];
109
182
  }
183
+ // Returns the minimum distance to a part in this stroke, where only parts that the given
184
+ // line could intersect are considered.
185
+ const sdf = (point) => {
186
+ let minDist = Infinity;
187
+ let minDistPart = null;
188
+ const uncheckedDistFunctions = [];
189
+ // First pass: only curves for which the current point is inside
190
+ // the bounding box.
191
+ for (const distFnRecord of partDistFunctionRecords) {
192
+ const { part, distFn, bbox } = distFnRecord;
193
+ // Check later if the current point isn't in the bounding box.
194
+ if (!bbox.containsPoint(point)) {
195
+ uncheckedDistFunctions.push(distFnRecord);
196
+ continue;
197
+ }
198
+ const currentDist = distFn(point);
199
+ if (currentDist <= minDist) {
200
+ minDist = currentDist;
201
+ minDistPart = part;
202
+ }
203
+ }
204
+ // Second pass: Everything else
205
+ for (const { part, distFn, bbox } of uncheckedDistFunctions) {
206
+ // Skip if impossible for the distance to the target to be lesser than
207
+ // the current minimum.
208
+ if (!bbox.grownBy(minDist).containsPoint(point)) {
209
+ continue;
210
+ }
211
+ const currentDist = distFn(point);
212
+ if (currentDist <= minDist) {
213
+ minDist = currentDist;
214
+ minDistPart = part;
215
+ }
216
+ }
217
+ return [minDistPart, minDist - strokeRadius];
218
+ };
219
+ // Raymarch:
220
+ const maxRaymarchSteps = 7;
221
+ // Start raymarching from each of these points. This allows detection of multiple
222
+ // intersections.
223
+ const startPoints = [
224
+ line.p1, ...additionalRaymarchStartPoints, line.p2
225
+ ];
226
+ // Converts a point ON THE LINE to a parameter
227
+ const pointToParameter = (point) => {
228
+ // Because line.direction is a unit vector, this computes the length
229
+ // of the projection of the vector(line.p1->point) onto line.direction.
230
+ //
231
+ // Note that this can be negative if the given point is outside of the given
232
+ // line segment.
233
+ return point.minus(line.p1).dot(line.direction);
234
+ };
235
+ // Sort start points by parameter on the line.
236
+ // This allows us to determine whether the current value of a parameter
237
+ // drops down to a value already tested.
238
+ startPoints.sort((a, b) => {
239
+ const t_a = pointToParameter(a);
240
+ const t_b = pointToParameter(b);
241
+ // Sort in increasing order
242
+ return t_a - t_b;
243
+ });
110
244
  const result = [];
245
+ const stoppingThreshold = strokeRadius / 1000;
246
+ // Returns the maximum x value explored
247
+ const raymarchFrom = (startPoint,
248
+ // Direction to march in (multiplies line.direction)
249
+ directionMultiplier,
250
+ // Terminate if the current point corresponds to a parameter
251
+ // below this.
252
+ minimumLineParameter) => {
253
+ let currentPoint = startPoint;
254
+ let [lastPart, lastDist] = sdf(currentPoint);
255
+ let lastParameter = pointToParameter(currentPoint);
256
+ if (lastDist > lineLength) {
257
+ return lastParameter;
258
+ }
259
+ const direction = line.direction.times(directionMultiplier);
260
+ for (let i = 0; i < maxRaymarchSteps; i++) {
261
+ // Step in the direction of the edge of the shape.
262
+ const step = lastDist;
263
+ currentPoint = currentPoint.plus(direction.times(step));
264
+ lastParameter = pointToParameter(currentPoint);
265
+ // If we're below the minimum parameter, stop. We've already tried
266
+ // this.
267
+ if (lastParameter <= minimumLineParameter) {
268
+ return lastParameter;
269
+ }
270
+ const [currentPart, signedDist] = sdf(currentPoint);
271
+ // Ensure we're stepping in the correct direction.
272
+ // Note that because we could start with a negative distance and work towards a
273
+ // positive distance, we need absolute values here.
274
+ if (Math.abs(signedDist) > Math.abs(lastDist)) {
275
+ // If not, stop.
276
+ return null;
277
+ }
278
+ lastDist = signedDist;
279
+ lastPart = currentPart;
280
+ // Is the distance close enough that we can stop early?
281
+ if (Math.abs(lastDist) < stoppingThreshold) {
282
+ break;
283
+ }
284
+ }
285
+ // Ensure that the point we ended with is on the line.
286
+ const isOnLineSegment = lastParameter >= 0 && lastParameter <= lineLength;
287
+ if (lastPart && isOnLineSegment && Math.abs(lastDist) < stoppingThreshold) {
288
+ result.push({
289
+ point: currentPoint,
290
+ parameterValue: NaN,
291
+ curve: lastPart,
292
+ });
293
+ }
294
+ return lastParameter;
295
+ };
296
+ // The maximum value of the line's parameter explored so far (0 corresponds to
297
+ // line.p1)
298
+ let maxLineT = 0;
299
+ // Raymarch for each start point.
300
+ //
301
+ // Use a for (i from 0 to length) loop because startPoints may be added
302
+ // during iteration.
303
+ for (let i = 0; i < startPoints.length; i++) {
304
+ const startPoint = startPoints[i];
305
+ // Try raymarching in both directions.
306
+ maxLineT = Math.max(maxLineT, (_a = raymarchFrom(startPoint, 1, maxLineT)) !== null && _a !== void 0 ? _a : maxLineT);
307
+ maxLineT = Math.max(maxLineT, (_b = raymarchFrom(startPoint, -1, maxLineT)) !== null && _b !== void 0 ? _b : maxLineT);
308
+ }
309
+ return result;
310
+ }
311
+ /**
312
+ * Returns a list of intersections with this path. If `strokeRadius` is given,
313
+ * intersections are approximated with the surface `strokeRadius` away from this.
314
+ *
315
+ * If `strokeRadius > 0`, the resultant `parameterValue` has no defined value.
316
+ */
317
+ intersection(line, strokeRadius) {
318
+ let result = [];
319
+ // Is any intersection between shapes within the bounding boxes impossible?
320
+ if (!line.bbox.intersects(this.bbox.grownBy(strokeRadius !== null && strokeRadius !== void 0 ? strokeRadius : 0))) {
321
+ return [];
322
+ }
111
323
  for (const part of this.geometry) {
112
324
  if (part instanceof LineSegment2) {
113
325
  const intersection = part.intersection(line);
@@ -119,7 +331,7 @@ export default class Path {
119
331
  });
120
332
  }
121
333
  }
122
- else {
334
+ else if (part instanceof Bezier) {
123
335
  const intersectionPoints = part.intersects(line).map(t => {
124
336
  // We're using the .intersects(line) function, which is documented
125
337
  // to always return numbers. However, to satisfy the type checker (and
@@ -142,6 +354,15 @@ export default class Path {
142
354
  result.push(...intersectionPoints);
143
355
  }
144
356
  }
357
+ // If given a non-zero strokeWidth, attempt to raymarch.
358
+ // Even if raymarching, we need to collect starting points.
359
+ // We use the above-calculated intersections for this.
360
+ const doRaymarching = strokeRadius && strokeRadius > 1e-8;
361
+ if (doRaymarching) {
362
+ // Starting points for raymarching (in addition to the end points of the line).
363
+ const startPoints = result.map(intersection => intersection.point);
364
+ result = this.raymarchIntersectionWith(line, strokeRadius, startPoints);
365
+ }
145
366
  return result;
146
367
  }
147
368
  static mapPathCommand(part, mapping) {
@@ -68,9 +68,7 @@ export default class Rect2 {
68
68
  }
69
69
  // Returns a new rectangle containing both [this] and [other].
70
70
  union(other) {
71
- const topLeft = this.topLeft.zip(other.topLeft, Math.min);
72
- const bottomRight = this.bottomRight.zip(other.bottomRight, Math.max);
73
- return Rect2.fromCorners(topLeft, bottomRight);
71
+ return Rect2.union(this, other);
74
72
  }
75
73
  // Returns a the subdivision of this into [columns] columns
76
74
  // and [rows] rows. For example,
@@ -108,6 +106,9 @@ export default class Rect2 {
108
106
  }
109
107
  // Returns this grown by [margin] in both the x and y directions.
110
108
  grownBy(margin) {
109
+ if (margin === 0) {
110
+ return this;
111
+ }
111
112
  return new Rect2(this.x - margin, this.y - margin, this.w + margin * 2, this.h + margin * 2);
112
113
  }
113
114
  getClosestPointOnBoundaryTo(target) {
@@ -21,7 +21,7 @@ export default class QuadraticBezier {
21
21
  */
22
22
  approximateDistance(point: Point2): number;
23
23
  /**
24
- * @returns the exact distance from `point` to this.
24
+ * @returns the (more) exact distance from `point` to this.
25
25
  */
26
26
  distance(point: Point2): number;
27
27
  normal(t: number): Vec2;
@@ -92,15 +92,14 @@ export default class QuadraticBezier {
92
92
  return Math.sqrt(Math.min(sqrDist1, sqrDist2, sqrDist3, sqrDist4));
93
93
  }
94
94
  /**
95
- * @returns the exact distance from `point` to this.
95
+ * @returns the (more) exact distance from `point` to this.
96
96
  */
97
97
  distance(point) {
98
98
  if (!this.bezierJs) {
99
99
  this.bezierJs = new Bezier([this.p0.xy, this.p1.xy, this.p2.xy]);
100
100
  }
101
- const proj = Vec2.ofXY(this.bezierJs.project(point.xy));
102
- const dist = proj.minus(point).magnitude();
103
- return dist;
101
+ // .d: Distance
102
+ return this.bezierJs.project(point.xy).d;
104
103
  }
105
104
  normal(t) {
106
105
  const tangent = this.derivativeAt(t);
@@ -1,5 +1,5 @@
1
1
  import { EditorEventType } from '../types.mjs';
2
- import { coloris, init as colorisInit } from '@melloware/coloris';
2
+ import { coloris, close as closeColoris, init as colorisInit } from '@melloware/coloris';
3
3
  import Color4 from '../Color4.mjs';
4
4
  import { defaultToolbarLocalization } from './localization.mjs';
5
5
  import SelectionTool from '../tools/SelectionTool/SelectionTool.mjs';
@@ -60,6 +60,13 @@ export default class HTMLToolbar {
60
60
  const closePickerOverlay = document.createElement('div');
61
61
  closePickerOverlay.className = `${toolbarCSSPrefix}closeColorPickerOverlay`;
62
62
  this.editor.createHTMLOverlay(closePickerOverlay);
63
+ // Hide the color picker when attempting to draw on the overlay.
64
+ this.listeners.push(this.editor.handlePointerEventsFrom(closePickerOverlay, (eventName) => {
65
+ if (eventName === 'pointerdown') {
66
+ closeColoris();
67
+ }
68
+ return true;
69
+ }));
63
70
  const maxSwatchLen = 12;
64
71
  const swatches = [
65
72
  Color4.red.toHexString(),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "js-draw",
3
- "version": "0.20.0",
3
+ "version": "0.21.0",
4
4
  "description": "Draw pictures using a pen, touchscreen, or mouse! JS-draw is a drawing library for JavaScript and TypeScript. ",
5
5
  "types": "./dist/mjs/src/lib.d.ts",
6
6
  "main": "./dist/cjs/src/lib.js",
@@ -0,0 +1,52 @@
1
+
2
+ /* Imports Coloris' CSS and makes additional changes to the color picker */
3
+
4
+ #clr-picker {
5
+ --clr-slider-size: 30px;
6
+ }
7
+
8
+ /* Coloris: Try to avoid scrolling instead of updating the color input. */
9
+ #clr-picker #clr-color-area, #clr-picker .clr_hue {
10
+ touch-action: none;
11
+ }
12
+
13
+ /* Increase space between inputs */
14
+ #clr-picker .clr-alpha {
15
+ margin-top: 15px;
16
+ margin-bottom: 15px;
17
+ }
18
+
19
+ /* Increase size of input thumb to make it easier to select colors. */
20
+ #clr-picker.clr-picker input[type="range"]::-moz-range-thumb {
21
+ width: var(--clr-slider-size);
22
+ height: var(--clr-slider-size);
23
+ }
24
+
25
+ /* Also apply to Chrome/iOS */
26
+ #clr-picker.clr-picker input[type="range"]::-webkit-slider-thumb {
27
+ /*
28
+ Note: This doesn't seem to take effect in iOS if it's combined with the
29
+ ::-moz-range-thumb rule above
30
+ */
31
+ width: var(--clr-slider-size);
32
+ height: var(--clr-slider-size);
33
+ }
34
+
35
+ #clr-picker.clr-picker input[type="range"]::-webkit-slider-runnable-track {
36
+ height: var(--clr-slider-size);
37
+ }
38
+
39
+ #clr-picker.clr-picker input[type="range"]::-moz-range-track {
40
+ height: var(--clr-slider-size);
41
+ }
42
+
43
+ /*
44
+ Debugging: Uncommenting this rule makes Coloris' sliders more
45
+ visible.
46
+
47
+ #clr-picker.clr-picker input[type="range"] {
48
+ opacity: 0.5;
49
+ -webkit-appearance: auto;
50
+ appearance: auto;
51
+ }
52
+ */
package/src/Editor.css CHANGED
@@ -1,6 +1,7 @@
1
1
 
2
2
  @import url('./toolbar/toolbar.css');
3
3
  @import url('./tools/tools.css');
4
+ @import url('./Coloris.css');
4
5
 
5
6
  .imageEditorContainer {
6
7
  /* Deafult colors for the editor */
@@ -84,3 +85,14 @@
84
85
  overflow: visible;
85
86
  z-index: 5;
86
87
  }
88
+
89
+ @media print {
90
+ .imageEditorContainer .loadingMessage {
91
+ display: none;
92
+ }
93
+
94
+ .imageEditorContainer .imageEditorRenderArea canvas {
95
+ width: 100%;
96
+ height: initial;
97
+ }
98
+ }
@@ -160,6 +160,8 @@
160
160
  bottom: 0;
161
161
  right: 0;
162
162
 
163
+ touch-action: none;
164
+
163
165
  background-color: var(--primary-background-color);
164
166
  opacity: 0.3;
165
167
  }
@@ -210,4 +212,11 @@
210
212
  .toolbar-spacedList > * {
211
213
  padding-bottom: 5px;
212
214
  padding-top: 5px;
215
+ }
216
+
217
+ @media print {
218
+ /* Hide the toolbar on print. */
219
+ .toolbar-root {
220
+ display: none;
221
+ }
213
222
  }