-
-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
StaticCanvas.ts
1503 lines (1385 loc) · 45.3 KB
/
StaticCanvas.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 { config } from '../config';
import { CENTER, VERSION } from '../constants';
import type { CanvasEvents, StaticCanvasEvents } from '../EventTypeDefs';
import type { Gradient } from '../gradient/Gradient';
import { createCollectionMixin } from '../Collection';
import { CommonMethods } from '../CommonMethods';
import type { Pattern } from '../Pattern';
import { Point } from '../Point';
import type { TCachedFabricObject } from '../shapes/Object/Object';
import type {
Abortable,
Constructor,
TCornerPoint,
TDataUrlOptions,
TFiller,
TMat2D,
TSize,
TSVGReviver,
TToCanvasElementOptions,
TValidToObjectMethod,
TOptions,
} from '../typedefs';
import {
cancelAnimFrame,
requestAnimFrame,
} from '../util/animation/AnimationFrameProvider';
import { uid } from '../util/internals/uid';
import { createCanvasElement, toDataURL } from '../util/misc/dom';
import { invertTransform, transformPoint } from '../util/misc/matrix';
import type { EnlivenObjectOptions } from '../util/misc/objectEnlive';
import {
enlivenObjectEnlivables,
enlivenObjects,
} from '../util/misc/objectEnlive';
import { pick } from '../util/misc/pick';
import { matrixToSVG } from '../util/misc/svgParsing';
import { toFixed } from '../util/misc/toFixed';
import {
isCollection,
isFiller,
isPattern,
isTextObject,
} from '../util/typeAssertions';
import { StaticCanvasDOMManager } from './DOMManagers/StaticCanvasDOMManager';
import type { CSSDimensions } from './DOMManagers/util';
import type { FabricObject } from '../shapes/Object/FabricObject';
import type { StaticCanvasOptions } from './StaticCanvasOptions';
import { staticCanvasDefaults } from './StaticCanvasOptions';
export type TCanvasSizeOptions = {
backstoreOnly?: boolean;
cssOnly?: boolean;
};
export type TSVGExportOptions = {
suppressPreamble?: boolean;
viewBox?: {
x: number;
y: number;
width: number;
height: number;
};
encoding?: 'UTF-8'; // test Encoding type and see what happens
width?: string;
height?: string;
reviver?: TSVGReviver;
};
/**
* Static canvas class
* @see {@link http://fabricjs.com/static_canvas|StaticCanvas demo}
* @fires before:render
* @fires after:render
* @fires canvas:cleared
* @fires object:added
* @fires object:removed
*/
// TODO: fix `EventSpec` inheritance https://github.com/microsoft/TypeScript/issues/26154#issuecomment-1366616260
export class StaticCanvas<
EventSpec extends StaticCanvasEvents = StaticCanvasEvents
>
extends createCollectionMixin(CommonMethods<CanvasEvents>)
implements StaticCanvasOptions
{
declare width: number;
declare height: number;
// background
declare backgroundVpt: boolean;
declare backgroundColor: TFiller | string;
declare backgroundImage?: FabricObject;
// overlay
declare overlayVpt: boolean;
declare overlayColor: TFiller | string;
declare overlayImage?: FabricObject;
declare clipPath?: FabricObject;
declare includeDefaultValues: boolean;
// rendering config
declare renderOnAddRemove: boolean;
declare skipOffscreen: boolean;
declare enableRetinaScaling: boolean;
declare imageSmoothingEnabled: boolean;
/**
* @todo move to Canvas
*/
declare controlsAboveOverlay: boolean;
/**
* @todo move to Canvas
*/
declare allowTouchScrolling: boolean;
declare viewportTransform: TMat2D;
/**
* Describe canvas element extension over design
* properties are tl,tr,bl,br.
* if canvas is not zoomed/panned those points are the four corner of canvas
* if canvas is viewportTransformed you those points indicate the extension
* of canvas element in plain untrasformed coordinates
* The coordinates get updated with @method calcViewportBoundaries.
*/
declare vptCoords: TCornerPoint;
/**
* A reference to the canvas actual HTMLCanvasElement.
* Can be use to read the raw pixels, but never write or manipulate
* @type HTMLCanvasElement
*/
get lowerCanvasEl() {
return this.elements.lower?.el;
}
get contextContainer() {
return this.elements.lower?.ctx;
}
/**
* If true the Canvas is in the process or has been disposed/destroyed.
* No more rendering operation will be executed on this canvas.
* @type boolean
*/
declare destroyed?: boolean;
/**
* Started the process of disposing but not done yet.
* WIll likely complete the render cycle already scheduled but stopping adding more.
* @type boolean
*/
declare disposed?: boolean;
declare _offset: { left: number; top: number };
protected declare hasLostContext: boolean;
protected declare nextRenderHandle: number;
declare elements: StaticCanvasDOMManager;
static ownDefaults = staticCanvasDefaults;
// reference to
protected declare __cleanupTask?: {
(): void;
kill: (reason?: any) => void;
};
static getDefaults(): Record<string, any> {
return StaticCanvas.ownDefaults;
}
constructor(
el: string | HTMLCanvasElement,
options: TOptions<StaticCanvasOptions> = {}
) {
super();
Object.assign(
this,
(this.constructor as typeof StaticCanvas).getDefaults()
);
this.set(options);
this.initElements(el);
this._setDimensionsImpl({
width: this.width || this.elements.lower.el.width || 0,
height: this.height || this.elements.lower.el.height || 0,
});
this.viewportTransform = [...this.viewportTransform];
this.calcViewportBoundaries();
}
protected initElements(el: string | HTMLCanvasElement) {
this.elements = new StaticCanvasDOMManager(el);
}
add(...objects: FabricObject[]) {
const size = super.add(...objects);
objects.length > 0 && this.renderOnAddRemove && this.requestRenderAll();
return size;
}
insertAt(index: number, ...objects: FabricObject[]) {
const size = super.insertAt(index, ...objects);
objects.length > 0 && this.renderOnAddRemove && this.requestRenderAll();
return size;
}
remove(...objects: FabricObject[]) {
const removed = super.remove(...objects);
removed.length > 0 && this.renderOnAddRemove && this.requestRenderAll();
return removed;
}
_onObjectAdded(obj: FabricObject) {
if (obj.canvas && (obj.canvas as StaticCanvas) !== this) {
/* _DEV_MODE_START_ */
console.warn(
'fabric.Canvas: trying to add an object that belongs to a different canvas.\n' +
'Resulting to default behavior: removing object from previous canvas and adding to new canvas'
);
/* _DEV_MODE_END_ */
obj.canvas.remove(obj);
}
obj._set('canvas', this);
obj.setCoords();
this.fire('object:added', { target: obj });
obj.fire('added', { target: this });
}
_onObjectRemoved(obj: FabricObject) {
obj._set('canvas', undefined);
this.fire('object:removed', { target: obj });
obj.fire('removed', { target: this });
}
_onStackOrderChanged() {
this.renderOnAddRemove && this.requestRenderAll();
}
/**
* @private
*/
_isRetinaScaling() {
return config.devicePixelRatio > 1 && this.enableRetinaScaling;
}
/**
* @private
* @return {Number} retinaScaling if applied, otherwise 1;
*/
getRetinaScaling() {
return this._isRetinaScaling() ? Math.max(1, config.devicePixelRatio) : 1;
}
/**
* Calculates canvas element offset relative to the document
* This method is also attached as "resize" event handler of window
*/
calcOffset() {
return (this._offset = this.elements.calcOffset());
}
/**
* Returns canvas width (in px)
* @return {Number}
*/
getWidth(): number {
return this.width;
}
/**
* Returns canvas height (in px)
* @return {Number}
*/
getHeight(): number {
return this.height;
}
/**
* Sets width of this canvas instance
* @param {Number|String} value Value to set width to
* @param {Object} [options] Options object
* @param {Boolean} [options.backstoreOnly=false] Set the given dimensions only as canvas backstore dimensions
* @param {Boolean} [options.cssOnly=false] Set the given dimensions only as css dimensions
* @deprecated will be removed in 7.0
*/
setWidth(value: number, options: TCanvasSizeOptions = {}) {
return this.setDimensions({ width: value }, options);
}
/**
* Sets height of this canvas instance
* @param {Number|String} value Value to set height to
* @param {Object} [options] Options object
* @param {Boolean} [options.backstoreOnly=false] Set the given dimensions only as canvas backstore dimensions
* @param {Boolean} [options.cssOnly=false] Set the given dimensions only as css dimensions
* @deprecated will be removed in 7.0
*/
setHeight(value: number, options: TCanvasSizeOptions = {}) {
return this.setDimensions({ height: value }, options);
}
/**
* Internal use only
* @protected
*/
protected _setDimensionsImpl(
dimensions: Partial<TSize | CSSDimensions>,
{ cssOnly = false, backstoreOnly = false }: TCanvasSizeOptions = {}
) {
if (!cssOnly) {
const size = {
width: this.width,
height: this.height,
...(dimensions as Partial<TSize>),
};
this.elements.setDimensions(size, this.getRetinaScaling());
this.hasLostContext = true;
this.width = size.width;
this.height = size.height;
}
if (!backstoreOnly) {
this.elements.setCSSDimensions(dimensions);
}
this.calcOffset();
}
/**
* Sets dimensions (width, height) of this canvas instance. when options.cssOnly flag active you should also supply the unit of measure (px/%/em)
* @param {Object} dimensions Object with width/height properties
* @param {Number|String} [dimensions.width] Width of canvas element
* @param {Number|String} [dimensions.height] Height of canvas element
* @param {Object} [options] Options object
* @param {Boolean} [options.backstoreOnly=false] Set the given dimensions only as canvas backstore dimensions
* @param {Boolean} [options.cssOnly=false] Set the given dimensions only as css dimensions
*/
setDimensions(
dimensions: Partial<TSize>,
{ cssOnly = false, backstoreOnly = false }: TCanvasSizeOptions = {}
) {
this._setDimensionsImpl(dimensions, {
cssOnly,
backstoreOnly,
});
if (!cssOnly) {
this.requestRenderAll();
}
}
/**
* Returns canvas zoom level
* @return {Number}
*/
getZoom() {
return this.viewportTransform[0];
}
/**
* Sets viewport transformation of this canvas instance
* @param {Array} vpt a Canvas 2D API transform matrix
*/
setViewportTransform(vpt: TMat2D) {
const backgroundObject = this.backgroundImage,
overlayObject = this.overlayImage,
len = this._objects.length;
this.viewportTransform = vpt;
for (let i = 0; i < len; i++) {
const object = this._objects[i];
object.group || object.setCoords();
}
if (backgroundObject) {
backgroundObject.setCoords();
}
if (overlayObject) {
overlayObject.setCoords();
}
this.calcViewportBoundaries();
this.renderOnAddRemove && this.requestRenderAll();
}
/**
* Sets zoom level of this canvas instance, the zoom centered around point
* meaning that following zoom to point with the same point will have the visual
* effect of the zoom originating from that point. The point won't move.
* It has nothing to do with canvas center or visual center of the viewport.
* @param {Point} point to zoom with respect to
* @param {Number} value to set zoom to, less than 1 zooms out
*/
zoomToPoint(point: Point, value: number) {
// TODO: just change the scale, preserve other transformations
const before = point,
vpt: TMat2D = [...this.viewportTransform];
const newPoint = transformPoint(point, invertTransform(vpt));
vpt[0] = value;
vpt[3] = value;
const after = transformPoint(newPoint, vpt);
vpt[4] += before.x - after.x;
vpt[5] += before.y - after.y;
this.setViewportTransform(vpt);
}
/**
* Sets zoom level of this canvas instance
* @param {Number} value to set zoom to, less than 1 zooms out
*/
setZoom(value: number) {
this.zoomToPoint(new Point(0, 0), value);
}
/**
* Pan viewport so as to place point at top left corner of canvas
* @param {Point} point to move to
*/
absolutePan(point: Point) {
const vpt: TMat2D = [...this.viewportTransform];
vpt[4] = -point.x;
vpt[5] = -point.y;
return this.setViewportTransform(vpt);
}
/**
* Pans viewpoint relatively
* @param {Point} point (position vector) to move by
*/
relativePan(point: Point) {
return this.absolutePan(
new Point(
-point.x - this.viewportTransform[4],
-point.y - this.viewportTransform[5]
)
);
}
/**
* Returns <canvas> element corresponding to this instance
* @return {HTMLCanvasElement}
*/
getElement(): HTMLCanvasElement {
return this.elements.lower.el;
}
/**
* Clears specified context of canvas element
* @param {CanvasRenderingContext2D} ctx Context to clear
*/
clearContext(ctx: CanvasRenderingContext2D) {
ctx.clearRect(0, 0, this.width, this.height);
}
/**
* Returns context of canvas where objects are drawn
* @return {CanvasRenderingContext2D}
*/
getContext(): CanvasRenderingContext2D {
return this.elements.lower.ctx;
}
/**
* Clears all contexts (background, main, top) of an instance
*/
clear() {
this.remove(...this.getObjects());
this.backgroundImage = undefined;
this.overlayImage = undefined;
this.backgroundColor = '';
this.overlayColor = '';
this.clearContext(this.getContext());
this.fire('canvas:cleared');
this.renderOnAddRemove && this.requestRenderAll();
}
/**
* Renders the canvas
*/
renderAll() {
this.cancelRequestedRender();
if (this.destroyed) {
return;
}
this.renderCanvas(this.getContext(), this._objects);
}
/**
* Function created to be instance bound at initialization
* used in requestAnimationFrame rendering
* Let the fabricJS call it. If you call it manually you could have more
* animationFrame stacking on to of each other
* for an imperative rendering, use canvas.renderAll
* @private
*/
renderAndReset() {
this.nextRenderHandle = 0;
this.renderAll();
}
/**
* Append a renderAll request to next animation frame.
* unless one is already in progress, in that case nothing is done
* a boolean flag will avoid appending more.
*/
requestRenderAll() {
if (!this.nextRenderHandle && !this.disposed && !this.destroyed) {
this.nextRenderHandle = requestAnimFrame(() => this.renderAndReset());
}
}
/**
* Calculate the position of the 4 corner of canvas with current viewportTransform.
* helps to determinate when an object is in the current rendering viewport using
* object absolute coordinates ( aCoords )
* @return {Object} points.tl
* @chainable
*/
calcViewportBoundaries(): TCornerPoint {
const width = this.width,
height = this.height,
iVpt = invertTransform(this.viewportTransform),
a = transformPoint({ x: 0, y: 0 }, iVpt),
b = transformPoint({ x: width, y: height }, iVpt),
// we don't support vpt flipping
// but the code is robust enough to mostly work with flipping
min = a.min(b),
max = a.max(b);
return (this.vptCoords = {
tl: min,
tr: new Point(max.x, min.y),
bl: new Point(min.x, max.y),
br: max,
});
}
cancelRequestedRender() {
if (this.nextRenderHandle) {
cancelAnimFrame(this.nextRenderHandle);
this.nextRenderHandle = 0;
}
}
drawControls(ctx: CanvasRenderingContext2D) {
// Static canvas has no controls
}
/**
* Renders background, objects, overlay and controls.
* @param {CanvasRenderingContext2D} ctx
* @param {Array} objects to render
*/
renderCanvas(ctx: CanvasRenderingContext2D, objects: FabricObject[]) {
if (this.destroyed) {
return;
}
const v = this.viewportTransform,
path = this.clipPath;
this.calcViewportBoundaries();
this.clearContext(ctx);
ctx.imageSmoothingEnabled = this.imageSmoothingEnabled;
// @ts-expect-error node-canvas stuff
ctx.patternQuality = 'best';
this.fire('before:render', { ctx });
this._renderBackground(ctx);
ctx.save();
//apply viewport transform once for all rendering process
ctx.transform(v[0], v[1], v[2], v[3], v[4], v[5]);
this._renderObjects(ctx, objects);
ctx.restore();
if (!this.controlsAboveOverlay) {
this.drawControls(ctx);
}
if (path) {
path._set('canvas', this);
// needed to setup a couple of variables
path.shouldCache();
path._transformDone = true;
path.renderCache({ forClipping: true });
this.drawClipPathOnCanvas(ctx, path as TCachedFabricObject);
}
this._renderOverlay(ctx);
if (this.controlsAboveOverlay) {
this.drawControls(ctx);
}
this.fire('after:render', { ctx });
if (this.__cleanupTask) {
this.__cleanupTask();
this.__cleanupTask = undefined;
}
}
/**
* Paint the cached clipPath on the lowerCanvasEl
* @param {CanvasRenderingContext2D} ctx Context to render on
*/
drawClipPathOnCanvas(
ctx: CanvasRenderingContext2D,
clipPath: TCachedFabricObject
) {
const v = this.viewportTransform;
ctx.save();
ctx.transform(...v);
// DEBUG: uncomment this line, comment the following
// ctx.globalAlpha = 0.4;
ctx.globalCompositeOperation = 'destination-in';
clipPath.transform(ctx);
ctx.scale(1 / clipPath.zoomX, 1 / clipPath.zoomY);
ctx.drawImage(
clipPath._cacheCanvas,
-clipPath.cacheTranslationX,
-clipPath.cacheTranslationY
);
ctx.restore();
}
/**
* @private
* @param {CanvasRenderingContext2D} ctx Context to render on
* @param {Array} objects to render
*/
_renderObjects(ctx: CanvasRenderingContext2D, objects: FabricObject[]) {
for (let i = 0, len = objects.length; i < len; ++i) {
objects[i] && objects[i].render(ctx);
}
}
/**
* @private
* @param {CanvasRenderingContext2D} ctx Context to render on
* @param {string} property 'background' or 'overlay'
*/
_renderBackgroundOrOverlay(
ctx: CanvasRenderingContext2D,
property: 'background' | 'overlay'
) {
const fill = this[`${property}Color`],
object = this[`${property}Image`],
v = this.viewportTransform,
needsVpt = this[`${property}Vpt`];
if (!fill && !object) {
return;
}
const isAFiller = isFiller(fill);
if (fill) {
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(this.width, 0);
ctx.lineTo(this.width, this.height);
ctx.lineTo(0, this.height);
ctx.closePath();
ctx.fillStyle = isAFiller ? fill.toLive(ctx /* this */)! : fill;
if (needsVpt) {
ctx.transform(...v);
}
if (isAFiller) {
ctx.transform(1, 0, 0, 1, fill.offsetX || 0, fill.offsetY || 0);
const m = ((fill as Gradient<'linear'>).gradientTransform ||
(fill as Pattern).patternTransform) as TMat2D;
m && ctx.transform(...m);
}
ctx.fill();
ctx.restore();
}
if (object) {
ctx.save();
const { skipOffscreen } = this;
// if the object doesn't move with the viewport,
// the offscreen concept does not apply;
this.skipOffscreen = needsVpt;
if (needsVpt) {
ctx.transform(...v);
}
object.render(ctx);
this.skipOffscreen = skipOffscreen;
ctx.restore();
}
}
/**
* @private
* @param {CanvasRenderingContext2D} ctx Context to render on
*/
_renderBackground(ctx: CanvasRenderingContext2D) {
this._renderBackgroundOrOverlay(ctx, 'background');
}
/**
* @private
* @param {CanvasRenderingContext2D} ctx Context to render on
*/
_renderOverlay(ctx: CanvasRenderingContext2D) {
this._renderBackgroundOrOverlay(ctx, 'overlay');
}
/**
* Returns coordinates of a center of canvas.
* Returned value is an object with top and left properties
* @return {Object} object with "top" and "left" number values
* @deprecated migrate to `getCenterPoint`
*/
getCenter() {
return {
top: this.height / 2,
left: this.width / 2,
};
}
/**
* Returns coordinates of a center of canvas.
* @return {Point}
*/
getCenterPoint() {
return new Point(this.width / 2, this.height / 2);
}
/**
* Centers object horizontally in the canvas
*/
centerObjectH(object: FabricObject) {
return this._centerObject(
object,
new Point(this.getCenterPoint().x, object.getCenterPoint().y)
);
}
/**
* Centers object vertically in the canvas
* @param {FabricObject} object Object to center vertically
*/
centerObjectV(object: FabricObject) {
return this._centerObject(
object,
new Point(object.getCenterPoint().x, this.getCenterPoint().y)
);
}
/**
* Centers object vertically and horizontally in the canvas
* @param {FabricObject} object Object to center vertically and horizontally
*/
centerObject(object: FabricObject) {
return this._centerObject(object, this.getCenterPoint());
}
/**
* Centers object vertically and horizontally in the viewport
* @param {FabricObject} object Object to center vertically and horizontally
*/
viewportCenterObject(object: FabricObject) {
return this._centerObject(object, this.getVpCenter());
}
/**
* Centers object horizontally in the viewport, object.top is unchanged
* @param {FabricObject} object Object to center vertically and horizontally
*/
viewportCenterObjectH(object: FabricObject) {
return this._centerObject(
object,
new Point(this.getVpCenter().x, object.getCenterPoint().y)
);
}
/**
* Centers object Vertically in the viewport, object.top is unchanged
* @param {FabricObject} object Object to center vertically and horizontally
*/
viewportCenterObjectV(object: FabricObject) {
return this._centerObject(
object,
new Point(object.getCenterPoint().x, this.getVpCenter().y)
);
}
/**
* Calculate the point in canvas that correspond to the center of actual viewport.
* @return {Point} vpCenter, viewport center
*/
getVpCenter(): Point {
return transformPoint(
this.getCenterPoint(),
invertTransform(this.viewportTransform)
);
}
/**
* @private
* @param {FabricObject} object Object to center
* @param {Point} center Center point
*/
_centerObject(object: FabricObject, center: Point) {
object.setXY(center, CENTER, CENTER);
object.setCoords();
this.renderOnAddRemove && this.requestRenderAll();
}
/**
* Returns dataless JSON representation of canvas
* @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
* @return {String} json string
*/
toDatalessJSON(propertiesToInclude?: string[]) {
return this.toDatalessObject(propertiesToInclude);
}
/**
* Returns object representation of canvas
* @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
* @return {Object} object representation of an instance
*/
toObject(propertiesToInclude?: string[]) {
return this._toObjectMethod('toObject', propertiesToInclude);
}
/**
* Returns Object representation of canvas
* this alias is provided because if you call JSON.stringify on an instance,
* the toJSON object will be invoked if it exists.
* Having a toJSON method means you can do JSON.stringify(myCanvas)
* @return {Object} JSON compatible object
* @tutorial {@link http://fabricjs.com/fabric-intro-part-3#serialization}
* @see {@link http://jsfiddle.net/fabricjs/pec86/|jsFiddle demo}
* @example <caption>JSON without additional properties</caption>
* var json = canvas.toJSON();
* @example <caption>JSON with additional properties included</caption>
* var json = canvas.toJSON(['lockMovementX', 'lockMovementY', 'lockRotation', 'lockScalingX', 'lockScalingY']);
* @example <caption>JSON without default values</caption>
* var json = canvas.toJSON();
*/
toJSON() {
return this.toObject();
}
/**
* Returns dataless object representation of canvas
* @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
* @return {Object} object representation of an instance
*/
toDatalessObject(propertiesToInclude?: string[]) {
return this._toObjectMethod('toDatalessObject', propertiesToInclude);
}
/**
* @private
*/
_toObjectMethod(
methodName: TValidToObjectMethod,
propertiesToInclude?: string[]
) {
const clipPath = this.clipPath;
const clipPathData =
clipPath && !clipPath.excludeFromExport
? this._toObject(clipPath, methodName, propertiesToInclude)
: null;
return {
version: VERSION,
...pick(this, propertiesToInclude as (keyof this)[]),
objects: this._objects
.filter((object) => !object.excludeFromExport)
.map((instance) =>
this._toObject(instance, methodName, propertiesToInclude)
),
...this.__serializeBgOverlay(methodName, propertiesToInclude),
...(clipPathData ? { clipPath: clipPathData } : null),
};
}
/**
* @private
*/
_toObject(
instance: FabricObject,
methodName: TValidToObjectMethod,
propertiesToInclude?: string[]
) {
let originalValue;
if (!this.includeDefaultValues) {
originalValue = instance.includeDefaultValues;
instance.includeDefaultValues = false;
}
const object = instance[methodName](propertiesToInclude);
if (!this.includeDefaultValues) {
instance.includeDefaultValues = !!originalValue;
}
return object;
}
/**
* @private
*/
__serializeBgOverlay(
methodName: TValidToObjectMethod,
propertiesToInclude?: string[]
) {
const data: any = {},
bgImage = this.backgroundImage,
overlayImage = this.overlayImage,
bgColor = this.backgroundColor,
overlayColor = this.overlayColor;
if (isFiller(bgColor)) {
if (!bgColor.excludeFromExport) {
data.background = bgColor.toObject(propertiesToInclude);
}
} else if (bgColor) {
data.background = bgColor;
}
if (isFiller(overlayColor)) {
if (!overlayColor.excludeFromExport) {
data.overlay = overlayColor.toObject(propertiesToInclude);
}
} else if (overlayColor) {
data.overlay = overlayColor;
}
if (bgImage && !bgImage.excludeFromExport) {
data.backgroundImage = this._toObject(
bgImage,
methodName,
propertiesToInclude
);
}
if (overlayImage && !overlayImage.excludeFromExport) {
data.overlayImage = this._toObject(
overlayImage,
methodName,
propertiesToInclude
);
}
return data;
}
/* _TO_SVG_START_ */
declare svgViewportTransformation: boolean;
/**
* Returns SVG representation of canvas
* @function
* @param {Object} [options] Options object for SVG output
* @param {Boolean} [options.suppressPreamble=false] If true xml tag is not included
* @param {Object} [options.viewBox] SVG viewbox object
* @param {Number} [options.viewBox.x] x-coordinate of viewbox
* @param {Number} [options.viewBox.y] y-coordinate of viewbox
* @param {Number} [options.viewBox.width] Width of viewbox
* @param {Number} [options.viewBox.height] Height of viewbox
* @param {String} [options.encoding=UTF-8] Encoding of SVG output
* @param {String} [options.width] desired width of svg with or without units
* @param {String} [options.height] desired height of svg with or without units
* @param {Function} [reviver] Method for further parsing of svg elements, called after each fabric object converted into svg representation.
* @return {String} SVG string
* @tutorial {@link http://fabricjs.com/fabric-intro-part-3#serialization}
* @see {@link http://jsfiddle.net/fabricjs/jQ3ZZ/|jsFiddle demo}
* @example <caption>Normal SVG output</caption>
* var svg = canvas.toSVG();
* @example <caption>SVG output without preamble (without <?xml ../>)</caption>
* var svg = canvas.toSVG({suppressPreamble: true});
* @example <caption>SVG output with viewBox attribute</caption>
* var svg = canvas.toSVG({
* viewBox: {
* x: 100,
* y: 100,
* width: 200,
* height: 300
* }
* });
* @example <caption>SVG output with different encoding (default: UTF-8)</caption>
* var svg = canvas.toSVG({encoding: 'ISO-8859-1'});
* @example <caption>Modify SVG output with reviver function</caption>
* var svg = canvas.toSVG(null, function(svg) {
* return svg.replace('stroke-dasharray: ; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; ', '');
* });
*/
toSVG(options: TSVGExportOptions = {}, reviver: TSVGReviver) {
options.reviver = reviver;
const markup: string[] = [];
this._setSVGPreamble(markup, options);
this._setSVGHeader(markup, options);
if (this.clipPath) {
markup.push(`<g clip-path="url(#${this.clipPath.clipPathId})" >\n`);
}
this._setSVGBgOverlayColor(markup, 'background');
this._setSVGBgOverlayImage(markup, 'backgroundImage', reviver);
this._setSVGObjects(markup, reviver);
if (this.clipPath) {
markup.push('</g>\n');
}
this._setSVGBgOverlayColor(markup, 'overlay');
this._setSVGBgOverlayImage(markup, 'overlayImage', reviver);
markup.push('</svg>');
return markup.join('');