-
-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
Canvas.ts
1532 lines (1440 loc) · 46.9 KB
/
Canvas.ts
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { classRegistry } from '../ClassRegistry';
import { NONE } from '../constants';
import type {
CanvasEvents,
DragEventData,
ObjectEvents,
TPointerEvent,
TPointerEventNames,
Transform,
} from '../EventTypeDefs';
import { Point } from '../Point';
import type { ActiveSelection } from '../shapes/ActiveSelection';
import type { Group } from '../shapes/Group';
import type { IText } from '../shapes/IText/IText';
import type { FabricObject } from '../shapes/Object/FabricObject';
import { isTouchEvent, stopEvent } from '../util/dom_event';
import { getDocumentFromElement, getWindowFromElement } from '../util/dom_misc';
import { sendPointToPlane } from '../util/misc/planeChange';
import { isActiveSelection } from '../util/typeAssertions';
import type { CanvasOptions, TCanvasOptions } from './CanvasOptions';
import { SelectableCanvas } from './SelectableCanvas';
import { TextEditingManager } from './TextEditingManager';
const addEventOptions = { passive: false } as EventListenerOptions;
const getEventPoints = (canvas: Canvas, e: TPointerEvent) => {
const viewportPoint = canvas.getViewportPoint(e);
const scenePoint = canvas.getScenePoint(e);
return {
viewportPoint,
scenePoint,
pointer: viewportPoint,
absolutePointer: scenePoint,
};
};
// just to be clear, the utils are now deprecated and those are here exactly as minifier helpers
// because el.addEventListener can't me be minified while a const yes and we use it 47 times in this file.
// few bytes but why give it away.
const addListener = (
el: HTMLElement | Document,
...args: Parameters<HTMLElement['addEventListener']>
) => el.addEventListener(...args);
const removeListener = (
el: HTMLElement | Document,
...args: Parameters<HTMLElement['removeEventListener']>
) => el.removeEventListener(...args);
const syntheticEventConfig = {
mouse: {
in: 'over',
out: 'out',
targetIn: 'mouseover',
targetOut: 'mouseout',
canvasIn: 'mouse:over',
canvasOut: 'mouse:out',
},
drag: {
in: 'enter',
out: 'leave',
targetIn: 'dragenter',
targetOut: 'dragleave',
canvasIn: 'drag:enter',
canvasOut: 'drag:leave',
},
} as const;
type TSyntheticEventContext = {
mouse: { e: TPointerEvent };
drag: DragEventData;
};
export class Canvas extends SelectableCanvas implements CanvasOptions {
/**
* Contains the id of the touch event that owns the fabric transform
* @type Number
* @private
*/
declare mainTouchId: null | number;
declare enablePointerEvents: boolean;
/**
* Holds a reference to a setTimeout timer for event synchronization
* @type number
* @private
*/
private declare _willAddMouseDown: number;
/**
* Holds a reference to an object on the canvas that is receiving the drag over event.
* @type FabricObject
* @private
*/
private declare _draggedoverTarget?: FabricObject;
/**
* Holds a reference to an object on the canvas from where the drag operation started
* @type FabricObject
* @private
*/
private declare _dragSource?: FabricObject;
/**
* Holds a reference to an object on the canvas that is the current drop target
* May differ from {@link _draggedoverTarget}
* @todo inspect whether {@link _draggedoverTarget} and {@link _dropTarget} should be merged somehow
* @type FabricObject
* @private
*/
private declare _dropTarget: FabricObject<ObjectEvents> | undefined;
private _isClick: boolean;
textEditingManager = new TextEditingManager(this);
constructor(el?: string | HTMLCanvasElement, options: TCanvasOptions = {}) {
super(el, options);
// bind event handlers
(
[
'_onMouseDown',
'_onTouchStart',
'_onMouseMove',
'_onMouseUp',
'_onTouchEnd',
'_onResize',
// '_onGesture',
// '_onDrag',
// '_onShake',
// '_onLongPress',
// '_onOrientationChange',
'_onMouseWheel',
'_onMouseOut',
'_onMouseEnter',
'_onContextMenu',
'_onDoubleClick',
'_onDragStart',
'_onDragEnd',
'_onDragProgress',
'_onDragOver',
'_onDragEnter',
'_onDragLeave',
'_onDrop',
] as (keyof this)[]
).forEach((eventHandler) => {
this[eventHandler] = (this[eventHandler] as Function).bind(this);
});
// register event handlers
this.addOrRemove(addListener, 'add');
}
/**
* return an event prefix pointer or mouse.
* @private
*/
private _getEventPrefix() {
return this.enablePointerEvents ? 'pointer' : 'mouse';
}
addOrRemove(functor: any, eventjsFunctor: 'add' | 'remove') {
const canvasElement = this.upperCanvasEl,
eventTypePrefix = this._getEventPrefix();
functor(getWindowFromElement(canvasElement), 'resize', this._onResize);
functor(canvasElement, eventTypePrefix + 'down', this._onMouseDown);
functor(
canvasElement,
`${eventTypePrefix}move`,
this._onMouseMove,
addEventOptions
);
functor(canvasElement, `${eventTypePrefix}out`, this._onMouseOut);
functor(canvasElement, `${eventTypePrefix}enter`, this._onMouseEnter);
functor(canvasElement, 'wheel', this._onMouseWheel);
functor(canvasElement, 'contextmenu', this._onContextMenu);
functor(canvasElement, 'dblclick', this._onDoubleClick);
functor(canvasElement, 'dragstart', this._onDragStart);
functor(canvasElement, 'dragend', this._onDragEnd);
functor(canvasElement, 'dragover', this._onDragOver);
functor(canvasElement, 'dragenter', this._onDragEnter);
functor(canvasElement, 'dragleave', this._onDragLeave);
functor(canvasElement, 'drop', this._onDrop);
if (!this.enablePointerEvents) {
functor(canvasElement, 'touchstart', this._onTouchStart, addEventOptions);
}
// if (typeof eventjs !== 'undefined' && eventjsFunctor in eventjs) {
// eventjs[eventjsFunctor](canvasElement, 'gesture', this._onGesture);
// eventjs[eventjsFunctor](canvasElement, 'drag', this._onDrag);
// eventjs[eventjsFunctor](
// canvasElement,
// 'orientation',
// this._onOrientationChange
// );
// eventjs[eventjsFunctor](canvasElement, 'shake', this._onShake);
// eventjs[eventjsFunctor](canvasElement, 'longpress', this._onLongPress);
// }
}
/**
* Removes all event listeners
*/
removeListeners() {
this.addOrRemove(removeListener, 'remove');
// if you dispose on a mouseDown, before mouse up, you need to clean document to...
const eventTypePrefix = this._getEventPrefix();
const doc = getDocumentFromElement(this.upperCanvasEl);
removeListener(
doc,
`${eventTypePrefix}up`,
this._onMouseUp as EventListener
);
removeListener(
doc,
'touchend',
this._onTouchEnd as EventListener,
addEventOptions
);
removeListener(
doc,
`${eventTypePrefix}move`,
this._onMouseMove as EventListener,
addEventOptions
);
removeListener(
doc,
'touchmove',
this._onMouseMove as EventListener,
addEventOptions
);
}
/**
* @private
* @param {Event} [e] Event object fired on wheel event
*/
private _onMouseWheel(e: MouseEvent) {
this.__onMouseWheel(e);
}
/**
* @private
* @param {Event} e Event object fired on mousedown
*/
private _onMouseOut(e: TPointerEvent) {
const target = this._hoveredTarget;
const shared = {
e,
...getEventPoints(this, e),
};
this.fire('mouse:out', { ...shared, target });
this._hoveredTarget = undefined;
target && target.fire('mouseout', { ...shared });
this._hoveredTargets.forEach((nestedTarget) => {
this.fire('mouse:out', { ...shared, target: nestedTarget });
nestedTarget && nestedTarget.fire('mouseout', { ...shared });
});
this._hoveredTargets = [];
}
/**
* @private
* @param {Event} e Event object fired on mouseenter
*/
private _onMouseEnter(e: TPointerEvent) {
// This find target and consequent 'mouse:over' is used to
// clear old instances on hovered target.
// calling findTarget has the side effect of killing target.__corner.
// as a short term fix we are not firing this if we are currently transforming.
// as a long term fix we need to separate the action of finding a target with the
// side effects we added to it.
if (!this._currentTransform && !this.findTarget(e)) {
this.fire('mouse:over', {
e,
...getEventPoints(this, e),
});
this._hoveredTarget = undefined;
this._hoveredTargets = [];
}
}
/**
* supports native like text dragging
* @private
* @param {DragEvent} e
*/
private _onDragStart(e: DragEvent) {
this._isClick = false;
const activeObject = this.getActiveObject();
if (activeObject && activeObject.onDragStart(e)) {
this._dragSource = activeObject;
const options = { e, target: activeObject };
this.fire('dragstart', options);
activeObject.fire('dragstart', options);
addListener(
this.upperCanvasEl,
'drag',
this._onDragProgress as EventListener
);
return;
}
stopEvent(e);
}
/**
* First we clear top context where the effects are being rendered.
* Then we render the effects.
* Doing so will render the correct effect for all cases including an overlap between `source` and `target`.
* @private
*/
private _renderDragEffects(
e: DragEvent,
source?: FabricObject,
target?: FabricObject
) {
let dirty = false;
// clear top context
const dropTarget = this._dropTarget;
if (dropTarget && dropTarget !== source && dropTarget !== target) {
dropTarget.clearContextTop();
dirty = true;
}
source?.clearContextTop();
target !== source && target?.clearContextTop();
// render effects
const ctx = this.contextTop;
ctx.save();
ctx.transform(...this.viewportTransform);
if (source) {
ctx.save();
source.transform(ctx);
source.renderDragSourceEffect(e);
ctx.restore();
dirty = true;
}
if (target) {
ctx.save();
target.transform(ctx);
target.renderDropTargetEffect(e);
ctx.restore();
dirty = true;
}
ctx.restore();
dirty && (this.contextTopDirty = true);
}
/**
* supports native like text dragging
* https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Drag_operations#finishing_a_drag
* @private
* @param {DragEvent} e
*/
private _onDragEnd(e: DragEvent) {
const didDrop = !!e.dataTransfer && e.dataTransfer.dropEffect !== NONE,
dropTarget = didDrop ? this._activeObject : undefined,
options = {
e,
target: this._dragSource as FabricObject,
subTargets: this.targets,
dragSource: this._dragSource as FabricObject,
didDrop,
dropTarget: dropTarget as FabricObject,
};
removeListener(
this.upperCanvasEl,
'drag',
this._onDragProgress as EventListener
);
this.fire('dragend', options);
this._dragSource && this._dragSource.fire('dragend', options);
delete this._dragSource;
// we need to call mouse up synthetically because the browser won't
this._onMouseUp(e);
}
/**
* fire `drag` event on canvas and drag source
* @private
* @param {DragEvent} e
*/
private _onDragProgress(e: DragEvent) {
const options = {
e,
target: this._dragSource as FabricObject | undefined,
dragSource: this._dragSource as FabricObject | undefined,
dropTarget: this._draggedoverTarget as FabricObject,
};
this.fire('drag', options);
this._dragSource && this._dragSource.fire('drag', options);
}
/**
* As opposed to {@link findTarget} we want the top most object to be returned w/o the active object cutting in line.
* Override at will
*/
protected findDragTargets(e: DragEvent) {
this.targets = [];
const target = this._searchPossibleTargets(
this._objects,
this.getViewportPoint(e)
);
return {
target,
targets: [...this.targets],
};
}
/**
* prevent default to allow drop event to be fired
* https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Drag_operations#specifying_drop_targets
* @private
* @param {DragEvent} [e] Event object fired on Event.js shake
*/
private _onDragOver(e: DragEvent) {
const eventType = 'dragover';
const { target, targets } = this.findDragTargets(e);
const dragSource = this._dragSource as FabricObject;
const options = {
e,
target,
subTargets: targets,
dragSource,
canDrop: false,
dropTarget: undefined,
};
let dropTarget;
// fire on canvas
this.fire(eventType, options);
// make sure we fire dragenter events before dragover
// if dragleave is needed, object will not fire dragover so we don't need to trouble ourselves with it
this._fireEnterLeaveEvents(target, options);
if (target) {
if (target.canDrop(e)) {
dropTarget = target;
}
target.fire(eventType, options);
}
// propagate the event to subtargets
for (let i = 0; i < targets.length; i++) {
const subTarget = targets[i];
// accept event only if previous targets didn't (the accepting target calls `preventDefault` to inform that the event is taken)
// TODO: verify if those should loop in inverse order then?
// what is the order of subtargets?
if (subTarget.canDrop(e)) {
dropTarget = subTarget;
}
subTarget.fire(eventType, options);
}
// render drag effects now that relations between source and target is clear
this._renderDragEffects(e, dragSource, dropTarget);
this._dropTarget = dropTarget;
}
/**
* fire `dragleave` on `dragover` targets
* @private
* @param {Event} [e] Event object fired on Event.js shake
*/
private _onDragEnter(e: DragEvent) {
const { target, targets } = this.findDragTargets(e);
const options = {
e,
target,
subTargets: targets,
dragSource: this._dragSource,
};
this.fire('dragenter', options);
// fire dragenter on targets
this._fireEnterLeaveEvents(target, options);
}
/**
* fire `dragleave` on `dragover` targets
* @private
* @param {Event} [e] Event object fired on Event.js shake
*/
private _onDragLeave(e: DragEvent) {
const options = {
e,
target: this._draggedoverTarget,
subTargets: this.targets,
dragSource: this._dragSource,
};
this.fire('dragleave', options);
// fire dragleave on targets
this._fireEnterLeaveEvents(undefined, options);
this._renderDragEffects(e, this._dragSource);
this._dropTarget = undefined;
// clear targets
this.targets = [];
this._hoveredTargets = [];
}
/**
* `drop:before` is a an event that allows you to schedule logic
* before the `drop` event. Prefer `drop` event always, but if you need
* to run some drop-disabling logic on an event, since there is no way
* to handle event handlers ordering, use `drop:before`
* @private
* @param {Event} e
*/
private _onDrop(e: DragEvent) {
const { target, targets } = this.findDragTargets(e);
const options = this._basicEventHandler('drop:before', {
e,
target,
subTargets: targets,
dragSource: this._dragSource,
...getEventPoints(this, e),
});
// will be set by the drop target
options.didDrop = false;
// will be set by the drop target, used in case options.target refuses the drop
options.dropTarget = undefined;
// fire `drop`
this._basicEventHandler('drop', options);
// inform canvas of the drop
// we do this because canvas was unaware of what happened at the time the `drop` event was fired on it
// use for side effects
this.fire('drop:after', options);
}
/**
* @private
* @param {Event} e Event object fired on mousedown
*/
private _onContextMenu(e: TPointerEvent): false {
const target = this.findTarget(e),
subTargets = this.targets || [];
const options = this._basicEventHandler('contextmenu:before', {
e,
target,
subTargets,
});
// TODO: this line is silly because the dev can subscribe to the event and prevent it themselves
this.stopContextMenu && stopEvent(e);
this._basicEventHandler('contextmenu', options);
return false;
}
/**
* @private
* @param {Event} e Event object fired on mousedown
*/
private _onDoubleClick(e: TPointerEvent) {
this._cacheTransformEventData(e);
this._handleEvent(e, 'dblclick');
this._resetTransformEventData();
}
/**
* Return a the id of an event.
* returns either the pointerId or the identifier or 0 for the mouse event
* @private
* @param {Event} evt Event object
*/
getPointerId(evt: TouchEvent | PointerEvent): number {
const changedTouches = (evt as TouchEvent).changedTouches;
if (changedTouches) {
return changedTouches[0] && changedTouches[0].identifier;
}
if (this.enablePointerEvents) {
return (evt as PointerEvent).pointerId;
}
return -1;
}
/**
* Determines if an event has the id of the event that is considered main
* @private
* @param {evt} event Event object
*/
_isMainEvent(evt: TPointerEvent): boolean {
if ((evt as PointerEvent).isPrimary === true) {
return true;
}
if ((evt as PointerEvent).isPrimary === false) {
return false;
}
if (evt.type === 'touchend' && (evt as TouchEvent).touches.length === 0) {
return true;
}
if ((evt as TouchEvent).changedTouches) {
return (
(evt as TouchEvent).changedTouches[0].identifier === this.mainTouchId
);
}
return true;
}
/**
* @private
* @param {Event} e Event object fired on mousedown
*/
_onTouchStart(e: TouchEvent) {
e.preventDefault();
if (this.mainTouchId === null) {
this.mainTouchId = this.getPointerId(e);
}
this.__onMouseDown(e);
this._resetTransformEventData();
const canvasElement = this.upperCanvasEl,
eventTypePrefix = this._getEventPrefix();
const doc = getDocumentFromElement(canvasElement);
addListener(
doc,
'touchend',
this._onTouchEnd as EventListener,
addEventOptions
);
addListener(
doc,
'touchmove',
this._onMouseMove as EventListener,
addEventOptions
);
// Unbind mousedown to prevent double triggers from touch devices
removeListener(
canvasElement,
`${eventTypePrefix}down`,
this._onMouseDown as EventListener
);
}
/**
* @private
* @param {Event} e Event object fired on mousedown
*/
_onMouseDown(e: TPointerEvent) {
this.__onMouseDown(e);
this._resetTransformEventData();
const canvasElement = this.upperCanvasEl,
eventTypePrefix = this._getEventPrefix();
removeListener(
canvasElement,
`${eventTypePrefix}move`,
this._onMouseMove as EventListener,
addEventOptions
);
const doc = getDocumentFromElement(canvasElement);
addListener(doc, `${eventTypePrefix}up`, this._onMouseUp as EventListener);
addListener(
doc,
`${eventTypePrefix}move`,
this._onMouseMove as EventListener,
addEventOptions
);
}
/**
* @private
* @param {Event} e Event object fired on mousedown
*/
_onTouchEnd(e: TouchEvent) {
if (e.touches.length > 0) {
// if there are still touches stop here
return;
}
this.__onMouseUp(e);
this._resetTransformEventData();
this.mainTouchId = null;
const eventTypePrefix = this._getEventPrefix();
const doc = getDocumentFromElement(this.upperCanvasEl);
removeListener(
doc,
'touchend',
this._onTouchEnd as EventListener,
addEventOptions
);
removeListener(
doc,
'touchmove',
this._onMouseMove as EventListener,
addEventOptions
);
if (this._willAddMouseDown) {
clearTimeout(this._willAddMouseDown);
}
this._willAddMouseDown = setTimeout(() => {
// Wait 400ms before rebinding mousedown to prevent double triggers
// from touch devices
addListener(
this.upperCanvasEl,
`${eventTypePrefix}down`,
this._onMouseDown as EventListener
);
this._willAddMouseDown = 0;
}, 400) as unknown as number;
}
/**
* @private
* @param {Event} e Event object fired on mouseup
*/
_onMouseUp(e: TPointerEvent) {
this.__onMouseUp(e);
this._resetTransformEventData();
const canvasElement = this.upperCanvasEl,
eventTypePrefix = this._getEventPrefix();
if (this._isMainEvent(e)) {
const doc = getDocumentFromElement(this.upperCanvasEl);
removeListener(
doc,
`${eventTypePrefix}up`,
this._onMouseUp as EventListener
);
removeListener(
doc,
`${eventTypePrefix}move`,
this._onMouseMove as EventListener,
addEventOptions
);
addListener(
canvasElement,
`${eventTypePrefix}move`,
this._onMouseMove as EventListener,
addEventOptions
);
}
}
/**
* @private
* @param {Event} e Event object fired on mousemove
*/
_onMouseMove(e: TPointerEvent) {
const activeObject = this.getActiveObject();
!this.allowTouchScrolling &&
(!activeObject ||
// a drag event sequence is started by the active object flagging itself on mousedown / mousedown:before
// we must not prevent the event's default behavior in order for the window to start dragging
!activeObject.shouldStartDragging()) &&
e.preventDefault &&
e.preventDefault();
this.__onMouseMove(e);
}
/**
* @private
*/
_onResize() {
this.calcOffset();
this._resetTransformEventData();
}
/**
* Decides whether the canvas should be redrawn in mouseup and mousedown events.
* @private
* @param {Object} target
*/
_shouldRender(target: FabricObject | undefined) {
const activeObject = this.getActiveObject();
// if just one of them is available or if they are both but are different objects
// this covers: switch of target, from target to no target, selection of target
// multiSelection with key and mouse
return (
!!activeObject !== !!target ||
(activeObject && target && activeObject !== target)
);
}
/**
* Method that defines the actions when mouse is released on canvas.
* The method resets the currentTransform parameters, store the image corner
* position in the image object and render the canvas on top.
* @private
* @param {Event} e Event object fired on mouseup
*/
__onMouseUp(e: TPointerEvent) {
this._cacheTransformEventData(e);
this._handleEvent(e, 'up:before');
const transform = this._currentTransform;
const isClick = this._isClick;
const target = this._target;
// if right/middle click just fire events and return
// target undefined will make the _handleEvent search the target
const { button } = e as MouseEvent;
if (button) {
((this.fireMiddleClick && button === 1) ||
(this.fireRightClick && button === 2)) &&
this._handleEvent(e, 'up');
this._resetTransformEventData();
return;
}
if (this.isDrawingMode && this._isCurrentlyDrawing) {
this._onMouseUpInDrawingMode(e);
return;
}
if (!this._isMainEvent(e)) {
return;
}
let shouldRender = false;
if (transform) {
this._finalizeCurrentTransform(e);
shouldRender = transform.actionPerformed;
}
if (!isClick) {
const targetWasActive = target === this._activeObject;
this.handleSelection(e);
if (!shouldRender) {
shouldRender =
this._shouldRender(target) ||
(!targetWasActive && target === this._activeObject);
}
}
let pointer, corner;
if (target) {
corner = target._findTargetCorner(
this.getViewportPoint(e),
isTouchEvent(e)
);
if (
target.selectable &&
target !== this._activeObject &&
target.activeOn === 'up'
) {
this.setActiveObject(target, e);
shouldRender = true;
} else {
const control = target.controls[corner];
const mouseUpHandler =
control && control.getMouseUpHandler(e, target, control);
if (mouseUpHandler) {
pointer = this.getScenePoint(e);
mouseUpHandler.call(control, e, transform!, pointer.x, pointer.y);
}
}
target.isMoving = false;
}
// if we are ending up a transform on a different control or a new object
// fire the original mouse up from the corner that started the transform
if (
transform &&
(transform.target !== target || transform.corner !== corner)
) {
const originalControl =
transform.target && transform.target.controls[transform.corner],
originalMouseUpHandler =
originalControl &&
originalControl.getMouseUpHandler(
e,
transform.target,
originalControl
);
pointer = pointer || this.getScenePoint(e);
originalMouseUpHandler &&
originalMouseUpHandler.call(
originalControl,
e,
transform,
pointer.x,
pointer.y
);
}
this._setCursorFromEvent(e, target);
this._handleEvent(e, 'up');
this._groupSelector = null;
this._currentTransform = null;
// reset the target information about which corner is selected
target && (target.__corner = undefined);
if (shouldRender) {
this.requestRenderAll();
} else if (!isClick && !(this._activeObject as IText)?.isEditing) {
this.renderTop();
}
}
_basicEventHandler<T extends keyof (CanvasEvents | ObjectEvents)>(
eventType: T,
options: (CanvasEvents & ObjectEvents)[T]
) {
const { target, subTargets = [] } = options as {
target?: FabricObject;
subTargets: FabricObject[];
};
this.fire(eventType, options);
target && target.fire(eventType, options);
for (let i = 0; i < subTargets.length; i++) {
subTargets[i] !== target && subTargets[i].fire(eventType, options);
}
return options;
}
/**
* @private
* Handle event firing for target and subtargets
* @param {TPointerEvent} e event from mouse
* @param {TPointerEventNames} eventType
*/
_handleEvent<T extends TPointerEventNames>(e: TPointerEvent, eventType: T) {
const target = this._target,
targets = this.targets || [],
options: CanvasEvents[`mouse:${T}`] = {
e,
target,
subTargets: targets,
...getEventPoints(this, e),
transform: this._currentTransform,
...(eventType === 'up:before' || eventType === 'up'
? {
isClick: this._isClick,
currentTarget: this.findTarget(e),
// set by the preceding `findTarget` call
currentSubTargets: this.targets,
}
: {}),
} as CanvasEvents[`mouse:${T}`];
this.fire(`mouse:${eventType}`, options);
// this may be a little be more complicated of what we want to handle
target && target.fire(`mouse${eventType}`, options);
for (let i = 0; i < targets.length; i++) {
targets[i] !== target && targets[i].fire(`mouse${eventType}`, options);
}
}
/**
* @private
* @param {Event} e Event object fired on mousedown
*/
_onMouseDownInDrawingMode(e: TPointerEvent) {
this._isCurrentlyDrawing = true;
if (this.getActiveObject()) {
this.discardActiveObject(e);
this.requestRenderAll();
}
// TODO: this is a scene point so it should be renamed
const pointer = this.getScenePoint(e);
this.freeDrawingBrush &&
this.freeDrawingBrush.onMouseDown(pointer, { e, pointer });
this._handleEvent(e, 'down');
}
/**
* @private
* @param {Event} e Event object fired on mousemove
*/
_onMouseMoveInDrawingMode(e: TPointerEvent) {
if (this._isCurrentlyDrawing) {
const pointer = this.getScenePoint(e);
this.freeDrawingBrush &&
this.freeDrawingBrush.onMouseMove(pointer, {
e,
// this is an absolute pointer, the naming is wrong
pointer,
});
}
this.setCursor(this.freeDrawingCursor);
this._handleEvent(e, 'move');
}
/**
* @private
* @param {Event} e Event object fired on mouseup
*/
_onMouseUpInDrawingMode(e: TPointerEvent) {
const pointer = this.getScenePoint(e);
if (this.freeDrawingBrush) {
this._isCurrentlyDrawing = !!this.freeDrawingBrush.onMouseUp({
e: e,
// this is an absolute pointer, the naming is wrong
pointer,
});
} else {
this._isCurrentlyDrawing = false;
}
this._handleEvent(e, 'up');
}
/**
* Method that defines the actions when mouse is clicked on canvas.
* The method inits the currentTransform parameters and renders all the
* canvas so the current image can be placed on the top canvas and the rest
* in on the container one.
* @private
* @param {Event} e Event object fired on mousedown
*/
__onMouseDown(e: TPointerEvent) {
this._isClick = true;
this._cacheTransformEventData(e);
this._handleEvent(e, 'down:before');
let target: FabricObject | undefined = this._target;
// if right/middle click just fire events
const { button } = e as MouseEvent;
if (button) {
((this.fireMiddleClick && button === 1) ||
(this.fireRightClick && button === 2)) &&
this._handleEvent(e, 'down');
this._resetTransformEventData();
return;
}