-
Notifications
You must be signed in to change notification settings - Fork 0
/
eraser.js
1012 lines (942 loc) · 33.1 KB
/
eraser.js
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 { fabric } from 'fabric';
(function () {
/** ERASER_START */
var __setBgOverlayColor = fabric.StaticCanvas.prototype.__setBgOverlayColor;
var ___setBgOverlay = fabric.StaticCanvas.prototype.__setBgOverlay;
var __setSVGBgOverlayColor =
fabric.StaticCanvas.prototype._setSVGBgOverlayColor;
fabric.util.object.extend(fabric.StaticCanvas.prototype, {
backgroundColor: undefined,
overlayColor: undefined,
/**
* Create Rect that holds the color to support erasing
* patches {@link CommonMethods#_initGradient}
* @private
* @param {'background'|'overlay'} property
* @param {(String|fabric.Pattern|fabric.Rect)} color Color or pattern or rect (in case of erasing)
* @param {Function} callback Callback to invoke when color is set
* @param {Object} options
* @return {fabric.Canvas} instance
* @chainable true
*/
__setBgOverlayColor: function (property, color, callback, options) {
if (color && color.isType && color.isType("rect")) {
// color is already an object
this[property] = color;
color.set(options);
callback && callback(this[property]);
} else {
var _this = this;
var cb = function () {
_this[property] = new fabric.Rect(
fabric.util.object.extend(
{
width: _this.width,
height: _this.height,
fill: _this[property]
},
options
)
);
callback && callback(_this[property]);
};
__setBgOverlayColor.call(this, property, color, cb);
// invoke cb in case of gradient
// see {@link CommonMethods#_initGradient}
if (color && color.colorStops && !(color instanceof fabric.Gradient)) {
cb();
}
}
return this;
},
setBackgroundColor: function (backgroundColor, callback, options) {
return this.__setBgOverlayColor(
"backgroundColor",
backgroundColor,
callback,
options
);
},
setOverlayColor: function (overlayColor, callback, options) {
return this.__setBgOverlayColor(
"overlayColor",
overlayColor,
callback,
options
);
},
/**
* patch serialization - from json
* background/overlay properties could be objects if parsed by this mixin or could be legacy values
* @private
* @param {String} property Property to set (backgroundImage, overlayImage, backgroundColor, overlayColor)
* @param {(Object|String)} value Value to set
* @param {Object} loaded Set loaded property to true if property is set
* @param {Object} callback Callback function to invoke after property is set
*/
__setBgOverlay: function (property, value, loaded, callback) {
var _this = this;
if (
(property === "backgroundColor" || property === "overlayColor") &&
value &&
typeof value === "object" &&
value.type === "rect"
) {
fabric.util.enlivenObjects([value], function (enlivedObject) {
_this[property] = enlivedObject[0];
loaded[property] = true;
callback && callback();
});
} else {
___setBgOverlay.call(this, property, value, loaded, callback);
}
},
/**
* patch serialization - to svg
* background/overlay properties could be objects if parsed by this mixin or could be legacy values
* @private
*/
_setSVGBgOverlayColor: function (markup, property, reviver) {
var filler = this[property + "Color"];
if (filler && filler.isType && filler.isType("rect")) {
var excludeFromExport =
filler.excludeFromExport ||
(this[property] && this[property].excludeFromExport);
if (filler && !excludeFromExport && filler.toSVG) {
markup.push(filler.toSVG(reviver));
}
} else {
__setSVGBgOverlayColor.call(this, markup, property, reviver);
}
},
/**
* @private
* @param {CanvasRenderingContext2D} ctx Context to render on
* @param {string} property 'background' or 'overlay'
*/
_renderBackgroundOrOverlay: function (ctx, property) {
var fill = this[property + "Color"],
object = this[property + "Image"],
v = this.viewportTransform,
needsVpt = this[property + "Vpt"];
if (!fill && !object) {
return;
}
if (fill || object) {
ctx.save();
fill && fill.render(ctx);
if (needsVpt) {
ctx.transform(v[0], v[1], v[2], v[3], v[4], v[5]);
}
object && object.render(ctx);
ctx.restore();
}
}
});
var _toObject = fabric.Object.prototype.toObject;
var __createBaseSVGMarkup = fabric.Object.prototype._createBaseSVGMarkup;
fabric.util.object.extend(fabric.Object.prototype, {
/**
* Indicates whether this object can be erased by {@link fabric.EraserBrush}
* The `deep` option introduces fine grained control over a group's `erasable` property.
* When set to `deep` the eraser will erase nested objects if they are erasable, leaving the group and the other objects untouched.
* When set to `true` the eraser will erase the entire group. Once the group changes the eraser is propagated to its children for proper functionality.
* When set to `false` the eraser will leave all objects including the group untouched.
* @tutorial {@link http://fabricjs.com/erasing#erasable_property}
* @type boolean | 'deep'
* @default true
*/
erasable: true,
/**
*
* @returns {fabric.Group | undefined}
*/
getEraser: function () {
return this.clipPath && this.clipPath.eraser ? this.clipPath : undefined;
},
/**
* Get the object's actual clip path regardless of clipping done by erasing
* @returns {fabric.Object | undefined}
*/
getClipPath: function () {
var eraser = this.getEraser();
return eraser ? eraser._objects[0].clipPath : this.clipPath;
},
/**
* Set the object's actual clip path regardless of clipping done by erasing
* @param {fabric.Object} [clipPath]
*/
setClipPath: function (clipPath) {
var eraser = this.getEraser();
var target = eraser ? eraser._objects[0] : this;
target.set("clipPath", clipPath);
this.set("dirty", true);
},
/**
* Returns an object representation of an instance
* @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
* @return {Object} Object representation of an instance
*/
toObject: function (additionalProperties) {
return _toObject.call(this, ["erasable"].concat(additionalProperties));
},
/**
* use <mask> to achieve erasing for svg
* credit: https://travishorn.com/removing-parts-of-shapes-in-svg-b539a89e5649
* @param {Function} reviver
* @returns {string} markup
*/
eraserToSVG: function (options) {
var eraser = this.getEraser();
if (eraser) {
var fill = eraser._objects[0].fill;
eraser._objects[0].fill = "white";
eraser.clipPathId = "CLIPPATH_" + fabric.Object.__uid++;
var commons = [
'id="' + eraser.clipPathId + '"'
/*options.additionalTransform ? ' transform="' + options.additionalTransform + '" ' : ''*/
].join(" ");
var objectMarkup = [
"<defs>",
"<mask " + commons + " >",
eraser.toSVG(options.reviver),
"</mask>",
"</defs>"
];
eraser._objects[0].fill = fill;
return objectMarkup.join("\n");
}
return "";
},
/**
* use <mask> to achieve erasing for svg, override <clipPath>
* @param {string[]} objectMarkup
* @param {Object} options
* @returns
*/
_createBaseSVGMarkup: function (objectMarkup, options) {
var eraser = this.getEraser();
if (eraser) {
var eraserMarkup = this.eraserToSVG(options);
this.clipPath = null;
var markup = __createBaseSVGMarkup.call(this, objectMarkup, options);
this.clipPath = eraser;
return [
eraserMarkup,
markup.replace(">", 'mask="url(#' + eraser.clipPathId + ')" >')
].join("\n");
} else {
return __createBaseSVGMarkup.call(this, objectMarkup, options);
}
}
});
var __restoreObjectsState = fabric.Group.prototype._restoreObjectsState;
var _groupToObject = fabric.Group.prototype.toObject;
var __getBounds = fabric.Group.prototype._getBounds;
fabric.util.object.extend(fabric.Group.prototype, {
/**
* If group is an eraser then dimensions should not change when paths are added or removed and should remain the size of the base rect
* @private
*/
_getBounds: function (aX, aY, onlyWidthHeight) {
if (this.eraser) {
this.width = this._objects[0].width;
this.height = this._objects[0].height;
return;
}
__getBounds.call(this, aX, aY, onlyWidthHeight);
},
/**
* @private
* @param {fabric.Path} path
*/
_addEraserPathToObjects: function (path) {
this._objects.forEach(function (object) {
fabric.EraserBrush.prototype._addPathToObjectEraser.call(
fabric.EraserBrush.prototype,
object,
path
);
});
},
/**
* Applies the group's eraser to its objects
* @tutorial {@link http://fabricjs.com/erasing#erasable_property}
*/
applyEraserToObjects: function () {
var _this = this;
if (this.erasable === true && this.getEraser()) {
var transform = _this.calcTransformMatrix();
_this.getEraser().clone(function (eraser) {
var clipPath = eraser._objects[0].clipPath;
_this.clipPath = clipPath ? clipPath : undefined;
eraser.getObjects("path").forEach(function (path) {
// first we transform the path from the group's coordinate system to the canvas'
var originalTransform = fabric.util.multiplyTransformMatrices(
transform,
path.calcTransformMatrix()
);
fabric.util.applyTransformToObject(path, originalTransform);
if (clipPath) {
clipPath.clone(function (_clipPath) {
fabric.EraserBrush.prototype.applyClipPathToPath.call(
fabric.EraserBrush.prototype,
path,
_clipPath,
transform
);
_this._addEraserPathToObjects(path);
});
} else {
_this._addEraserPathToObjects(path);
}
});
});
}
},
/**
* Propagate the group's eraser to its objects, crucial for proper functionality of the eraser within the group and nested objects.
* @private
*/
_restoreObjectsState: function () {
this.applyEraserToObjects();
return __restoreObjectsState.call(this);
},
/**
* Returns an object representation of an instance
* @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
* @return {Object} Object representation of an instance
*/
toObject: function (additionalProperties) {
return _groupToObject.call(this, ["eraser"].concat(additionalProperties));
}
});
var __onResize = fabric.Canvas.prototype._onResize;
fabric.util.object.extend(fabric.Canvas.prototype, {
/**
* Used by {@link #renderAll}
* @returns boolean
*/
isErasing: function () {
return (
this.isDrawingMode &&
this.freeDrawingBrush &&
this.freeDrawingBrush.type === "eraser" &&
this.freeDrawingBrush._isErasing
);
},
_onResize: function () {
__onResize.call(this);
if (this.backgroundColor) {
this.backgroundColor.set({
width: this.getWidth(),
height: this.getHeight()
});
this.backgroundColor.setPositionByOrigin(
new fabric.Point(0, 0),
"center",
"center"
);
}
if (this.overlayColor) {
/*
var clipPath = this.overlayColor.clipPath;
this.setOverlayColor(this.overlayColor.fill);
this.overlayColor.clipPath = clipPath;
*/
/*
*/
var size = this.overlayColor.getBoundingRect();
var newSize = { width: this.getWidth(), height: this.getHeight() };
var delta = {
x: size.width - newSize.width,
y: size.height - newSize.height
};
var absCenter = new fabric.Point(size.width / 2, size.height / 2);
var absNewCenter = new fabric.Point(
newSize.width / 2,
newSize.height / 2
);
var offset = new fabric.Point(delta.x / 2, delta.y / 2);
var overlayColor = this.overlayColor;
overlayColor.set(newSize);
var eraser = this.overlayColor.getEraser();
if (eraser) {
var paths = eraser.getObjects("path");
//eraser._restoreObjectsState();
eraser.set(newSize);
eraser._objects[0].set(newSize);
eraser.setPositionByOrigin(
new fabric.Point(0, 0),
"center",
"center"
);
/*
paths.forEach(function (path) {
eraser.removeWithUpdate(path);
}); /*
eraser.set(newSize);
eraser._objects[0].set(newSize);
eraser.setPositionByOrigin(
new fabric.Point(0, 0),
"center",
"center"
);*/
//delete overlayColor.clipPath;
paths.forEach(function (path, index) {
/*
fabric.EraserBrush.prototype._addPathToObjectEraser.call(
fabric.EraserBrush.prototype,
overlayColor,
path
);
/*
path.setPositionByOrigin(
new fabric.Point(0, 0),
"center",
"center"
);
*/
});
}
//fabric.util.resetObjectTransform(this.overlayColor);
/*
fabric.util.applyTransformToObject(
this.overlayColor,
fabric.util.multiplyTransformMatrices(
this.viewportTransform,
this.overlayColor.calcTransformMatrix()
)
);*/
//var center = this.getCenter();
/*
this.overlayColor.setPositionByOrigin(
new fabric.Point(center.left, 0),
"center",
"center"
);
*/
}
this.renderAll();
},
/**
* While erasing, the brush is in charge of rendering the canvas
* It uses both layers to achieve diserd erasing effect
*
* @returns fabric.Canvas
*/
renderAll: function () {
if (this.contextTopDirty && !this._groupSelector && !this.isDrawingMode) {
this.clearContext(this.contextTop);
this.contextTopDirty = false;
}
// while erasing the brush is in charge of rendering the canvas so we return
if (this.isErasing()) {
this.freeDrawingBrush._render();
return;
}
if (this.hasLostContext) {
this.renderTopLayer(this.contextTop);
}
var canvasToDrawOn = this.contextContainer;
this.renderCanvas(canvasToDrawOn, this._chooseObjectsToRender());
return this;
}
});
/**
* EraserBrush class
* Supports selective erasing meaning that only erasable objects are affected by the eraser brush.
* In order to support selective erasing all non erasable objects are rendered on the main/bottom ctx
* while the entire canvas is rendered on the top ctx.
* Canvas background/overlay image/color are handled as well.
* When erasing occurs, the path clips the top ctx and reveals the bottom ctx.
* This achieves the desired effect of seeming to erase only erasable objects.
* After erasing is done the created path is added to all intersected objects' `clipPath` property.
*
* @tutorial {@link http://fabricjs.com/erasing}
* @class fabric.EraserBrush
* @extends fabric.PencilBrush
*/
fabric.EraserBrush = fabric.util.createClass(
fabric.PencilBrush,
/** @lends fabric.EraserBrush.prototype */ {
type: "eraser",
/**
* Indicates that the ctx is ready and rendering can begin.
* Used to prevent a race condition caused by {@link fabric.EraserBrush#onMouseMove} firing before {@link fabric.EraserBrush#onMouseDown} has completed
*
* @private
*/
_ready: false,
/**
* @private
*/
_drawOverlayOnTop: false,
/**
* @private
*/
_isErasing: false,
initialize: function (canvas) {
this.callSuper("initialize", canvas);
this._renderBound = this._render.bind(this);
this.render = this.render.bind(this);
},
/**
* Used to hide a drawable from the rendering process
* @param {fabric.Object} object
*/
hideObject: function (object) {
if (object) {
object._originalOpacity = object.opacity;
object.set({ opacity: 0 });
}
},
/**
* Restores hiding an object
* {@link fabric.EraserBrush#hideObject}
* @param {fabric.Object} object
*/
restoreObjectVisibility: function (object) {
if (object && object._originalOpacity) {
object.set({ opacity: object._originalOpacity });
object._originalOpacity = undefined;
}
},
/**
*
* @private
* @param {fabric.Object} object
* @returns boolean
*/
_isErasable: function (object) {
return object.erasable !== false;
},
/**
* Drawing Logic For background drawables: (`backgroundImage`, `backgroundColor`)
* 1. if erasable = true:
* we need to hide the drawable on the bottom ctx so when the brush is erasing it will clip the top ctx and reveal white space underneath
* 2. if erasable = false:
* we need to draw the drawable only on the bottom ctx so the brush won't affect it
* @param {'bottom' | 'top' | 'overlay'} layer
*/
prepareCanvasBackgroundForLayer: function (layer) {
if (layer === "overlay") {
return;
}
var canvas = this.canvas;
var image = canvas.get("backgroundImage");
var color = canvas.get("backgroundColor");
var erasablesOnLayer = layer === "top";
if (image && this._isErasable(image) === !erasablesOnLayer) {
this.hideObject(image);
}
if (color && this._isErasable(color) === !erasablesOnLayer) {
this.hideObject(color);
}
},
/**
* Drawing Logic For overlay drawables (`overlayImage`, `overlayColor`)
* We must draw on top ctx to be on top of visible canvas
* 1. if erasable = true:
* we need to draw the drawable on the top ctx as a normal object
* 2. if erasable = false:
* we need to draw the drawable on top of the brush,
* this means we need to repaint for every stroke
*
* @param {'bottom' | 'top' | 'overlay'} layer
* @returns boolean render overlay above brush
*/
prepareCanvasOverlayForLayer: function (layer) {
var canvas = this.canvas;
var image = canvas.get("overlayImage");
var color = canvas.get("overlayColor");
if (layer === "bottom") {
this.hideObject(image);
this.hideObject(color);
return false;
}
var erasablesOnLayer = layer === "top";
var renderOverlayOnTop =
(image && !this._isErasable(image)) ||
(color && !this._isErasable(color));
if (image && this._isErasable(image) === !erasablesOnLayer) {
this.hideObject(image);
}
if (color && this._isErasable(color) === !erasablesOnLayer) {
this.hideObject(color);
}
return renderOverlayOnTop;
},
/**
* @private
*/
restoreCanvasDrawables: function () {
var canvas = this.canvas;
this.restoreObjectVisibility(canvas.get("backgroundImage"));
this.restoreObjectVisibility(canvas.get("backgroundColor"));
this.restoreObjectVisibility(canvas.get("overlayImage"));
this.restoreObjectVisibility(canvas.get("overlayColor"));
},
/**
* @private
* This is designed to support erasing a group with both erasable and non-erasable objects.
* Iterates over collections to allow nested selective erasing.
* Used by {@link fabric.EraserBrush#prepareCanvasObjectsForLayer}
* to prepare the bottom layer by hiding erasable nested objects
*
* @param {fabric.Collection} collection
*/
prepareCollectionTraversal: function (collection) {
var _this = this;
collection.forEachObject(function (obj) {
if (obj.forEachObject && obj.erasable === "deep") {
_this.prepareCollectionTraversal(obj);
} else if (obj.erasable) {
_this.hideObject(obj);
}
});
},
/**
* @private
* Used by {@link fabric.EraserBrush#prepareCanvasObjectsForLayer}
* to reverse the action of {@link fabric.EraserBrush#prepareCollectionTraversal}
*
* @param {fabric.Collection} collection
*/
restoreCollectionTraversal: function (collection) {
var _this = this;
collection.forEachObject(function (obj) {
if (obj.forEachObject && obj.erasable === "deep") {
_this.restoreCollectionTraversal(obj);
} else {
_this.restoreObjectVisibility(obj);
}
});
},
/**
* @private
* This is designed to support erasing a group with both erasable and non-erasable objects.
*
* @param {'bottom' | 'top' | 'overlay'} layer
*/
prepareCanvasObjectsForLayer: function (layer) {
if (layer !== "bottom") {
return;
}
this.prepareCollectionTraversal(this.canvas);
},
/**
* @private
* @param {'bottom' | 'top' | 'overlay'} layer
*/
restoreCanvasObjectsFromLayer: function (layer) {
if (layer !== "bottom") {
return;
}
this.restoreCollectionTraversal(this.canvas);
},
/**
* @private
* @param {'bottom' | 'top' | 'overlay'} layer
* @returns boolean render overlay above brush
*/
prepareCanvasForLayer: function (layer) {
this.prepareCanvasBackgroundForLayer(layer);
this.prepareCanvasObjectsForLayer(layer);
return this.prepareCanvasOverlayForLayer(layer);
},
/**
* @private
* @param {'bottom' | 'top' | 'overlay'} layer
*/
restoreCanvasFromLayer: function (layer) {
this.restoreCanvasDrawables();
this.restoreCanvasObjectsFromLayer(layer);
},
/**
* Render all non-erasable objects on bottom layer with the exception of overlays to avoid being clipped by the brush.
* Groups are rendered for nested selective erasing, non-erasable objects are visible while erasable objects are not.
*/
renderBottomLayer: function () {
var canvas = this.canvas;
this.prepareCanvasForLayer("bottom");
canvas.renderCanvas(
canvas.getContext(),
canvas.getObjects().filter(function (obj) {
return !obj.erasable || obj.isType("group");
})
);
this.restoreCanvasFromLayer("bottom");
},
/**
* 1. Render all objects on top layer, erasable and non-erasable
* This is important for cases such as overlapping objects, the background object erasable and the foreground object not erasable.
* 2. Render the brush
*/
renderTopLayer: function () {
var canvas = this.canvas;
this._drawOverlayOnTop = this.prepareCanvasForLayer("top");
canvas.renderCanvas(canvas.contextTop, canvas.getObjects());
this.callSuper("_render");
this.restoreCanvasFromLayer("top");
},
/**
* Render all non-erasable overlays on top of the brush so that they won't get erased
*/
renderOverlay: function () {
this.prepareCanvasForLayer("overlay");
var canvas = this.canvas;
var ctx = canvas.contextTop;
this._saveAndTransform(ctx);
canvas._renderOverlay(ctx);
ctx.restore();
this.restoreCanvasFromLayer("overlay");
},
/**
* @extends @class fabric.BaseBrush
* @param {CanvasRenderingContext2D} ctx
*/
_saveAndTransform: function (ctx) {
this.callSuper("_saveAndTransform", ctx);
ctx.globalCompositeOperation = "destination-out";
},
/**
* We indicate {@link fabric.PencilBrush} to repaint itself if necessary
* @returns
*/
needsFullRender: function () {
return this.callSuper("needsFullRender") || this._drawOverlayOnTop;
},
/**
*
* @param {fabric.Point} pointer
* @param {fabric.IEvent} options
* @returns
*/
onMouseDown: function (pointer, options) {
if (!this.canvas._isMainEvent(options.e)) {
return;
}
this._prepareForDrawing(pointer);
// capture coordinates immediately
// this allows to draw dots (when movement never occurs)
this._captureDrawingPath(pointer);
this._isErasing = true;
this.canvas.fire("erasing:start");
this._ready = true;
this._render();
},
/**
* Rendering is done in 4 steps:
* 1. Draw all non-erasable objects on bottom ctx with the exception of overlays {@link fabric.EraserBrush#renderBottomLayer}
* 2. Draw all objects on top ctx including erasable drawables {@link fabric.EraserBrush#renderTopLayer}
* 3. Draw eraser {@link fabric.PencilBrush#_render} at {@link fabric.EraserBrush#renderTopLayer}
* 4. Draw non-erasable overlays {@link fabric.EraserBrush#renderOverlay}
*
* @param {fabric.Canvas} canvas
*/
_render: function () {
if (!this._ready) {
return;
}
this.isRendering = 1;
this.renderBottomLayer();
this.renderTopLayer();
this.renderOverlay();
this.isRendering = 0;
},
/**
* @public
*/
render: function () {
if (this._isErasing) {
if (this.isRendering) {
this.isRendering = fabric.util.requestAnimFrame(this._renderBound);
} else {
this._render();
}
return true;
}
return false;
},
/**
* Utility to apply a clip path to a path.
* Used to preserve clipping on eraser paths in nested objects.
* Called when a group has a clip path that should be applied to the path before applying erasing on the group's objects.
* @param {fabric.Path} path The eraser path
* @param {fabric.Object} clipPath The clipPath to apply to the path
* @param {number[]} clipPathContainerTransformMatrix The transform matrix of the object that the clip path belongs to
* @returns {fabric.Path} path with clip path
*/
applyClipPathToPath: function (
path,
clipPath,
clipPathContainerTransformMatrix
) {
var pathTransform = path.calcTransformMatrix();
var clipPathTransform = clipPath.calcTransformMatrix();
var transform = fabric.util.multiplyTransformMatrices(
fabric.util.invertTransform(pathTransform),
clipPathContainerTransformMatrix
);
fabric.util.applyTransformToObject(
clipPath,
fabric.util.multiplyTransformMatrices(transform, clipPathTransform)
);
path.clipPath = clipPath;
return path;
},
/**
* Utility to apply a clip path to a path.
* Used to preserve clipping on eraser paths in nested objects.
* Called when a group has a clip path that should be applied to the path before applying erasing on the group's objects.
* @param {fabric.Path} path The eraser path
* @param {fabric.Object} object The clipPath to apply to path belongs to object
* @param {Function} callback Callback to be invoked with the cloned path after applying the clip path
*/
clonePathWithClipPath: function (path, object, callback) {
var objTransform = object.calcTransformMatrix();
var clipPath = object.getClipPath();
var _this = this;
path.clone(function (_path) {
clipPath.clone(function (_clipPath) {
callback(_this.applyClipPathToPath(_path, _clipPath, objTransform));
});
});
},
/**
* Adds path to existing clipPath of object
*
* @param {fabric.Object} obj
* @param {fabric.Path} path
*/
_addPathToObjectEraser: function (obj, path) {
var clipObject;
var _this = this;
// object is collection, i.e group
if (obj.forEachObject && obj.erasable === "deep") {
var targets = obj._objects.filter(function (_obj) {
return _obj.erasable;
});
if (targets.length > 0 && obj.clipPath) {
this.clonePathWithClipPath(path, obj, function (_path) {
targets.forEach(function (_obj) {
_this._addPathToObjectEraser(_obj, _path);
});
});
} else if (targets.length > 0) {
targets.forEach(function (_obj) {
_this._addPathToObjectEraser(_obj, path);
});
}
return;
}
if (!obj.getEraser()) {
var size = obj._getNonTransformedDimensions();
var rect = new fabric.Rect({
width: size.x,
height: size.y,
clipPath: obj.clipPath,
originX: "center",
originY: "center"
});
clipObject = new fabric.Group([rect], {
eraser: true
});
} else {
clipObject = obj.clipPath;
}
path.clone(function (path) {
path.globalCompositeOperation = "destination-out";
// http://fabricjs.com/using-transformations
var desiredTransform = fabric.util.multiplyTransformMatrices(
fabric.util.invertTransform(obj.calcTransformMatrix()),
path.calcTransformMatrix()
);
fabric.util.applyTransformToObject(path, desiredTransform);
clipObject.addWithUpdate(path);
obj.set({
clipPath: clipObject,
dirty: true
});
});
},
/**
* Add the eraser path to canvas drawables' clip paths
*
* @param {fabric.Canvas} source
* @param {fabric.Canvas} path
* @returns {Object} canvas drawables that were erased by the path
*/
applyEraserToCanvas: function (path) {
var canvas = this.canvas;
var drawables = {};
[
"backgroundImage",
"backgroundColor",
"overlayImage",
"overlayColor"
].forEach(function (prop) {
var drawable = canvas[prop];
if (drawable && drawable.erasable) {
this._addPathToObjectEraser(drawable, path);
drawables[prop] = drawable;
}
}, this);
return drawables;
},
/**
* On mouseup after drawing the path on contextTop canvas
* we use the points captured to create an new fabric path object
* and add it to every intersected erasable object.
*/
_finalizeAndAddPath: function () {
var ctx = this.canvas.contextTop,
canvas = this.canvas;
ctx.closePath();
if (this.decimate) {
this._points = this.decimatePoints(this._points, this.decimate);
}
// clear
canvas.clearContext(canvas.contextTop);
this._isErasing = false;
var pathData =
this._points && this._points.length > 1
? this.convertPointsToSVGPath(this._points).join("")
: "M 0 0 Q 0 0 0 0 L 0 0";
if (pathData === "M 0 0 Q 0 0 0 0 L 0 0") {
canvas.fire("erasing:end");
// do not create 0 width/height paths, as they are
// rendered inconsistently across browsers
// Firefox 4, for example, renders a dot,
// whereas Chrome 10 renders nothing
canvas.requestRenderAll();
return;
}
var path = this.createPath(pathData);
canvas.fire("before:path:created", { path: path });
// finalize erasing
var drawables = this.applyEraserToCanvas(path);
var _this = this;
var targets = [];
canvas.forEachObject(function (obj) {
if (obj.erasable && path.intersectsWithObject(obj, true, false)) {
_this._addPathToObjectEraser(obj, path);
targets.push(obj);
}
});
canvas.fire("erasing:end", {
path: path,
targets: targets,
drawables: drawables
});