-
-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
canvas.class.ts
1520 lines (1400 loc) · 49.6 KB
/
canvas.class.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
//@ts-nocheck
import { dragHandler, getActionFromCorner } from './controls/actions';
import { Point } from './point.class';
import { FabricObject } from './shapes/fabricObject.class';
import { Transform } from './typedefs';
import { saveObjectTransform } from './util/misc/objectTransforms';
(function (global) {
var fabric = global.fabric,
getPointer = fabric.util.getPointer,
degreesToRadians = fabric.util.degreesToRadians,
isTouchEvent = fabric.util.isTouchEvent;
/**
* Canvas class
* @class fabric.Canvas
* @extends fabric.StaticCanvas
* @tutorial {@link http://fabricjs.com/fabric-intro-part-1#canvas}
* @see {@link fabric.Canvas#initialize} for constructor definition
*
* @fires object:modified at the end of a transform or any change when statefull is true
* @fires object:rotating while an object is being rotated from the control
* @fires object:scaling while an object is being scaled by controls
* @fires object:moving while an object is being dragged
* @fires object:skewing while an object is being skewed from the controls
*
* @fires before:transform before a transform is is started
* @fires before:selection:cleared
* @fires selection:cleared
* @fires selection:updated
* @fires selection:created
*
* @fires path:created after a drawing operation ends and the path is added
* @fires mouse:down
* @fires mouse:move
* @fires mouse:up
* @fires mouse:down:before on mouse down, before the inner fabric logic runs
* @fires mouse:move:before on mouse move, before the inner fabric logic runs
* @fires mouse:up:before on mouse up, before the inner fabric logic runs
* @fires mouse:over
* @fires mouse:out
* @fires mouse:dblclick whenever a native dbl click event fires on the canvas.
*
* @fires dragover
* @fires dragenter
* @fires dragleave
* @fires drag:enter object drag enter
* @fires drag:leave object drag leave
* @fires drop:before before drop event. Prepare for the drop event (same native event).
* @fires drop
* @fires drop:after after drop event. Run logic on canvas after event has been accepted/declined (same native event).
* @example
* let a: fabric.Object, b: fabric.Object;
* let flag = false;
* canvas.add(a, b);
* a.on('drop:before', opt => {
* // we want a to accept the drop even though it's below b in the stack
* flag = this.canDrop(opt.e);
* });
* b.canDrop = function(e) {
* !flag && this.callSuper('canDrop', e);
* }
* b.on('dragover', opt => b.set('fill', opt.dropTarget === b ? 'pink' : 'black'));
* a.on('drop', opt => {
* opt.e.defaultPrevented // drop occured
* opt.didDrop // drop occured on canvas
* opt.target // drop target
* opt.target !== a && a.set('text', 'I lost');
* });
* canvas.on('drop:after', opt => {
* // inform user who won
* if(!opt.e.defaultPrevented) {
* // no winners
* }
* else if(!opt.didDrop) {
* // my objects didn't win, some other lucky object
* }
* else {
* // we have a winner it's opt.target!!
* }
* })
*
* @fires after:render at the end of the render process, receives the context in the callback
* @fires before:render at start the render process, receives the context in the callback
*
* @fires contextmenu:before
* @fires contextmenu
* @example
* let handler;
* targets.forEach(target => {
* target.on('contextmenu:before', opt => {
* // decide which target should handle the event before canvas hijacks it
* if (someCaseHappens && opt.targets.includes(target)) {
* handler = target;
* }
* });
* target.on('contextmenu', opt => {
* // do something fantastic
* });
* });
* canvas.on('contextmenu', opt => {
* if (!handler) {
* // no one takes responsibility, it's always left to me
* // let's show them how it's done!
* }
* });
*
*/
fabric.Canvas = fabric.util.createClass(
fabric.StaticCanvas,
/** @lends fabric.Canvas.prototype */ {
/**
* Constructor
* @param {HTMLElement | String} el <canvas> element to initialize instance on
* @param {Object} [options] Options object
* @return {Object} thisArg
*/
initialize: function (el, options) {
options || (options = {});
this.renderAndResetBound = this.renderAndReset.bind(this);
this.requestRenderAllBound = this.requestRenderAll.bind(this);
this._initStatic(el, options);
this._initInteractive();
this._createCacheCanvas();
},
/**
* When true, objects can be transformed by one side (unproportionally)
* when dragged on the corners that normally would not do that.
* @type Boolean
* @default
* @since fabric 4.0 // changed name and default value
*/
uniformScaling: true,
/**
* Indicates which key switches uniform scaling.
* values: 'altKey', 'shiftKey', 'ctrlKey'.
* If `null` or 'none' or any other string that is not a modifier key
* feature is disabled.
* totally wrong named. this sounds like `uniform scaling`
* if Canvas.uniformScaling is true, pressing this will set it to false
* and viceversa.
* @since 1.6.2
* @type ModifierKey
* @default
*/
uniScaleKey: 'shiftKey',
/**
* When true, objects use center point as the origin of scale transformation.
* <b>Backwards incompatibility note:</b> This property replaces "centerTransform" (Boolean).
* @since 1.3.4
* @type Boolean
* @default
*/
centeredScaling: false,
/**
* When true, objects use center point as the origin of rotate transformation.
* <b>Backwards incompatibility note:</b> This property replaces "centerTransform" (Boolean).
* @since 1.3.4
* @type Boolean
* @default
*/
centeredRotation: false,
/**
* Indicates which key enable centered Transform
* values: 'altKey', 'shiftKey', 'ctrlKey'.
* If `null` or 'none' or any other string that is not a modifier key
* feature is disabled feature disabled.
* @since 1.6.2
* @type ModifierKey
* @default
*/
centeredKey: 'altKey',
/**
* Indicates which key enable alternate action on corner
* values: 'altKey', 'shiftKey', 'ctrlKey'.
* If `null` or 'none' or any other string that is not a modifier key
* feature is disabled feature disabled.
* @since 1.6.2
* @type ModifierKey
* @default
*/
altActionKey: 'shiftKey',
/**
* Indicates that canvas is interactive. This property should not be changed.
* @type Boolean
* @default
*/
interactive: true,
/**
* Indicates whether group selection should be enabled
* @type Boolean
* @default
*/
selection: true,
/**
* Indicates which key or keys enable multiple click selection
* Pass value as a string or array of strings
* values: 'altKey', 'shiftKey', 'ctrlKey'.
* If `null` or empty or containing any other string that is not a modifier key
* feature is disabled.
* @since 1.6.2
* @type ModifierKey|ModifierKey[]
* @default
*/
selectionKey: 'shiftKey',
/**
* Indicates which key enable alternative selection
* in case of target overlapping with active object
* values: 'altKey', 'shiftKey', 'ctrlKey'.
* For a series of reason that come from the general expectations on how
* things should work, this feature works only for preserveObjectStacking true.
* If `null` or 'none' or any other string that is not a modifier key
* feature is disabled.
* @since 1.6.5
* @type null|ModifierKey
* @default
*/
altSelectionKey: null,
/**
* Color of selection
* @type String
* @default
*/
selectionColor: 'rgba(100, 100, 255, 0.3)', // blue
/**
* Default dash array pattern
* If not empty the selection border is dashed
* @type Array
*/
selectionDashArray: [],
/**
* Color of the border of selection (usually slightly darker than color of selection itself)
* @type String
* @default
*/
selectionBorderColor: 'rgba(255, 255, 255, 0.3)',
/**
* Width of a line used in object/group selection
* @type Number
* @default
*/
selectionLineWidth: 1,
/**
* Select only shapes that are fully contained in the dragged selection rectangle.
* @type Boolean
* @default
*/
selectionFullyContained: false,
/**
* Default cursor value used when hovering over an object on canvas
* @type String
* @default
*/
hoverCursor: 'move',
/**
* Default cursor value used when moving an object on canvas
* @type String
* @default
*/
moveCursor: 'move',
/**
* Default cursor value used for the entire canvas
* @type String
* @default
*/
defaultCursor: 'default',
/**
* Cursor value used during free drawing
* @type String
* @default
*/
freeDrawingCursor: 'crosshair',
/**
* Cursor value used for disabled elements ( corners with disabled action )
* @type String
* @since 2.0.0
* @default
*/
notAllowedCursor: 'not-allowed',
/**
* Default element class that's given to wrapper (div) element of canvas
* @type String
* @default
*/
containerClass: 'canvas-container',
/**
* When true, object detection happens on per-pixel basis rather than on per-bounding-box
* @type Boolean
* @default
*/
perPixelTargetFind: false,
/**
* Number of pixels around target pixel to tolerate (consider active) during object detection
* @type Number
* @default
*/
targetFindTolerance: 0,
/**
* When true, target detection is skipped. Target detection will return always undefined.
* click selection won't work anymore, events will fire with no targets.
* if something is selected before setting it to true, it will be deselected at the first click.
* area selection will still work. check the `selection` property too.
* if you deactivate both, you should look into staticCanvas.
* @type Boolean
* @default
*/
skipTargetFind: false,
/**
* When true, mouse events on canvas (mousedown/mousemove/mouseup) result in free drawing.
* After mousedown, mousemove creates a shape,
* and then mouseup finalizes it and adds an instance of `fabric.Path` onto canvas.
* @tutorial {@link http://fabricjs.com/fabric-intro-part-4#free_drawing}
* @type Boolean
* @default
*/
isDrawingMode: false,
/**
* Indicates whether objects should remain in current stack position when selected.
* When false objects are brought to top and rendered as part of the selection group
* @type Boolean
* @default
*/
preserveObjectStacking: false,
/**
* Indicates if the right click on canvas can output the context menu or not
* @type Boolean
* @since 1.6.5
* @default
*/
stopContextMenu: false,
/**
* Indicates if the canvas can fire right click events
* @type Boolean
* @since 1.6.5
* @default
*/
fireRightClick: false,
/**
* Indicates if the canvas can fire middle click events
* @type Boolean
* @since 1.7.8
* @default
*/
fireMiddleClick: false,
/**
* Keep track of the subTargets for Mouse Events
* @type fabric.Object[]
*/
targets: [],
/**
* When the option is enabled, PointerEvent is used instead of MouseEvent.
* @type Boolean
* @default
*/
enablePointerEvents: false,
/**
* Keep track of the hovered target
* @type fabric.Object
* @private
*/
_hoveredTarget: null,
/**
* hold the list of nested targets hovered
* @type fabric.Object[]
* @private
*/
_hoveredTargets: [],
/**
* hold the list of objects to render
* @type fabric.Object[]
* @private
*/
_objectsToRender: undefined,
/**
* @private
*/
_initInteractive: function () {
this._currentTransform = null;
this._groupSelector = null;
this._initWrapperElement();
this._createUpperCanvas();
this._initEventListeners();
this._initRetinaScaling();
this.freeDrawingBrush =
fabric.PencilBrush && new fabric.PencilBrush(this);
this.calcOffset();
},
/**
* @private
* @param {fabric.Object} obj Object that was added
*/
_onObjectAdded: function (obj) {
this._objectsToRender = undefined;
this.callSuper('_onObjectAdded', obj);
},
/**
* @private
* @param {fabric.Object} obj Object that was removed
*/
_onObjectRemoved: function (obj) {
this._objectsToRender = undefined;
// removing active object should fire "selection:cleared" events
if (obj === this._activeObject) {
this.fire('before:selection:cleared', { target: obj });
this._discardActiveObject();
this.fire('selection:cleared', { target: obj });
obj.fire('deselected');
}
if (obj === this._hoveredTarget) {
this._hoveredTarget = null;
this._hoveredTargets = [];
}
this.callSuper('_onObjectRemoved', obj);
},
/**
* Divides objects in two groups, one to render immediately
* and one to render as activeGroup.
* @return {Array} objects to render immediately and pushes the other in the activeGroup.
*/
_chooseObjectsToRender: function () {
var activeObjects = this.getActiveObjects(),
object,
objsToRender,
activeGroupObjects;
if (!this.preserveObjectStacking && activeObjects.length > 1) {
objsToRender = [];
activeGroupObjects = [];
for (var i = 0, length = this._objects.length; i < length; i++) {
object = this._objects[i];
if (activeObjects.indexOf(object) === -1) {
objsToRender.push(object);
} else {
activeGroupObjects.push(object);
}
}
if (activeObjects.length > 1) {
this._activeObject._objects = activeGroupObjects;
}
objsToRender.push.apply(objsToRender, activeGroupObjects);
}
// in case a single object is selected render it's entire parent above the other objects
else if (!this.preserveObjectStacking && activeObjects.length === 1) {
var target = activeObjects[0],
ancestors = target.getAncestors(true);
var topAncestor = ancestors.length === 0 ? target : ancestors.pop();
objsToRender = this._objects.slice();
var index = objsToRender.indexOf(topAncestor);
index > -1 &&
objsToRender.splice(objsToRender.indexOf(topAncestor), 1);
objsToRender.push(topAncestor);
} else {
objsToRender = this._objects;
}
return objsToRender;
},
/**
* Renders both the top canvas and the secondary container canvas.
* @return {fabric.Canvas} instance
* @chainable
*/
renderAll: function () {
this.cancelRequestedRender();
if (this.destroyed) {
return;
}
if (
this.contextTopDirty &&
!this._groupSelector &&
!this.isDrawingMode
) {
this.clearContext(this.contextTop);
this.contextTopDirty = false;
}
if (this.hasLostContext) {
this.renderTopLayer(this.contextTop);
this.hasLostContext = false;
}
!this._objectsToRender &&
(this._objectsToRender = this._chooseObjectsToRender());
this.renderCanvas(this.contextContainer, this._objectsToRender);
return this;
},
renderTopLayer: function (ctx) {
ctx.save();
if (this.isDrawingMode && this._isCurrentlyDrawing) {
this.freeDrawingBrush && this.freeDrawingBrush._render();
this.contextTopDirty = true;
}
// we render the top context - last object
if (this.selection && this._groupSelector) {
this._drawSelection(ctx);
this.contextTopDirty = true;
}
ctx.restore();
},
/**
* Method to render only the top canvas.
* Also used to render the group selection box.
* @return {fabric.Canvas} thisArg
* @chainable
*/
renderTop: function () {
var ctx = this.contextTop;
this.clearContext(ctx);
this.renderTopLayer(ctx);
this.fire('after:render');
return this;
},
/**
* @private
*/
_normalizePointer: function (object, pointer) {
var m = object.calcTransformMatrix(),
invertedM = fabric.util.invertTransform(m),
vptPointer = this.restorePointerVpt(pointer);
return fabric.util.transformPoint(vptPointer, invertedM);
},
/**
* Returns true if object is transparent at a certain location
* @param {fabric.Object} target Object to check
* @param {Number} x Left coordinate
* @param {Number} y Top coordinate
* @return {Boolean}
*/
isTargetTransparent: function (target, x, y) {
// in case the target is the activeObject, we cannot execute this optimization
// because we need to draw controls too.
if (
target.shouldCache() &&
target._cacheCanvas &&
target !== this._activeObject
) {
var normalizedPointer = this._normalizePointer(target, {
x: x,
y: y,
}),
targetRelativeX = Math.max(
target.cacheTranslationX + normalizedPointer.x * target.zoomX,
0
),
targetRelativeY = Math.max(
target.cacheTranslationY + normalizedPointer.y * target.zoomY,
0
);
var isTransparent = fabric.util.isTransparent(
target._cacheContext,
Math.round(targetRelativeX),
Math.round(targetRelativeY),
this.targetFindTolerance
);
return isTransparent;
}
var ctx = this.contextCache,
originalColor = target.selectionBackgroundColor,
v = this.viewportTransform;
target.selectionBackgroundColor = '';
this.clearContext(ctx);
ctx.save();
ctx.transform(v[0], v[1], v[2], v[3], v[4], v[5]);
target.render(ctx);
ctx.restore();
target.selectionBackgroundColor = originalColor;
var isTransparent = fabric.util.isTransparent(
ctx,
x,
y,
this.targetFindTolerance
);
return isTransparent;
},
/**
* takes an event and determines if selection key has been pressed
* @private
* @param {Event} e Event object
*/
_isSelectionKeyPressed: function (e) {
var selectionKeyPressed = false;
if (Array.isArray(this.selectionKey)) {
selectionKeyPressed = !!this.selectionKey.find(function (key) {
return e[key] === true;
});
} else {
selectionKeyPressed = e[this.selectionKey];
}
return selectionKeyPressed;
},
/**
* @private
* @param {Event} e Event object
* @param {fabric.Object} target
*/
_shouldClearSelection: function (e, target) {
var activeObjects = this.getActiveObjects(),
activeObject = this._activeObject;
return (
!target ||
(target &&
activeObject &&
activeObjects.length > 1 &&
activeObjects.indexOf(target) === -1 &&
activeObject !== target &&
!this._isSelectionKeyPressed(e)) ||
(target && !target.evented) ||
(target &&
!target.selectable &&
activeObject &&
activeObject !== target)
);
},
/**
* centeredScaling from object can't override centeredScaling from canvas.
* this should be fixed, since object setting should take precedence over canvas.
* also this should be something that will be migrated in the control properties.
* as ability to define the origin of the transformation that the control provide.
* @private
* @param {fabric.Object} target
* @param {String} action
* @param {Boolean} altKey
*/
_shouldCenterTransform: function (target, action, altKey) {
if (!target) {
return;
}
var centerTransform;
if (
action === 'scale' ||
action === 'scaleX' ||
action === 'scaleY' ||
action === 'resizing'
) {
centerTransform = this.centeredScaling || target.centeredScaling;
} else if (action === 'rotate') {
centerTransform = this.centeredRotation || target.centeredRotation;
}
return centerTransform ? !altKey : altKey;
},
/**
* should disappear before release 4.0
* @private
*/
_getOriginFromCorner: function (target, corner) {
var origin = {
x: target.originX,
y: target.originY,
};
if (corner === 'ml' || corner === 'tl' || corner === 'bl') {
origin.x = 'right';
} else if (corner === 'mr' || corner === 'tr' || corner === 'br') {
origin.x = 'left';
}
if (corner === 'tl' || corner === 'mt' || corner === 'tr') {
origin.y = 'bottom';
} else if (corner === 'bl' || corner === 'mb' || corner === 'br') {
origin.y = 'top';
}
return origin;
},
/**
* @private
* @param {Event} e Event object
* @param {fabric.Object} target
*/
_setupCurrentTransform: function (e, target, alreadySelected) {
if (!target) {
return;
}
var pointer = this.getPointer(e);
if (target.group) {
// transform pointer to target's containing coordinate plane
pointer = fabric.util.transformPoint(
pointer,
fabric.util.invertTransform(target.group.calcTransformMatrix())
);
}
var corner = target.__corner,
control = target.controls[corner],
actionHandler =
alreadySelected && corner
? control.getActionHandler(e, target, control)
: dragHandler,
action = getActionFromCorner(alreadySelected, corner, e, target),
origin = this._getOriginFromCorner(target, corner),
altKey = e[this.centeredKey],
/**
* relative to target's containing coordinate plane
* both agree on every point
**/
transform: Transform = {
target: target,
action: action,
actionHandler: actionHandler,
corner: corner,
scaleX: target.scaleX,
scaleY: target.scaleY,
skewX: target.skewX,
skewY: target.skewY,
offsetX: pointer.x - target.left,
offsetY: pointer.y - target.top,
originX: origin.x,
originY: origin.y,
ex: pointer.x,
ey: pointer.y,
lastX: pointer.x,
lastY: pointer.y,
theta: degreesToRadians(target.angle),
width: target.width,
height: target.height,
shiftKey: e.shiftKey,
altKey: altKey,
original: saveObjectTransform(target),
};
if (this._shouldCenterTransform(target, action, altKey)) {
transform.originX = 'center';
transform.originY = 'center';
}
transform.original.originX = origin.x;
transform.original.originY = origin.y;
this._currentTransform = transform;
this._beforeTransform(e);
},
/**
* Set the cursor type of the canvas element
* @param {String} value Cursor type of the canvas element.
* @see http://www.w3.org/TR/css3-ui/#cursor
*/
setCursor: function (value) {
this.upperCanvasEl.style.cursor = value;
},
/**
* @private
* @param {CanvasRenderingContext2D} ctx to draw the selection on
*/
_drawSelection: function (ctx) {
var selector = this._groupSelector,
viewportStart = new Point(selector.ex, selector.ey),
start = fabric.util.transformPoint(
viewportStart,
this.viewportTransform
),
viewportExtent = new Point(
selector.ex + selector.left,
selector.ey + selector.top
),
extent = fabric.util.transformPoint(
viewportExtent,
this.viewportTransform
),
minX = Math.min(start.x, extent.x),
minY = Math.min(start.y, extent.y),
maxX = Math.max(start.x, extent.x),
maxY = Math.max(start.y, extent.y),
strokeOffset = this.selectionLineWidth / 2;
if (this.selectionColor) {
ctx.fillStyle = this.selectionColor;
ctx.fillRect(minX, minY, maxX - minX, maxY - minY);
}
if (!this.selectionLineWidth || !this.selectionBorderColor) {
return;
}
ctx.lineWidth = this.selectionLineWidth;
ctx.strokeStyle = this.selectionBorderColor;
minX += strokeOffset;
minY += strokeOffset;
maxX -= strokeOffset;
maxY -= strokeOffset;
// selection border
FabricObject.prototype._setLineDash.call(
this,
ctx,
this.selectionDashArray
);
ctx.strokeRect(minX, minY, maxX - minX, maxY - minY);
},
/**
* Method that determines what object we are clicking on
* the skipGroup parameter is for internal use, is needed for shift+click action
* 11/09/2018 TODO: would be cool if findTarget could discern between being a full target
* or the outside part of the corner.
* @param {Event} e mouse event
* @param {Boolean} skipGroup when true, activeGroup is skipped and only objects are traversed through
* @return {fabric.Object} the target found
*/
findTarget: function (e, skipGroup) {
if (this.skipTargetFind) {
return;
}
var ignoreZoom = true,
pointer = this.getPointer(e, ignoreZoom),
activeObject = this._activeObject,
aObjects = this.getActiveObjects(),
activeTarget,
activeTargetSubs,
isTouch = isTouchEvent(e),
shouldLookForActive =
(aObjects.length > 1 && !skipGroup) || aObjects.length === 1;
// first check current group (if one exists)
// active group does not check sub targets like normal groups.
// if active group just exits.
this.targets = [];
// if we hit the corner of an activeObject, let's return that.
if (
shouldLookForActive &&
activeObject._findTargetCorner(pointer, isTouch)
) {
return activeObject;
}
if (
aObjects.length > 1 &&
activeObject.type === 'activeSelection' &&
!skipGroup &&
this.searchPossibleTargets([activeObject], pointer)
) {
return activeObject;
}
if (
aObjects.length === 1 &&
activeObject === this.searchPossibleTargets([activeObject], pointer)
) {
if (!this.preserveObjectStacking) {
return activeObject;
} else {
activeTarget = activeObject;
activeTargetSubs = this.targets;
this.targets = [];
}
}
var target = this.searchPossibleTargets(this._objects, pointer);
if (
e[this.altSelectionKey] &&
target &&
activeTarget &&
target !== activeTarget
) {
target = activeTarget;
this.targets = activeTargetSubs;
}
return target;
},
/**
* Checks point is inside the object.
* @param {Object} [pointer] x,y object of point coordinates we want to check.
* @param {fabric.Object} obj Object to test against
* @param {Object} [globalPointer] x,y object of point coordinates relative to canvas used to search per pixel target.
* @return {Boolean} true if point is contained within an area of given object
* @private
*/
_checkTarget: function (pointer, obj, globalPointer) {
if (
obj &&
obj.visible &&
obj.evented &&
// http://www.geog.ubc.ca/courses/klink/gis.notes/ncgia/u32.html
// http://idav.ucdavis.edu/~okreylos/TAship/Spring2000/PointInPolygon.html
obj.containsPoint(pointer)
) {
if (
(this.perPixelTargetFind || obj.perPixelTargetFind) &&
!obj.isEditing
) {
var isTransparent = this.isTargetTransparent(
obj,
globalPointer.x,
globalPointer.y
);
if (!isTransparent) {
return true;
}
} else {
return true;
}
}
},
/**
* Internal Function used to search inside objects an object that contains pointer in bounding box or that contains pointerOnCanvas when painted
* @param {Array} [objects] objects array to look into
* @param {Object} [pointer] x,y object of point coordinates we want to check.
* @return {fabric.Object} **top most object from given `objects`** that contains pointer
* @private
*/
_searchPossibleTargets: function (objects, pointer) {
// Cache all targets where their bounding box contains point.
var target,
i = objects.length,
subTarget;
// Do not check for currently grouped objects, since we check the parent group itself.
// until we call this function specifically to search inside the activeGroup
while (i--) {
var objToCheck = objects[i];
var pointerToUse = objToCheck.group
? this._normalizePointer(objToCheck.group, pointer)
: pointer;
if (this._checkTarget(pointerToUse, objToCheck, pointer)) {
target = objects[i];
if (target.subTargetCheck && Array.isArray(target._objects)) {
subTarget = this._searchPossibleTargets(target._objects, pointer);
subTarget && this.targets.push(subTarget);
}
break;
}
}
return target;
},
/**
* Function used to search inside objects an object that contains pointer in bounding box or that contains pointerOnCanvas when painted
* @see {@link fabric.Canvas#_searchPossibleTargets}
* @param {Array} [objects] objects array to look into
* @param {Object} [pointer] x,y object of point coordinates we want to check.
* @return {fabric.Object} **top most object on screen** that contains pointer
*/
searchPossibleTargets: function (objects, pointer) {
var target = this._searchPossibleTargets(objects, pointer);
return target && target.interactive && this.targets[0]
? this.targets[0]
: target;
},
/**
* Returns pointer coordinates without the effect of the viewport