-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathtools.ts
More file actions
373 lines (326 loc) · 8.51 KB
/
tools.ts
File metadata and controls
373 lines (326 loc) · 8.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
import * as fabric from "fabric";
import Page from "./page";
import ClipboardHandler from "./clipboard";
import HistoryHandler from "./history";
import { PathEvent, GuaranteedIObjectOptions } from "../types/fabric";
import AssertType from "../types/assert";
type Async<T = void> = T | Promise<T>;
class Behaviors {
// given the origin x, y, snaps the point x2, y2 to the nearest vector in dirs
static rectify = (
dirs: number[][],
x: number,
y: number,
x2: number,
y2: number,
): number[] => {
return dirs
.map((d) => Behaviors.project(x, y, d[0], d[1], x2, y2))
.reduce((acc, cur) => (acc[0] < cur[0] ? acc : cur));
};
// projects the point x2, y2 to the vector with origin ox, oy and direction vx, vy. returns the square distance and the coordinates of the projection.
private static project = (
ox: number,
oy: number,
vx: number,
vy: number,
x2: number,
y2: number,
): number[] => {
const x = x2 - ox;
const y = y2 - oy;
const side = vx * y - vy * x;
const sq = vx * vx + vy * vy;
return [
Math.abs(side) / sq,
ox + x + (vy * side) / sq,
oy + y - (vx * side) / sq,
];
};
}
export class Tool {
// Add type marker `boolean` so it can be overridden; otherwise takes type `false`
/**
* Make sure that no extending classes except DrawingTool set this to true;
* the value of this property is used as a type guard.
*/
protected readonly _isDrawing: boolean = false;
/**
* Make sure that no extending classes except RequiresBaseTool set this to true;
* the value of this property is used as a type guard.
*/
protected readonly _requiresBase: boolean = false;
/**
* Make sure that no extending classes except Brush set this to true;
* the value of this property is used as a type guard.
*/
protected readonly _isBrush: boolean = false;
isDrawing(): this is DrawingTool {
return this._isDrawing;
}
requiresBase(): this is RequiresBase {
return this._requiresBase;
}
isBrush(): this is Brush {
return this._isBrush;
}
resize?: (
object: fabric.FabricObject,
x2: number,
y2: number,
strict: boolean,
) => Async<fabric.FabricObject>;
/**
* Set externally from activate() and deactivate().
* Set internally (from an extending class) with setActive();
* @private
*/
private active = false;
constructor(
protected baseCanvas: Page,
protected history: HistoryHandler,
protected clipboard: ClipboardHandler,
) {}
/**
* @return Whether the activation was successful.
* Maybe want to throw error instead of return boolean.
*/
activate: () => Async<boolean> = () => this.setActive(true);
/**
* Not allowed to fail
*/
deactivate: () => void = () => this.setActive(false);
/**
* get this.active
*/
isActive = (): boolean => this.active;
/**
* set this.active active
*/
protected setActive = (active: boolean): boolean => (this.active = active);
}
export abstract class DrawingTool extends Tool {
_isDrawing = true;
abstract draw: (
x: number,
y: number,
options: Partial<fabric.FabricObjectProps>,
x2?: number,
y2?: number,
) => fabric.FabricObject | Promise<fabric.FabricObject>;
}
export abstract class RequiresBase extends Tool {
_requiresBase = true;
}
export abstract class Brush extends RequiresBase {
_isBrush = true;
/**
* Handle the pathCreated event
*/
pathCreated: (e: PathEvent) => void = () => {};
setBrush: (
brush: fabric.BaseBrush,
options: GuaranteedIObjectOptions,
) => void | Promise<void> = () => {};
}
export class Move extends RequiresBase {}
export class Pen extends Brush {
pathCreated = (e: PathEvent): void => {
this.history.add([e.path]);
};
setBrush = (
brush: fabric.BaseBrush,
options: GuaranteedIObjectOptions,
): void => {
brush.color = options.stroke;
brush.strokeDashArray = options.strokeDashArray;
brush.width = options.strokeWidth;
};
}
export class Eraser extends Brush {
pathCreated = ({ path }: PathEvent): void => {
const objects = this.baseCanvas
.getObjects()
.filter((object) => object.intersectsWithObject(path));
this.baseCanvas.remove(path, ...objects);
this.history.remove(objects);
};
setBrush = (
brush: fabric.BaseBrush,
options: GuaranteedIObjectOptions,
): void => {
brush.color = "#ff005455";
brush.strokeDashArray = [0, 0];
brush.width = 5 * options.strokeWidth;
};
/**
* Attempts to activate the current tool
*
* Default implementation:
* Execute cut() which attempts to cut currently selected objects if they exist.
* If cut() true then abort; leave current tool active.
* Otherwise, mark internal state as active and return true
*
* @return Whether it was able to successfully activate
*/
activate = (): boolean => !this.clipboard.cut() && this.setActive(true);
}
export class Laser extends Brush {
pathCreated = (e: PathEvent): void => {
setTimeout(() => {
this.baseCanvas.remove(e.path);
this.baseCanvas.requestRenderAll();
}, 1000);
};
setBrush = (
brush: fabric.BaseBrush,
options: GuaranteedIObjectOptions,
): void => {
brush.color = "#f23523";
brush.strokeDashArray = [0, 0];
brush.width = options.strokeWidth;
};
}
export class Line extends DrawingTool {
x = 0;
y = 0;
dirs: number[][] = [
[1, 0],
[1, 1],
[0, 1],
[-1, 1],
];
draw = (
x: number,
y: number,
options: Partial<fabric.FabricObjectProps>,
x2?: number,
y2?: number,
): fabric.Line => {
this.x = x;
this.y = y;
return new fabric.Line([x, y, x2 ?? x, y2 ?? y], {
...options,
perPixelTargetFind: true,
});
};
resize = (
object: fabric.FabricObject,
x2: number,
y2: number,
strict: boolean,
): fabric.Line => {
AssertType<fabric.Line>(object);
const [, x, y] = strict
? Behaviors.rectify(this.dirs, this.x, this.y, x2, y2)
: [undefined, x2, y2];
object.set({ x2: x, y2: y }).setCoords();
return object;
};
}
export class Rectangle extends DrawingTool {
x = 0;
y = 0;
dirs: number[][] = [
[1, 1],
[-1, 1],
];
draw = (
x: number,
y: number,
options: Partial<fabric.FabricObjectProps>,
x2?: number,
y2?: number,
): fabric.Rect => {
this.x = x;
this.y = y;
return new fabric.Rect({
left: x,
top: y,
width: x2,
height: y2,
...options,
});
};
resize = (
object: fabric.FabricObject,
x2: number,
y2: number,
strict: boolean,
): fabric.Rect => {
const [, x, y] = strict
? Behaviors.rectify(this.dirs, this.x, this.y, x2, y2)
: [undefined, x2, y2];
object
.set({
originX: this.x > x ? "right" : "left",
originY: this.y > y ? "bottom" : "top",
width: Math.abs(this.x - x),
height: Math.abs(this.y - y),
})
.setCoords();
return object as fabric.Rect;
};
}
export class Ellipse extends DrawingTool {
x = 0;
y = 0;
dirs: number[][] = [
[1, 1],
[-1, 1],
];
draw = (
x: number,
y: number,
options: Partial<fabric.FabricObjectProps>,
x2?: number,
y2?: number,
): fabric.Ellipse => {
this.x = x;
this.y = y;
return new fabric.Ellipse({ ...options, left: x, top: y, rx: x2, ry: y2 });
};
resize = (
object: fabric.FabricObject,
x2: number,
y2: number,
strict: boolean,
): fabric.Ellipse => {
AssertType<fabric.Ellipse>(object);
const [, x, y] = strict
? Behaviors.rectify(this.dirs, this.x, this.y, x2, y2)
: [undefined, x2, y2];
object
.set({
originX: this.x > x ? "right" : "left",
originY: this.y > y ? "bottom" : "top",
rx: Math.abs(x - (object.left || 0)) / 2,
ry: Math.abs(y - (object.top || 0)) / 2,
})
.setCoords();
return object;
};
}
export interface Tools {
Line: Line;
Ellipse: Ellipse;
Move: Move;
Laser: Laser;
Pen: Pen;
Rectangle: Rectangle;
Eraser: Eraser;
}
const instantiateTools = (
baseCanvas: Page,
history: HistoryHandler,
clipboard: ClipboardHandler,
): Tools => ({
Move: new Move(baseCanvas, history, clipboard),
Pen: new Pen(baseCanvas, history, clipboard),
Eraser: new Eraser(baseCanvas, history, clipboard),
Laser: new Laser(baseCanvas, history, clipboard),
Line: new Line(baseCanvas, history, clipboard),
Rectangle: new Rectangle(baseCanvas, history, clipboard),
Ellipse: new Ellipse(baseCanvas, history, clipboard),
});
export default instantiateTools;