@bensitu/image-editor 1.2.0 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2563 @@
1
+ (() => {
2
+ // src/image-editor.js
3
+ /**
4
+ * @file image-editor.js
5
+ * @module image-editor
6
+ * @version 1.2.2
7
+ * @author Ben Situ
8
+ * @license MIT
9
+ * @description Lightweight canvas-based image editor with masking/transform/export support.
10
+ */
11
+ var fabric = null;
12
+ function getGlobalScope() {
13
+ if (typeof globalThis !== "undefined")
14
+ return globalThis;
15
+ if (typeof self !== "undefined")
16
+ return self;
17
+ if (typeof window !== "undefined")
18
+ return window;
19
+ return null;
20
+ }
21
+ function getGlobalFabric() {
22
+ const scope2 = getGlobalScope();
23
+ return scope2 && scope2.fabric ? scope2.fabric : null;
24
+ }
25
+ function setFabric(fabricInstance) {
26
+ fabric = fabricInstance || getGlobalFabric();
27
+ return fabric;
28
+ }
29
+ function ensureFabric() {
30
+ if (!fabric)
31
+ setFabric();
32
+ return fabric;
33
+ }
34
+ var ImageEditor = class {
35
+ constructor(options = {}) {
36
+ const defaultLabel = {
37
+ getText: (mask) => mask.maskName,
38
+ textOptions: {
39
+ fontSize: 12,
40
+ fill: "#fff",
41
+ backgroundColor: "rgba(0,0,0,0.7)",
42
+ padding: 2,
43
+ fontFamily: "monospace",
44
+ fontWeight: "bold",
45
+ selectable: false,
46
+ evented: false,
47
+ originX: "left",
48
+ originY: "top"
49
+ }
50
+ };
51
+ const defaultCrop = {
52
+ minWidth: 100,
53
+ minHeight: 100,
54
+ padding: 10,
55
+ hideMasksDuringCrop: true,
56
+ preserveMasksAfterCrop: false,
57
+ allowRotationOfCropRect: false
58
+ };
59
+ const userLabel = options.label || {};
60
+ const userCrop = options.crop || {};
61
+ this.options = {
62
+ canvasWidth: 800,
63
+ canvasHeight: 600,
64
+ backgroundColor: "transparent",
65
+ animationDuration: 300,
66
+ minScale: 0.1,
67
+ maxScale: 5,
68
+ scaleStep: 0.05,
69
+ rotationStep: 90,
70
+ expandCanvasToImage: true,
71
+ fitImageToCanvas: false,
72
+ coverImageToCanvas: false,
73
+ downsampleOnLoad: true,
74
+ downsampleMaxWidth: 4e3,
75
+ downsampleMaxHeight: 3e3,
76
+ downsampleQuality: 0.92,
77
+ exportMultiplier: 1,
78
+ exportImageAreaByDefault: true,
79
+ defaultMaskWidth: 50,
80
+ defaultMaskHeight: 80,
81
+ maskRotatable: false,
82
+ maskLabelOnSelect: true,
83
+ maskLabelOffset: 3,
84
+ maskName: "mask",
85
+ groupSelection: false,
86
+ showPlaceholder: true,
87
+ initialImageBase64: null,
88
+ // Provide a base64 'data:image/...' string here if you want auto-load
89
+ defaultDownloadFileName: "edited_image.jpg",
90
+ onError: null,
91
+ onWarning: null,
92
+ ...options,
93
+ label: {
94
+ ...defaultLabel,
95
+ ...userLabel,
96
+ textOptions: {
97
+ ...defaultLabel.textOptions,
98
+ ...userLabel.textOptions || {}
99
+ }
100
+ },
101
+ crop: {
102
+ ...defaultCrop,
103
+ ...userCrop
104
+ }
105
+ };
106
+ this._fabricLoaded = !!ensureFabric();
107
+ if (!this._fabricLoaded) {
108
+ this._reportError("fabric.js is not loaded. Please include fabric.js first. Initialization will be aborted.");
109
+ }
110
+ this.canvas = null;
111
+ this.canvasElement = null;
112
+ this.containerElement = null;
113
+ this.placeholderElement = null;
114
+ this.originalImage = null;
115
+ this.baseImageScale = 1;
116
+ this.currentScale = 1;
117
+ this.currentRotation = 0;
118
+ this.maskCounter = 0;
119
+ this.isAnimating = false;
120
+ this.elements = {};
121
+ this.isImageLoadedToCanvas = false;
122
+ this.maxHistorySize = 50;
123
+ this._handlersByElementKey = {};
124
+ this._lastMask = null;
125
+ this._lastMaskInitialLeft = null;
126
+ this._lastMaskInitialTop = null;
127
+ this._lastMaskInitialWidth = null;
128
+ this._lastSnapshot = null;
129
+ this._cropMode = false;
130
+ this._cropRect = null;
131
+ this._cropHandlers = [];
132
+ this._cropPrevEvented = null;
133
+ this._prevSelectionSetting = void 0;
134
+ this._containerOriginalOverflow = void 0;
135
+ this.onImageLoaded = typeof options.onImageLoaded === "function" ? options.onImageLoaded : null;
136
+ this.animQueue = new AnimationQueue();
137
+ this.historyManager = new HistoryManager(this.maxHistorySize);
138
+ }
139
+ /**
140
+ * @deprecated Use canvasElement instead.
141
+ */
142
+ get canvasEl() {
143
+ return this.canvasElement;
144
+ }
145
+ set canvasEl(value) {
146
+ this.canvasElement = value;
147
+ }
148
+ /**
149
+ * @deprecated Use containerElement instead.
150
+ */
151
+ get containerEl() {
152
+ return this.containerElement;
153
+ }
154
+ set containerEl(value) {
155
+ this.containerElement = value;
156
+ }
157
+ /**
158
+ * @deprecated Use placeholderElement instead.
159
+ */
160
+ get placeholderEl() {
161
+ return this.placeholderElement;
162
+ }
163
+ set placeholderEl(value) {
164
+ this.placeholderElement = value;
165
+ }
166
+ /**
167
+ * Initializes the editor, binds to DOM elements, sets up event handlers,
168
+ * and (optionally) loads an initial image.
169
+ * Use this method to set up the editor UI before interacting with it.
170
+ *
171
+ * @param {Object} [idMap={}] - Optional mapping from logical element names to actual DOM element IDs.
172
+ * Supported keys include: canvas, canvasContainer, imgPlaceholder, scaleRate, rotationLeftInput, rotationRightInput,
173
+ * rotateLeftBtn, rotateRightBtn, addMaskBtn, removeMaskBtn, removeAllMasksBtn, mergeBtn, downloadBtn, maskList,
174
+ * zoomInBtn, zoomOutBtn, resetBtn, imageInput. Unknown keys are ignored.
175
+ *
176
+ * @returns {void}
177
+ *
178
+ * @public
179
+ *
180
+ * @example
181
+ * editor.init({
182
+ * canvas: 'myFabricCanvasId',
183
+ * downloadBtn: 'myDownloadButtonId'
184
+ * });
185
+ */
186
+ init(idMap = {}) {
187
+ if (!this._fabricLoaded)
188
+ return;
189
+ const defaults = {
190
+ canvas: "fabricCanvas",
191
+ canvasContainer: null,
192
+ // Pass an ID here if you have a scrollable viewport container
193
+ imgPlaceholder: "imgPlaceholder",
194
+ scaleRate: "scaleRate",
195
+ rotationLeftInput: "rotationLeftInput",
196
+ rotationRightInput: "rotationRightInput",
197
+ rotateLeftBtn: "rotateLeftBtn",
198
+ rotateRightBtn: "rotateRightBtn",
199
+ addMaskBtn: "addMaskBtn",
200
+ removeMaskBtn: "removeMaskBtn",
201
+ removeAllMasksBtn: "removeAllMasksBtn",
202
+ mergeBtn: "mergeBtn",
203
+ downloadBtn: "downloadBtn",
204
+ maskList: "maskList",
205
+ zoomInBtn: "zoomInBtn",
206
+ zoomOutBtn: "zoomOutBtn",
207
+ resetBtn: "resetBtn",
208
+ undoBtn: "undoBtn",
209
+ redoBtn: "redoBtn",
210
+ imageInput: "imageInput",
211
+ cropBtn: "cropBtn",
212
+ applyCropBtn: "applyCropBtn",
213
+ cancelCropBtn: "cancelCropBtn"
214
+ };
215
+ this.elements = { ...defaults, ...idMap };
216
+ this._initCanvas();
217
+ this._bindEvents();
218
+ this._updateInputs();
219
+ this._updateMaskList();
220
+ this._updateUI();
221
+ if (this.options.initialImageBase64) {
222
+ this.loadImage(this.options.initialImageBase64);
223
+ } else {
224
+ this._updatePlaceholderStatus();
225
+ }
226
+ }
227
+ _reportError(message, error = null) {
228
+ const handler = this.options && this.options.onError;
229
+ if (typeof handler !== "function")
230
+ return;
231
+ try {
232
+ handler(error, message);
233
+ } catch {
234
+ }
235
+ }
236
+ _reportWarning(message, error = null) {
237
+ const handler = this.options && this.options.onWarning;
238
+ if (typeof handler !== "function")
239
+ return;
240
+ try {
241
+ handler(error, message);
242
+ } catch {
243
+ }
244
+ }
245
+ /**
246
+ * Canvas setup helpers
247
+ * @private
248
+ */
249
+ _initCanvas() {
250
+ const canvasElement = document.getElementById(this.elements.canvas);
251
+ if (!canvasElement)
252
+ throw new Error("Canvas is not found: " + this.elements.canvas);
253
+ this.canvasElement = canvasElement;
254
+ if (this.elements.canvasContainer) {
255
+ const containerElement = document.getElementById(this.elements.canvasContainer);
256
+ this.containerElement = containerElement || canvasElement.parentElement;
257
+ } else {
258
+ this.containerElement = canvasElement.parentElement;
259
+ }
260
+ this.placeholderElement = document.getElementById(this.elements.imgPlaceholder) || null;
261
+ let initialWidth = this.options.canvasWidth;
262
+ let initialHeight = this.options.canvasHeight;
263
+ if (this.containerElement) {
264
+ const containerWidth = Math.floor(this.containerElement.clientWidth);
265
+ const containerHeight = Math.floor(this.containerElement.clientHeight);
266
+ if (containerWidth > 0 && containerHeight > 0) {
267
+ initialWidth = containerWidth;
268
+ initialHeight = containerHeight;
269
+ }
270
+ }
271
+ this.canvas = new fabric.Canvas(canvasElement, {
272
+ width: initialWidth,
273
+ height: initialHeight,
274
+ backgroundColor: this.options.backgroundColor,
275
+ selection: this.options.groupSelection,
276
+ preserveObjectStacking: true
277
+ });
278
+ this.canvas.on("selection:created", (event) => this._handleSelectionChanged(event.selected));
279
+ this.canvas.on("selection:updated", (event) => this._handleSelectionChanged(event.selected));
280
+ this.canvas.on("selection:cleared", () => this._handleSelectionChanged([]));
281
+ this.canvas.on("object:moving", (event) => {
282
+ if (event.target && event.target.maskId)
283
+ this._syncMaskLabel(event.target);
284
+ });
285
+ this.canvas.on("object:scaling", (event) => {
286
+ if (event.target && event.target.maskId)
287
+ this._syncMaskLabel(event.target);
288
+ });
289
+ this.canvas.on("object:rotating", (event) => {
290
+ if (event.target && event.target.maskId)
291
+ this._syncMaskLabel(event.target);
292
+ });
293
+ this.canvas.on("object:modified", (event) => this._handleObjectModified(event.target));
294
+ this.canvasElement.style.display = "block";
295
+ }
296
+ _handleObjectModified(target) {
297
+ const masks = this._getModifiedMasks(target);
298
+ if (!masks.length)
299
+ return;
300
+ masks.forEach((mask) => {
301
+ if (typeof mask.setCoords === "function")
302
+ mask.setCoords();
303
+ this._syncMaskLabel(mask);
304
+ this._expandCanvasToFitObject(mask);
305
+ });
306
+ this.saveState();
307
+ }
308
+ _getModifiedMasks(target) {
309
+ if (!target)
310
+ return [];
311
+ if (target.maskId)
312
+ return [target];
313
+ const objects = typeof target.getObjects === "function" ? target.getObjects() : [];
314
+ return Array.isArray(objects) ? objects.filter((object) => object && object.maskId) : [];
315
+ }
316
+ _syncContainerOverflow() {
317
+ if (!this.containerElement || !this.containerElement.style)
318
+ return;
319
+ if (this._containerOriginalOverflow === void 0) {
320
+ this._containerOriginalOverflow = this.containerElement.style.overflow || "";
321
+ }
322
+ if (this.options.coverImageToCanvas) {
323
+ const shouldResetScroll = !this.isImageLoadedToCanvas;
324
+ this.containerElement.style.overflow = "scroll";
325
+ if (shouldResetScroll) {
326
+ this.containerElement.scrollLeft = 0;
327
+ this.containerElement.scrollTop = 0;
328
+ }
329
+ } else if (this.options.fitImageToCanvas) {
330
+ this.containerElement.style.overflow = "auto";
331
+ this.containerElement.scrollLeft = 0;
332
+ this.containerElement.scrollTop = 0;
333
+ } else {
334
+ this.containerElement.style.overflow = this._containerOriginalOverflow;
335
+ }
336
+ }
337
+ /**
338
+ * DOM / UI bindings
339
+ * @private
340
+ */
341
+ _bindEvents() {
342
+ this._bindIfExists("uploadArea", "click", () => {
343
+ const uploadAreaElement = document.getElementById(this.elements.uploadArea);
344
+ if (this._isElementDisabled(uploadAreaElement))
345
+ return;
346
+ document.getElementById(this.elements.imageInput)?.click();
347
+ });
348
+ this._bindIfExists("imageInput", "change", (event) => {
349
+ const file = event.target.files && event.target.files[0];
350
+ if (file)
351
+ this._loadImageFile(file);
352
+ });
353
+ this._bindIfExists("zoomInBtn", "click", () => this.scaleImage(this.currentScale + this.options.scaleStep));
354
+ this._bindIfExists("zoomOutBtn", "click", () => this.scaleImage(this.currentScale - this.options.scaleStep));
355
+ this._bindIfExists("resetBtn", "click", () => {
356
+ this.resetImageTransform();
357
+ });
358
+ this._bindIfExists("addMaskBtn", "click", () => this.createMask());
359
+ this._bindIfExists("removeMaskBtn", "click", () => this.removeSelectedMask());
360
+ this._bindIfExists("removeAllMasksBtn", "click", () => this.removeAllMasks());
361
+ this._bindIfExists("mergeBtn", "click", () => this.mergeMasks());
362
+ this._bindIfExists("downloadBtn", "click", () => this.downloadImage());
363
+ this._bindIfExists("undoBtn", "click", () => this.undo());
364
+ this._bindIfExists("redoBtn", "click", () => this.redo());
365
+ this._bindIfExists("rotateLeftBtn", "click", () => {
366
+ const rotationInputElement = document.getElementById(this.elements.rotationLeftInput);
367
+ let step = this.options.rotationStep;
368
+ if (rotationInputElement) {
369
+ const parsedStep = parseFloat(rotationInputElement.value);
370
+ if (!isNaN(parsedStep))
371
+ step = parsedStep;
372
+ }
373
+ this.rotateImage(this.currentRotation - step);
374
+ });
375
+ this._bindIfExists("rotateRightBtn", "click", () => {
376
+ const rotationInputElement = document.getElementById(this.elements.rotationRightInput);
377
+ let step = this.options.rotationStep;
378
+ if (rotationInputElement) {
379
+ const parsedStep = parseFloat(rotationInputElement.value);
380
+ if (!isNaN(parsedStep))
381
+ step = parsedStep;
382
+ }
383
+ this.rotateImage(this.currentRotation + step);
384
+ });
385
+ this._bindIfExists("cropBtn", "click", () => this.enterCropMode());
386
+ this._bindIfExists("applyCropBtn", "click", () => {
387
+ this.applyCrop().catch((error) => this._reportError("applyCrop failed", error));
388
+ });
389
+ this._bindIfExists("cancelCropBtn", "click", () => this.cancelCrop());
390
+ }
391
+ /**
392
+ * Event binding element check
393
+ *
394
+ * @param {*} eventName
395
+ * @param {*} handler
396
+ * @param {*} key
397
+ * @private
398
+ */
399
+ _bindIfExists(key, eventName, handler) {
400
+ const element = document.getElementById(this.elements[key]);
401
+ if (element) {
402
+ element.addEventListener(eventName, handler);
403
+ this._handlersByElementKey = this._handlersByElementKey || {};
404
+ if (!this._handlersByElementKey[key])
405
+ this._handlersByElementKey[key] = [];
406
+ this._handlersByElementKey[key].push({ eventName, handler });
407
+ }
408
+ }
409
+ /**
410
+ * Image loading helpers
411
+ *
412
+ * @param {File} file
413
+ * @private
414
+ */
415
+ _loadImageFile(file) {
416
+ if (!file || !file.type.startsWith("image/"))
417
+ return;
418
+ const reader = new FileReader();
419
+ reader.onload = (event) => this.loadImage(event.target.result);
420
+ reader.onerror = (event) => {
421
+ this._reportError("Image file could not be read", event);
422
+ };
423
+ reader.readAsDataURL(file);
424
+ }
425
+ /**
426
+ * Load a base64 encoded image string into fabric.
427
+ * @async
428
+ * @param {String} imageBase64
429
+ */
430
+ async loadImage(imageBase64) {
431
+ if (!this._fabricLoaded)
432
+ return;
433
+ if (!this.canvas)
434
+ return;
435
+ if (!imageBase64 || typeof imageBase64 !== "string" || !imageBase64.startsWith("data:image/"))
436
+ return;
437
+ this._setPlaceholderVisible(false);
438
+ this._syncContainerOverflow();
439
+ const imageElement = await this._createImageElement(imageBase64);
440
+ let loadSource = imageBase64;
441
+ if (this.options.downsampleOnLoad) {
442
+ const shouldResize = imageElement.naturalWidth > this.options.downsampleMaxWidth || imageElement.naturalHeight > this.options.downsampleMaxHeight;
443
+ if (shouldResize) {
444
+ const ratio = Math.min(
445
+ this.options.downsampleMaxWidth / imageElement.naturalWidth,
446
+ this.options.downsampleMaxHeight / imageElement.naturalHeight
447
+ );
448
+ const targetWidth = Math.round(imageElement.naturalWidth * ratio);
449
+ const targetHeight = Math.round(imageElement.naturalHeight * ratio);
450
+ loadSource = this._resampleImageToDataURL(imageElement, targetWidth, targetHeight, this.options.downsampleQuality);
451
+ }
452
+ }
453
+ return new Promise((resolve, reject) => {
454
+ fabric.Image.fromURL(loadSource, (fabricImage) => {
455
+ try {
456
+ if (!fabricImage)
457
+ throw new Error("Image could not be loaded");
458
+ this.canvas.discardActiveObject();
459
+ this._hideAllMaskLabels();
460
+ this.canvas.clear();
461
+ this.canvas.setBackgroundColor(this.options.backgroundColor, this.canvas.renderAll.bind(this.canvas));
462
+ fabricImage.set({ originX: "left", originY: "top", selectable: false, evented: false });
463
+ const imageWidth = fabricImage.width;
464
+ const imageHeight = fabricImage.height;
465
+ const viewport = this._getContainerViewportSize();
466
+ const minWidth = viewport.width;
467
+ const minHeight = viewport.height;
468
+ if (this.options.fitImageToCanvas) {
469
+ const canvasWidth = Math.max(1, Math.min(this.options.canvasWidth, minWidth) - 1);
470
+ const canvasHeight = Math.max(1, Math.min(this.options.canvasHeight, minHeight) - 1);
471
+ this._setCanvasSizeInt(canvasWidth, canvasHeight);
472
+ const fitScale = Math.min(canvasWidth / imageWidth, canvasHeight / imageHeight, 1);
473
+ fabricImage.set({ left: 0, top: 0 });
474
+ fabricImage.scale(fitScale);
475
+ this.baseImageScale = fabricImage.scaleX || 1;
476
+ } else if (this.options.coverImageToCanvas) {
477
+ const layout = this._calculateCoverCanvasLayout(imageWidth, imageHeight);
478
+ this._setCanvasSizeInt(layout.canvasWidth, layout.canvasHeight);
479
+ fabricImage.set({ left: 0, top: 0 });
480
+ fabricImage.scale(layout.scale);
481
+ this.baseImageScale = fabricImage.scaleX || 1;
482
+ } else if (this.options.expandCanvasToImage) {
483
+ const canvasWidth = Math.max(minWidth, Math.floor(imageWidth));
484
+ const canvasHeight = Math.max(minHeight, Math.floor(imageHeight));
485
+ this._setCanvasSizeInt(canvasWidth, canvasHeight);
486
+ fabricImage.set({ left: 0, top: 0 });
487
+ fabricImage.scale(1);
488
+ this.baseImageScale = 1;
489
+ } else {
490
+ const canvasWidth = Math.max(this.options.canvasWidth, minWidth);
491
+ const canvasHeight = Math.max(this.options.canvasHeight, minHeight);
492
+ this._setCanvasSizeInt(canvasWidth, canvasHeight);
493
+ const fitScale = Math.min(canvasWidth / imageWidth, canvasHeight / imageHeight, 1);
494
+ fabricImage.set({ left: 0, top: 0 });
495
+ fabricImage.scale(fitScale);
496
+ this.baseImageScale = fabricImage.scaleX || 1;
497
+ }
498
+ this.originalImage = fabricImage;
499
+ this.canvas.add(fabricImage);
500
+ this.canvas.sendToBack(fabricImage);
501
+ this._lastMask = null;
502
+ this._lastMaskInitialLeft = null;
503
+ this._lastMaskInitialTop = null;
504
+ this._lastMaskInitialWidth = null;
505
+ this.maskCounter = 0;
506
+ this.currentScale = 1;
507
+ this.currentRotation = 0;
508
+ this._updateInputs();
509
+ this._updateMaskList();
510
+ this.isImageLoadedToCanvas = true;
511
+ this._updateUI();
512
+ this.canvas.renderAll();
513
+ try {
514
+ this._lastSnapshot = this._serializeCanvasState();
515
+ } catch (error) {
516
+ this._reportWarning("loadImage: failed to capture initial canvas snapshot", error);
517
+ }
518
+ if (typeof this.onImageLoaded === "function") {
519
+ this.onImageLoaded();
520
+ }
521
+ resolve();
522
+ } catch (error) {
523
+ reject(error);
524
+ }
525
+ }, { crossOrigin: "anonymous" });
526
+ });
527
+ }
528
+ /**
529
+ * Checks whether there is a loaded image on the current canvas.
530
+ * @returns {boolean} true if loaded, false if not
531
+ */
532
+ isImageLoaded() {
533
+ const fabricInstance = ensureFabric();
534
+ return !!(this.originalImage && fabricInstance && this.originalImage instanceof fabricInstance.Image && this.originalImage.width > 0 && this.originalImage.height > 0);
535
+ }
536
+ /**
537
+ * Creates an HTMLImageElement from a given data URL.
538
+ *
539
+ * @param {string} dataUrl - A data URL representing the image (e.g., "data:image/png;base64,...").
540
+ * @returns {Promise<HTMLImageElement>} A promise that resolves to the created image element when loaded, or rejects on error.
541
+ * @private
542
+ */
543
+ _createImageElement(dataUrl) {
544
+ return new Promise((resolve, reject) => {
545
+ const imageElement = new Image();
546
+ imageElement.onload = () => {
547
+ imageElement.onload = null;
548
+ imageElement.onerror = null;
549
+ resolve(imageElement);
550
+ };
551
+ imageElement.onerror = (error) => {
552
+ imageElement.onload = null;
553
+ imageElement.onerror = null;
554
+ reject(error);
555
+ };
556
+ imageElement.src = dataUrl;
557
+ });
558
+ }
559
+ /**
560
+ * Resamples the given image element to a new width and height and returns the result as a JPEG data URL.
561
+ *
562
+ * @param {HTMLImageElement} imageElement - The image element to resample.
563
+ * @param {number} targetWidth - Target width (in pixels) for the resampled image.
564
+ * @param {number} targetHeight - Target height (in pixels) for the resampled image.
565
+ * @param {number} [quality=0.92] - JPEG image quality between 0 and 1 (optional, default 0.92).
566
+ * @returns {string} A data URL representing the resampled image as JPEG.
567
+ * @private
568
+ */
569
+ _resampleImageToDataURL(imageElement, targetWidth, targetHeight, quality = 0.92) {
570
+ const offscreenCanvas = document.createElement("canvas");
571
+ offscreenCanvas.width = targetWidth;
572
+ offscreenCanvas.height = targetHeight;
573
+ const context = offscreenCanvas.getContext("2d");
574
+ context.drawImage(imageElement, 0, 0, imageElement.naturalWidth, imageElement.naturalHeight, 0, 0, targetWidth, targetHeight);
575
+ return offscreenCanvas.toDataURL("image/jpeg", quality);
576
+ }
577
+ /**
578
+ * Sets canvas size to integer width and height values to prevent scrollbars due to sub-pixel rendering.
579
+ * Also updates the corresponding style attributes.
580
+ *
581
+ * @param {number} w - Canvas width (in pixels).
582
+ * @param {number} h - Canvas height (in pixels).
583
+ * @private
584
+ */
585
+ _setCanvasSizeInt(w, h) {
586
+ const iw = Math.max(1, Math.round(Number(w) || 1));
587
+ const ih = Math.max(1, Math.round(Number(h) || 1));
588
+ this.canvas.setWidth(iw);
589
+ this.canvas.setHeight(ih);
590
+ if (typeof this.canvas.calcOffset === "function")
591
+ this.canvas.calcOffset();
592
+ if (this.canvasElement) {
593
+ this.canvasElement.style.width = iw + "px";
594
+ this.canvasElement.style.height = ih + "px";
595
+ this.canvasElement.style.maxWidth = "none";
596
+ }
597
+ }
598
+ _ceilCanvasDimension(value) {
599
+ const numericValue = Number(value) || 0;
600
+ const roundedValue = Math.round(numericValue);
601
+ if (Math.abs(numericValue - roundedValue) < 0.01)
602
+ return roundedValue;
603
+ return Math.ceil(numericValue);
604
+ }
605
+ _getContainerViewportSize() {
606
+ if (!this.containerElement) {
607
+ return {
608
+ width: Math.max(1, Math.floor(this.options.canvasWidth || 1)),
609
+ height: Math.max(1, Math.floor(this.options.canvasHeight || 1))
610
+ };
611
+ }
612
+ if (this._hasFixedContainerScrollbars()) {
613
+ return {
614
+ width: Math.max(1, Math.floor(this.containerElement.clientWidth || this.options.canvasWidth || 1)),
615
+ height: Math.max(1, Math.floor(this.containerElement.clientHeight || this.options.canvasHeight || 1))
616
+ };
617
+ }
618
+ const previousOverflow = this.containerElement.style.overflow;
619
+ this.containerElement.style.overflow = "hidden";
620
+ const width = Math.max(1, Math.floor(this.containerElement.clientWidth || this.options.canvasWidth || 1));
621
+ const height = Math.max(1, Math.floor(this.containerElement.clientHeight || this.options.canvasHeight || 1));
622
+ this.containerElement.style.overflow = previousOverflow;
623
+ return { width, height };
624
+ }
625
+ _hasFixedContainerScrollbars() {
626
+ if (!this.containerElement)
627
+ return false;
628
+ const inlineOverflow = this.containerElement.style.overflow;
629
+ const inlineOverflowX = this.containerElement.style.overflowX;
630
+ const inlineOverflowY = this.containerElement.style.overflowY;
631
+ let computedOverflow = "";
632
+ let computedOverflowX = "";
633
+ let computedOverflowY = "";
634
+ if (typeof window !== "undefined" && typeof window.getComputedStyle === "function") {
635
+ const style = window.getComputedStyle(this.containerElement);
636
+ computedOverflow = style.overflow;
637
+ computedOverflowX = style.overflowX;
638
+ computedOverflowY = style.overflowY;
639
+ }
640
+ return [inlineOverflow, inlineOverflowX, inlineOverflowY, computedOverflow, computedOverflowX, computedOverflowY].some((value) => value === "scroll");
641
+ }
642
+ _getScrollbarSize() {
643
+ if (typeof document === "undefined" || !document.createElement || !document.body) {
644
+ return { width: 0, height: 0 };
645
+ }
646
+ const probe = document.createElement("div");
647
+ probe.style.position = "absolute";
648
+ probe.style.visibility = "hidden";
649
+ probe.style.overflow = "scroll";
650
+ probe.style.width = "100px";
651
+ probe.style.height = "100px";
652
+ probe.style.top = "-9999px";
653
+ document.body.appendChild(probe);
654
+ const width = Math.max(0, probe.offsetWidth - probe.clientWidth);
655
+ const height = Math.max(0, probe.offsetHeight - probe.clientHeight);
656
+ document.body.removeChild(probe);
657
+ return { width, height };
658
+ }
659
+ _getScrollSafetyMargin() {
660
+ return 2;
661
+ }
662
+ _getScrollableCanvasSize(contentWidth, contentHeight, viewport = this._getContainerViewportSize()) {
663
+ if (this._hasFixedContainerScrollbars()) {
664
+ const safetyMargin = this._getScrollSafetyMargin();
665
+ const safeWidth = Math.max(1, viewport.width - safetyMargin);
666
+ const safeHeight = Math.max(1, viewport.height - safetyMargin);
667
+ return {
668
+ width: contentWidth > viewport.width + 0.5 ? this._ceilCanvasDimension(contentWidth) : safeWidth,
669
+ height: contentHeight > viewport.height + 0.5 ? this._ceilCanvasDimension(contentHeight) : safeHeight,
670
+ viewportWidth: viewport.width,
671
+ viewportHeight: viewport.height,
672
+ hasHorizontal: true,
673
+ hasVertical: true
674
+ };
675
+ }
676
+ const scrollbar = this._getScrollbarSize();
677
+ let hasVertical = false;
678
+ let hasHorizontal = false;
679
+ let effectiveWidth = viewport.width;
680
+ let effectiveHeight = viewport.height;
681
+ for (let i = 0; i < 4; i += 1) {
682
+ effectiveWidth = Math.max(1, viewport.width - (hasVertical ? scrollbar.width : 0));
683
+ effectiveHeight = Math.max(1, viewport.height - (hasHorizontal ? scrollbar.height : 0));
684
+ const nextHasVertical = contentHeight > effectiveHeight + 0.5;
685
+ const nextHasHorizontal = contentWidth > effectiveWidth + 0.5;
686
+ if (nextHasVertical === hasVertical && nextHasHorizontal === hasHorizontal)
687
+ break;
688
+ hasVertical = nextHasVertical;
689
+ hasHorizontal = nextHasHorizontal;
690
+ }
691
+ effectiveWidth = Math.max(1, viewport.width - (hasVertical ? scrollbar.width : 0));
692
+ effectiveHeight = Math.max(1, viewport.height - (hasHorizontal ? scrollbar.height : 0));
693
+ return {
694
+ width: hasHorizontal ? this._ceilCanvasDimension(contentWidth) : effectiveWidth,
695
+ height: hasVertical ? this._ceilCanvasDimension(contentHeight) : effectiveHeight,
696
+ viewportWidth: effectiveWidth,
697
+ viewportHeight: effectiveHeight,
698
+ hasHorizontal,
699
+ hasVertical
700
+ };
701
+ }
702
+ _calculateCoverCanvasLayout(imageWidth, imageHeight) {
703
+ const viewport = this._getContainerViewportSize();
704
+ if (this._hasFixedContainerScrollbars()) {
705
+ const safetyMargin = this._getScrollSafetyMargin();
706
+ const targetWidth = Math.max(1, viewport.width - safetyMargin);
707
+ const targetHeight = Math.max(1, viewport.height - safetyMargin);
708
+ const scale2 = Math.min(1, Math.max(targetWidth / imageWidth, targetHeight / imageHeight));
709
+ const contentWidth2 = imageWidth * scale2;
710
+ const contentHeight2 = imageHeight * scale2;
711
+ const canvasSize2 = this._getScrollableCanvasSize(contentWidth2, contentHeight2, viewport);
712
+ return {
713
+ scale: scale2,
714
+ canvasWidth: canvasSize2.width,
715
+ canvasHeight: canvasSize2.height
716
+ };
717
+ }
718
+ const scrollbar = this._getScrollbarSize();
719
+ let hasVertical = false;
720
+ let hasHorizontal = false;
721
+ let scale = 1;
722
+ let contentWidth = imageWidth;
723
+ let contentHeight = imageHeight;
724
+ let effectiveWidth = viewport.width;
725
+ let effectiveHeight = viewport.height;
726
+ for (let i = 0; i < 4; i += 1) {
727
+ effectiveWidth = Math.max(1, viewport.width - (hasVertical ? scrollbar.width : 0));
728
+ effectiveHeight = Math.max(1, viewport.height - (hasHorizontal ? scrollbar.height : 0));
729
+ scale = Math.min(1, Math.max(effectiveWidth / imageWidth, effectiveHeight / imageHeight));
730
+ contentWidth = imageWidth * scale;
731
+ contentHeight = imageHeight * scale;
732
+ const nextHasVertical = contentHeight > effectiveHeight + 0.5;
733
+ const nextHasHorizontal = contentWidth > effectiveWidth + 0.5;
734
+ if (nextHasVertical === hasVertical && nextHasHorizontal === hasHorizontal)
735
+ break;
736
+ hasVertical = nextHasVertical;
737
+ hasHorizontal = nextHasHorizontal;
738
+ }
739
+ const canvasSize = this._getScrollableCanvasSize(contentWidth, contentHeight, viewport);
740
+ return {
741
+ scale,
742
+ canvasWidth: canvasSize.width,
743
+ canvasHeight: canvasSize.height
744
+ };
745
+ }
746
+ _getStateProperties() {
747
+ return [
748
+ "maskId",
749
+ "maskName",
750
+ "maskLabel",
751
+ "isCropRect",
752
+ "originalAlpha",
753
+ "originalStroke",
754
+ "originalStrokeWidth",
755
+ "selectable",
756
+ "evented",
757
+ "hasControls",
758
+ "lockRotation",
759
+ "borderColor",
760
+ "cornerColor",
761
+ "cornerSize",
762
+ "transparentCorners",
763
+ "strokeUniform",
764
+ "strokeDashArray"
765
+ ];
766
+ }
767
+ _getMaskNormalStyle(mask) {
768
+ const strokeWidth = Number(mask && mask.originalStrokeWidth);
769
+ const opacity = Number(mask && mask.originalAlpha);
770
+ const style = {
771
+ stroke: mask && mask.originalStroke || "#ccc",
772
+ strokeWidth: Number.isFinite(strokeWidth) ? strokeWidth : 1
773
+ };
774
+ if (Number.isFinite(opacity))
775
+ style.opacity = opacity;
776
+ return style;
777
+ }
778
+ _withNormalizedMaskStyles(callback) {
779
+ if (!this.canvas)
780
+ return callback();
781
+ const masks = this.canvas.getObjects().filter((object) => object.maskId);
782
+ const maskStyleBackups = masks.map((mask) => ({
783
+ object: mask,
784
+ stroke: mask.stroke,
785
+ strokeWidth: mask.strokeWidth,
786
+ opacity: mask.opacity
787
+ }));
788
+ try {
789
+ masks.forEach((mask) => {
790
+ mask.set(this._getMaskNormalStyle(mask));
791
+ });
792
+ return callback();
793
+ } finally {
794
+ maskStyleBackups.forEach((backup) => {
795
+ try {
796
+ backup.object.set({
797
+ stroke: backup.stroke,
798
+ strokeWidth: backup.strokeWidth,
799
+ opacity: backup.opacity
800
+ });
801
+ } catch (error) {
802
+ }
803
+ });
804
+ }
805
+ }
806
+ _restoreMaskControls(mask) {
807
+ if (!mask)
808
+ return;
809
+ const cornerSize = Number(mask.cornerSize);
810
+ mask.set({
811
+ selectable: mask.selectable !== false,
812
+ evented: mask.evented !== false,
813
+ hasControls: mask.hasControls !== false,
814
+ lockRotation: typeof mask.lockRotation === "boolean" ? mask.lockRotation : !this.options.maskRotatable,
815
+ borderColor: mask.borderColor || "red",
816
+ cornerColor: mask.cornerColor || "black",
817
+ cornerSize: Number.isFinite(cornerSize) ? cornerSize : 8,
818
+ transparentCorners: mask.transparentCorners === true,
819
+ strokeUniform: mask.strokeUniform !== false
820
+ });
821
+ if (typeof mask.setCoords === "function")
822
+ mask.setCoords();
823
+ }
824
+ _serializeCanvasState() {
825
+ if (!this.canvas)
826
+ return null;
827
+ return this._withNormalizedMaskStyles(() => {
828
+ const jsonObject = this.canvas.toJSON(this._getStateProperties());
829
+ if (Array.isArray(jsonObject.objects)) {
830
+ jsonObject.objects = jsonObject.objects.filter((object) => !object.isCropRect && !object.maskLabel);
831
+ }
832
+ return JSON.stringify(jsonObject);
833
+ });
834
+ }
835
+ _normalizeQuality(quality) {
836
+ const numericQuality = Number(quality);
837
+ if (!Number.isFinite(numericQuality))
838
+ return this.options.downsampleQuality ?? 0.92;
839
+ return Math.max(0, Math.min(1, numericQuality));
840
+ }
841
+ _normalizeImageFormat(format) {
842
+ const typeMapping = {
843
+ "jpeg": "jpeg",
844
+ "jpg": "jpeg",
845
+ "image/jpeg": "jpeg",
846
+ "png": "png",
847
+ "image/png": "png",
848
+ "webp": "webp",
849
+ "image/webp": "webp"
850
+ };
851
+ return typeMapping[String(format || "jpeg").toLowerCase()] || "jpeg";
852
+ }
853
+ _getClampedCanvasRegion(bounds, options = {}) {
854
+ const canvasWidth = Math.max(1, Math.round(this.canvas.getWidth()));
855
+ const canvasHeight = Math.max(1, Math.round(this.canvas.getHeight()));
856
+ const left = Number(bounds.left) || 0;
857
+ const top = Number(bounds.top) || 0;
858
+ const width = Math.max(0, Number(bounds.width) || 0);
859
+ const height = Math.max(0, Number(bounds.height) || 0);
860
+ const includePartialPixels = options.includePartialPixels !== false;
861
+ const roundEnd = includePartialPixels ? Math.ceil : Math.floor;
862
+ const sourceX = Math.min(canvasWidth - 1, Math.max(0, Math.floor(left)));
863
+ const sourceY = Math.min(canvasHeight - 1, Math.max(0, Math.floor(top)));
864
+ const endX = Math.min(canvasWidth, Math.max(sourceX + 1, roundEnd(left + width)));
865
+ const endY = Math.min(canvasHeight, Math.max(sourceY + 1, roundEnd(top + height)));
866
+ return {
867
+ sx: sourceX,
868
+ sy: sourceY,
869
+ sw: Math.max(1, endX - sourceX),
870
+ sh: Math.max(1, endY - sourceY)
871
+ };
872
+ }
873
+ async _cropDataUrl(dataUrl, sourceX, sourceY, sourceWidth, sourceHeight, multiplier, format = "jpeg", quality = 0.92) {
874
+ return new Promise((resolve, reject) => {
875
+ const imageElement = new Image();
876
+ imageElement.onload = () => {
877
+ try {
878
+ const safeMultiplier = Math.max(1, Number(multiplier) || 1);
879
+ const scaledSourceX = Math.round(sourceX * safeMultiplier);
880
+ const scaledSourceY = Math.round(sourceY * safeMultiplier);
881
+ const scaledSourceWidth = Math.max(1, Math.round(sourceWidth * safeMultiplier));
882
+ const scaledSourceHeight = Math.max(1, Math.round(sourceHeight * safeMultiplier));
883
+ const offscreenCanvas = document.createElement("canvas");
884
+ offscreenCanvas.width = scaledSourceWidth;
885
+ offscreenCanvas.height = scaledSourceHeight;
886
+ const context = offscreenCanvas.getContext("2d");
887
+ context.drawImage(imageElement, scaledSourceX, scaledSourceY, scaledSourceWidth, scaledSourceHeight, 0, 0, scaledSourceWidth, scaledSourceHeight);
888
+ resolve(offscreenCanvas.toDataURL(`image/${format}`, quality));
889
+ } catch (error) {
890
+ reject(error);
891
+ }
892
+ };
893
+ imageElement.onerror = reject;
894
+ imageElement.src = dataUrl;
895
+ });
896
+ }
897
+ async _exportCanvasRegionToDataURL({ sx, sy, sw, sh, multiplier = 1, quality = 0.92, format = "jpeg" }) {
898
+ const safeMultiplier = Math.max(1, Number(multiplier) || 1);
899
+ const fullDataUrl = this.canvas.toDataURL({
900
+ format,
901
+ quality,
902
+ multiplier: safeMultiplier
903
+ });
904
+ return this._cropDataUrl(fullDataUrl, sx, sy, sw, sh, safeMultiplier, format, quality);
905
+ }
906
+ /**
907
+ * Gets the top-left corner coordinates of the given object.
908
+ * Used for geometry calculations (e.g., scale, rotate).
909
+ *
910
+ * @param {Object} fabricObject - The object for which to get the top-left coordinates. Should support setCoords and getCoords/getBoundingRect methods.
911
+ * @returns {{x: number, y: number}} The top-left corner point as an object with x and y properties.
912
+ * @private
913
+ */
914
+ _getObjectTopLeftPoint(fabricObject) {
915
+ if (!fabricObject)
916
+ return { x: 0, y: 0 };
917
+ fabricObject.setCoords();
918
+ const coords = typeof fabricObject.getCoords === "function" ? fabricObject.getCoords() : null;
919
+ if (coords && coords.length)
920
+ return coords[0];
921
+ const boundingRect = fabricObject.getBoundingRect(true, true);
922
+ return { x: boundingRect.left, y: boundingRect.top };
923
+ }
924
+ /**
925
+ * Sets the object's origin at the specified origin point, keeping a reference point fixed in position.
926
+ *
927
+ * @param {Object} fabricObject - The object to modify. Should support set, setPositionByOrigin, and setCoords.
928
+ * @param {string} originX - The new originX ("left", "center", "right", etc.).
929
+ * @param {string} originY - The new originY ("top", "center", "bottom", etc.).
930
+ * @param {{x: number, y: number}} refPoint - The point to keep fixed while setting the new origins.
931
+ * @private
932
+ */
933
+ _setObjectOriginKeepingPosition(fabricObject, originX, originY, refPoint) {
934
+ if (!fabricObject || !refPoint || !fabricObject.setPositionByOrigin)
935
+ return;
936
+ fabricObject.set({ originX, originY });
937
+ fabricObject.setPositionByOrigin(refPoint, originX, originY);
938
+ fabricObject.setCoords();
939
+ }
940
+ /**
941
+ * Moves the object so its bounding box aligns with the canvas's top-left corner (0, 0).
942
+ *
943
+ * @param {Object} fabricObject - The object to align.
944
+ * @private
945
+ */
946
+ _alignObjectBoundingBoxToCanvasTopLeft(fabricObject) {
947
+ if (!fabricObject)
948
+ return;
949
+ fabricObject.setCoords();
950
+ const boundingRect = fabricObject.getBoundingRect(true, true);
951
+ const deltaX = boundingRect.left;
952
+ const deltaY = boundingRect.top;
953
+ fabricObject.set({ left: (fabricObject.left || 0) - deltaX, top: (fabricObject.top || 0) - deltaY });
954
+ fabricObject.setCoords();
955
+ this.canvas.renderAll();
956
+ }
957
+ /**
958
+ * Updates the canvas size to match the bounding box of the original image,
959
+ * ensuring that the canvas is always at least as large as its container.
960
+ * @private
961
+ */
962
+ _updateCanvasSizeToImageBounds() {
963
+ if (!this.originalImage)
964
+ return;
965
+ this.originalImage.setCoords();
966
+ const imageBounds = this.originalImage.getBoundingRect(true, true);
967
+ const size = this._getScrollableCanvasSize(imageBounds.width, imageBounds.height);
968
+ this._setCanvasSizeInt(size.width, size.height);
969
+ }
970
+ _expandCanvasToFitObject(fabricObject, padding = 10) {
971
+ if (!this.canvas || !fabricObject || !this.options.expandCanvasToImage)
972
+ return;
973
+ try {
974
+ fabricObject.setCoords();
975
+ const boundingRect = fabricObject.getBoundingRect(true, true);
976
+ const requiredWidth = Math.ceil(boundingRect.left + boundingRect.width + padding);
977
+ const requiredHeight = Math.ceil(boundingRect.top + boundingRect.height + padding);
978
+ const minWidth = this.containerElement ? Math.floor(this.containerElement.clientWidth || 0) : 0;
979
+ const minHeight = this.containerElement ? Math.floor(this.containerElement.clientHeight || 0) : 0;
980
+ const newWidth = Math.max(this.canvas.getWidth(), minWidth, requiredWidth);
981
+ const newHeight = Math.max(this.canvas.getHeight(), minHeight, requiredHeight);
982
+ this._setCanvasSizeInt(newWidth, newHeight);
983
+ } catch (error) {
984
+ this._reportWarning("expandCanvasToFitObject: failed to expand canvas", error);
985
+ }
986
+ }
987
+ /**
988
+ * Scales the original image by a given factor, with animation.
989
+ * Returns a promise that resolves when the scale animation is complete.
990
+ * @param {number} factor - The scaling factor (will be clamped between `options.minScale` and `options.maxScale`).
991
+ * @returns {Promise<void>} Promise that resolves once the scaling animation finishes.
992
+ * @public
993
+ */
994
+ scaleImage(factor, options = {}) {
995
+ return this.animQueue.add(() => this._scaleImageImpl(factor, options));
996
+ }
997
+ /**
998
+ * Scales the original image by a given factor, with animation.
999
+ * Returns a promise that resolves when the scale animation is complete.
1000
+ * @param {number} factor - The scaling factor (will be clamped between `options.minScale` and `options.maxScale`).
1001
+ * @returns {Promise<void>} Promise that resolves once the scaling animation finishes.
1002
+ * @private
1003
+ */
1004
+ _scaleImageImpl(factor, options = {}) {
1005
+ if (!this.originalImage)
1006
+ return Promise.resolve();
1007
+ if (this.isAnimating)
1008
+ return Promise.resolve();
1009
+ const saveHistory = options.saveHistory !== false;
1010
+ factor = Math.max(this.options.minScale, Math.min(this.options.maxScale, factor));
1011
+ this.currentScale = factor;
1012
+ this.isAnimating = true;
1013
+ this._updateUI();
1014
+ const targetScale = this.baseImageScale * factor;
1015
+ const topLeft = this._getObjectTopLeftPoint(this.originalImage);
1016
+ this._setObjectOriginKeepingPosition(this.originalImage, "left", "top", topLeft);
1017
+ const scaleXAnimation = new Promise((resolve) => {
1018
+ this.originalImage.animate("scaleX", targetScale, {
1019
+ duration: this.options.animationDuration,
1020
+ onChange: this.canvas.renderAll.bind(this.canvas),
1021
+ onComplete: resolve
1022
+ });
1023
+ });
1024
+ const scaleYAnimation = new Promise((resolve) => {
1025
+ this.originalImage.animate("scaleY", targetScale, {
1026
+ duration: this.options.animationDuration,
1027
+ onChange: this.canvas.renderAll.bind(this.canvas),
1028
+ onComplete: resolve
1029
+ });
1030
+ });
1031
+ return Promise.all([scaleXAnimation, scaleYAnimation]).then(() => {
1032
+ this.originalImage.set({ scaleX: targetScale, scaleY: targetScale });
1033
+ this.originalImage.setCoords();
1034
+ if (this.options.expandCanvasToImage || this.options.coverImageToCanvas) {
1035
+ this._updateCanvasSizeToImageBounds();
1036
+ }
1037
+ this._alignObjectBoundingBoxToCanvasTopLeft(this.originalImage);
1038
+ this.canvas.getObjects().forEach((object) => {
1039
+ if (object.maskId)
1040
+ this._syncMaskLabel(object);
1041
+ });
1042
+ this.isAnimating = false;
1043
+ this._updateInputs();
1044
+ this._updateUI();
1045
+ if (saveHistory)
1046
+ this.saveState();
1047
+ }).catch(() => {
1048
+ this.isAnimating = false;
1049
+ this._updateUI();
1050
+ });
1051
+ }
1052
+ /**
1053
+ * Rotates the original image by a given number of degrees, with animation.
1054
+ * Returns a promise that resolves when the rotation animation is complete.
1055
+ * @param {number} degrees - The angle in degrees to rotate the image.
1056
+ * @returns {Promise<void>} Promise that resolves once the rotation animation finishes.
1057
+ * @public
1058
+ */
1059
+ rotateImage(degrees, options = {}) {
1060
+ return this.animQueue.add(() => this._rotateImageImpl(degrees, options));
1061
+ }
1062
+ /**
1063
+ * Rotates the original image by a given number of degrees, with animation.
1064
+ * Returns a promise that resolves when the rotation animation is complete.
1065
+ * @param {number} degrees - The angle in degrees to rotate the image.
1066
+ * @returns {Promise<void>} Promise that resolves once the rotation animation finishes.
1067
+ * @private
1068
+ */
1069
+ _rotateImageImpl(degrees, options = {}) {
1070
+ if (!this.originalImage)
1071
+ return Promise.resolve();
1072
+ if (this.isAnimating)
1073
+ return Promise.resolve();
1074
+ if (isNaN(degrees))
1075
+ return Promise.resolve();
1076
+ const saveHistory = options.saveHistory !== false;
1077
+ this.currentRotation = degrees;
1078
+ this.isAnimating = true;
1079
+ this._updateUI();
1080
+ const center = this.originalImage.getCenterPoint();
1081
+ this._setObjectOriginKeepingPosition(this.originalImage, "center", "center", center);
1082
+ const rotationAnimation = new Promise((resolve) => {
1083
+ this.originalImage.animate("angle", degrees, {
1084
+ duration: this.options.animationDuration,
1085
+ onChange: this.canvas.renderAll.bind(this.canvas),
1086
+ onComplete: resolve
1087
+ });
1088
+ });
1089
+ return rotationAnimation.then(() => {
1090
+ this.originalImage.set("angle", degrees);
1091
+ this.originalImage.setCoords();
1092
+ if (this.options.expandCanvasToImage || this.options.coverImageToCanvas) {
1093
+ this._updateCanvasSizeToImageBounds();
1094
+ }
1095
+ this._alignObjectBoundingBoxToCanvasTopLeft(this.originalImage);
1096
+ const newTopLeft = this._getObjectTopLeftPoint(this.originalImage);
1097
+ this._setObjectOriginKeepingPosition(this.originalImage, "left", "top", newTopLeft);
1098
+ this.canvas.getObjects().forEach((object) => {
1099
+ if (object.maskId)
1100
+ this._syncMaskLabel(object);
1101
+ });
1102
+ this.isAnimating = false;
1103
+ this._updateInputs();
1104
+ this._updateUI();
1105
+ if (saveHistory)
1106
+ this.saveState();
1107
+ }).catch(() => {
1108
+ this.isAnimating = false;
1109
+ this._updateUI();
1110
+ });
1111
+ }
1112
+ /**
1113
+ * Resets the image transform: scales to 1 and rotates to 0 degrees.
1114
+ * @returns {Promise<void>} Promise that resolves when reset is complete.
1115
+ */
1116
+ resetImageTransform() {
1117
+ if (!this.originalImage)
1118
+ return Promise.resolve();
1119
+ return this.animQueue.add(async () => {
1120
+ const before = this._serializeCanvasState();
1121
+ await this._scaleImageImpl(1, { saveHistory: false });
1122
+ await this._rotateImageImpl(0, { saveHistory: false });
1123
+ const after = this._serializeCanvasState();
1124
+ this._pushStateTransition(before, after);
1125
+ }).catch((err) => {
1126
+ this._reportError("resetImageTransform() failed", err);
1127
+ });
1128
+ }
1129
+ /**
1130
+ * @deprecated Use resetImageTransform() instead.
1131
+ */
1132
+ reset() {
1133
+ return this.resetImageTransform();
1134
+ }
1135
+ /**
1136
+ * Restores a canvas state that was previously stored by saveState().
1137
+ * @param {string} jsonString - the JSON string returned by fabric.toJSON().
1138
+ */
1139
+ loadFromState(jsonString) {
1140
+ if (!jsonString || !this.canvas)
1141
+ return Promise.resolve();
1142
+ return new Promise((resolve) => {
1143
+ try {
1144
+ const json = typeof jsonString === "string" ? JSON.parse(jsonString) : jsonString;
1145
+ this.canvas.loadFromJSON(json, () => {
1146
+ try {
1147
+ this._hideAllMaskLabels();
1148
+ const canvasObjects = this.canvas.getObjects();
1149
+ this.originalImage = canvasObjects.find((object) => object.type === "image" && !object.maskId) || null;
1150
+ if (this.originalImage) {
1151
+ this.originalImage.set({ originX: "left", originY: "top", selectable: false, evented: false, hasControls: false, hoverCursor: "default" });
1152
+ this.canvas.sendToBack(this.originalImage);
1153
+ this.currentRotation = Number(this.originalImage.angle) || 0;
1154
+ const baseScale = Number(this.baseImageScale) || 1;
1155
+ const imageScale = Number(this.originalImage.scaleX) || baseScale;
1156
+ this.currentScale = imageScale / baseScale;
1157
+ } else {
1158
+ this.currentScale = 1;
1159
+ this.currentRotation = 0;
1160
+ }
1161
+ const masks = canvasObjects.filter((object) => object.maskId);
1162
+ masks.forEach((mask) => {
1163
+ this._restoreMaskControls(mask);
1164
+ this._rebindMaskEvents(mask);
1165
+ mask.set(this._getMaskNormalStyle(mask));
1166
+ });
1167
+ this.maskCounter = masks.reduce((max, mask) => Math.max(max, mask.maskId), 0);
1168
+ this._lastMask = masks.length ? masks[masks.length - 1] : null;
1169
+ if (!this._lastMask) {
1170
+ this._lastMaskInitialLeft = null;
1171
+ this._lastMaskInitialTop = null;
1172
+ this._lastMaskInitialWidth = null;
1173
+ }
1174
+ this.isImageLoadedToCanvas = !!this.originalImage;
1175
+ this.canvas.renderAll();
1176
+ this._updateInputs();
1177
+ this._updateMaskList();
1178
+ this._updatePlaceholderStatus();
1179
+ this._lastSnapshot = this._serializeCanvasState();
1180
+ this._updateUI();
1181
+ } catch (callbackError) {
1182
+ this._reportError("loadFromState() failed", callbackError);
1183
+ } finally {
1184
+ resolve();
1185
+ }
1186
+ });
1187
+ } catch (error) {
1188
+ this._reportError("loadFromState() failed", error);
1189
+ resolve();
1190
+ }
1191
+ });
1192
+ }
1193
+ /**
1194
+ * Saves the current state of the canvas to history, storing any mask/raster label information.
1195
+ */
1196
+ saveState() {
1197
+ if (!this.canvas)
1198
+ return;
1199
+ const activeObject = this.canvas.getActiveObject();
1200
+ this._hideAllMaskLabels();
1201
+ try {
1202
+ const after = this._serializeCanvasState();
1203
+ const before = this._lastSnapshot || after;
1204
+ if (after === before)
1205
+ return;
1206
+ let executedOnce = false;
1207
+ const command = new Command(
1208
+ () => {
1209
+ if (executedOnce) {
1210
+ return this.loadFromState(after);
1211
+ }
1212
+ executedOnce = true;
1213
+ return void 0;
1214
+ },
1215
+ () => this.loadFromState(before)
1216
+ );
1217
+ this.historyManager.execute(command);
1218
+ this._lastSnapshot = after;
1219
+ } catch (error) {
1220
+ this._reportWarning("saveState: failed to save canvas snapshot", error);
1221
+ } finally {
1222
+ if (activeObject && activeObject.maskId && this.canvas.getObjects().includes(activeObject)) {
1223
+ this._handleSelectionChanged([activeObject]);
1224
+ }
1225
+ this._updateUI();
1226
+ }
1227
+ }
1228
+ _pushStateTransition(before, after) {
1229
+ if (!before || !after)
1230
+ return;
1231
+ if (before === after)
1232
+ return;
1233
+ if (!this.historyManager)
1234
+ this.historyManager = new HistoryManager(this.maxHistorySize || 50);
1235
+ const command = new Command(
1236
+ () => this.loadFromState(after),
1237
+ () => this.loadFromState(before)
1238
+ );
1239
+ this.historyManager.push(command);
1240
+ this._lastSnapshot = after;
1241
+ this._updateUI();
1242
+ }
1243
+ /**
1244
+ * Undo the last state change, if possible.
1245
+ */
1246
+ undo() {
1247
+ return this.historyManager.undo().then(() => {
1248
+ this._updateUI();
1249
+ }).catch((error) => {
1250
+ this._reportError("undo failed", error);
1251
+ });
1252
+ }
1253
+ /**
1254
+ * Redo the next state change, if possible.
1255
+ */
1256
+ redo() {
1257
+ return this.historyManager.redo().then(() => {
1258
+ this._updateUI();
1259
+ }).catch((error) => {
1260
+ this._reportError("redo failed", error);
1261
+ });
1262
+ }
1263
+ _rebindMaskEvents(mask) {
1264
+ if (!mask)
1265
+ return;
1266
+ if (mask.__imageEditorMaskHandlers) {
1267
+ try {
1268
+ mask.off("mouseover", mask.__imageEditorMaskHandlers.mouseover);
1269
+ mask.off("mouseout", mask.__imageEditorMaskHandlers.mouseout);
1270
+ } catch (e) {
1271
+ }
1272
+ }
1273
+ const metadata = {};
1274
+ if (!Number.isFinite(Number(mask.originalAlpha))) {
1275
+ metadata.originalAlpha = Number.isFinite(Number(mask.opacity)) ? Number(mask.opacity) : 0.5;
1276
+ }
1277
+ if (!mask.originalStroke)
1278
+ metadata.originalStroke = mask.stroke || "#ccc";
1279
+ if (!Number.isFinite(Number(mask.originalStrokeWidth))) {
1280
+ metadata.originalStrokeWidth = Number.isFinite(Number(mask.strokeWidth)) ? Number(mask.strokeWidth) : 1;
1281
+ }
1282
+ if (Object.keys(metadata).length)
1283
+ mask.set(metadata);
1284
+ const normalStyle = {
1285
+ stroke: mask.originalStroke || "#ccc",
1286
+ strokeWidth: mask.originalStrokeWidth,
1287
+ opacity: mask.originalAlpha
1288
+ };
1289
+ const hoverStyle = {
1290
+ stroke: "#ff5500",
1291
+ strokeWidth: 2,
1292
+ opacity: Math.min(mask.originalAlpha + 0.2, 1)
1293
+ };
1294
+ const mouseover = () => {
1295
+ mask.set(hoverStyle);
1296
+ if (mask.canvas)
1297
+ mask.canvas.requestRenderAll();
1298
+ };
1299
+ const mouseout = () => {
1300
+ mask.set(normalStyle);
1301
+ if (mask.canvas)
1302
+ mask.canvas.requestRenderAll();
1303
+ };
1304
+ mask.on("mouseover", mouseover);
1305
+ mask.on("mouseout", mouseout);
1306
+ mask.__imageEditorMaskHandlers = { mouseover, mouseout };
1307
+ }
1308
+ /**
1309
+ * Creates a mask and adds it to the canvas.
1310
+ * Mask placement and properties are determined by the provided config and instance options.
1311
+ * Canvas and list UI are updated accordingly.
1312
+ * @param {Object} [config={}] - Optional mask configuration overrides:
1313
+ * @param {string} [config.shape='rect'] - 'rect', 'circle', 'ellipse', 'polygon', ...
1314
+ * @param {Object|Array} [config.points] - Required for polygon: [{x, y}, ...] or [[x, y], ...]
1315
+ * @param {number|function} [config.width/height/rx/ry/radius] - Can be number or function(canvas, options)
1316
+ * @param {number|string|function} [config.left/top] - Absolute, %, or function
1317
+ * @param {number|string} [config.angle] - Rotation angle (degree)
1318
+ * @param {string} [config.color] - Fill color in CSS color format (default 'rgba(0,0,0,0.5)')
1319
+ * @param {number} [config.alpha] - Opacity, from 0 to 1 (default 0.5)
1320
+ * @param {boolean} [config.selectable=true]
1321
+ * @param {Object} [config.styles] - Custom styles (stroke, dashArray, etc)
1322
+ * @param {function} [config.onCreate] - Callback after mask created (receives Fabric object)
1323
+ * @param {function} [config.fabricGenerator] - (maskConfig) => new FabricObj
1324
+ * @returns {fabric.Rect|null} The created mask object, or null if canvas is not available.
1325
+ * @public
1326
+ */
1327
+ createMask(config = {}) {
1328
+ if (!this.canvas)
1329
+ return null;
1330
+ const shapeType = config.shape || "rect";
1331
+ const maskConfig = {
1332
+ shape: shapeType,
1333
+ width: this.options.defaultMaskWidth,
1334
+ height: this.options.defaultMaskHeight,
1335
+ color: "rgba(0,0,0,0.5)",
1336
+ alpha: 0.5,
1337
+ gap: 5,
1338
+ left: void 0,
1339
+ top: void 0,
1340
+ angle: 0,
1341
+ selectable: true,
1342
+ ...config
1343
+ };
1344
+ const firstOffset = 10;
1345
+ let left = firstOffset;
1346
+ let top = firstOffset;
1347
+ const resolveValue = (value, fallback) => {
1348
+ if (typeof value === "function")
1349
+ return value(this.canvas, this.options);
1350
+ if (typeof value === "string" && value.endsWith("%")) {
1351
+ const percent = parseFloat(value) / 100;
1352
+ return Math.floor((this.canvas ? this.canvas.getWidth() : 0) * percent);
1353
+ }
1354
+ return value != null ? value : fallback;
1355
+ };
1356
+ if (maskConfig.left === void 0 && this._lastMask) {
1357
+ const previousMask = this._lastMask;
1358
+ let previousMaskRight = previousMask.left;
1359
+ if (previousMask.getScaledWidth) {
1360
+ previousMaskRight += previousMask.getScaledWidth();
1361
+ } else if (previousMask.width) {
1362
+ previousMaskRight += previousMask.width * (previousMask.scaleX ?? 1);
1363
+ }
1364
+ left = Math.round(previousMaskRight + maskConfig.gap);
1365
+ top = previousMask.top ?? firstOffset;
1366
+ } else {
1367
+ left = resolveValue(maskConfig.left, firstOffset);
1368
+ top = resolveValue(maskConfig.top, firstOffset);
1369
+ }
1370
+ maskConfig.width = resolveValue(maskConfig.width, this.options.defaultMaskWidth);
1371
+ maskConfig.height = resolveValue(maskConfig.height, this.options.defaultMaskHeight);
1372
+ let mask;
1373
+ if (typeof maskConfig.fabricGenerator === "function") {
1374
+ mask = maskConfig.fabricGenerator(maskConfig, this.canvas, this.options);
1375
+ } else {
1376
+ switch (shapeType) {
1377
+ case "circle":
1378
+ mask = new fabric.Circle({
1379
+ left,
1380
+ top,
1381
+ radius: resolveValue(maskConfig.radius, Math.min(maskConfig.width, maskConfig.height) / 2),
1382
+ fill: maskConfig.color,
1383
+ opacity: maskConfig.alpha,
1384
+ angle: maskConfig.angle,
1385
+ ...maskConfig.styles
1386
+ });
1387
+ break;
1388
+ case "ellipse":
1389
+ mask = new fabric.Ellipse({
1390
+ left,
1391
+ top,
1392
+ rx: resolveValue(maskConfig.rx, maskConfig.width / 2),
1393
+ ry: resolveValue(maskConfig.ry, maskConfig.height / 2),
1394
+ fill: maskConfig.color,
1395
+ opacity: maskConfig.alpha,
1396
+ angle: maskConfig.angle,
1397
+ ...maskConfig.styles
1398
+ });
1399
+ break;
1400
+ case "polygon": {
1401
+ let polygonPoints = maskConfig.points || [];
1402
+ if (Array.isArray(polygonPoints) && polygonPoints.length && typeof polygonPoints[0] === "object") {
1403
+ polygonPoints = polygonPoints.map((point) => ({ x: Number(point.x), y: Number(point.y) }));
1404
+ }
1405
+ mask = new fabric.Polygon(polygonPoints, {
1406
+ left,
1407
+ top,
1408
+ fill: maskConfig.color,
1409
+ opacity: maskConfig.alpha,
1410
+ angle: maskConfig.angle,
1411
+ ...maskConfig.styles
1412
+ });
1413
+ break;
1414
+ }
1415
+ case "rect":
1416
+ default:
1417
+ mask = new fabric.Rect({
1418
+ left,
1419
+ top,
1420
+ width: resolveValue(maskConfig.width, this.options.defaultMaskWidth),
1421
+ height: resolveValue(maskConfig.height, this.options.defaultMaskHeight),
1422
+ fill: maskConfig.color,
1423
+ opacity: maskConfig.alpha,
1424
+ angle: maskConfig.angle,
1425
+ rx: maskConfig.rx,
1426
+ // Rounded Corners
1427
+ ry: maskConfig.ry,
1428
+ ...maskConfig.styles
1429
+ });
1430
+ }
1431
+ }
1432
+ const styles = maskConfig.styles || {};
1433
+ const hasStyle = (property) => Object.prototype.hasOwnProperty.call(styles, property);
1434
+ const maskSettings = {
1435
+ selectable: maskConfig.selectable !== false,
1436
+ hasControls: "hasControls" in maskConfig ? maskConfig.hasControls : true,
1437
+ lockRotation: !this.options.maskRotatable,
1438
+ borderColor: "borderColor" in maskConfig ? maskConfig.borderColor : "red",
1439
+ cornerColor: "cornerColor" in maskConfig ? maskConfig.cornerColor : "black",
1440
+ cornerSize: "cornerSize" in maskConfig ? maskConfig.cornerSize : 8,
1441
+ transparentCorners: "transparentCorners" in maskConfig ? maskConfig.transparentCorners : false,
1442
+ stroke: hasStyle("stroke") ? styles.stroke : "#ccc",
1443
+ strokeWidth: hasStyle("strokeWidth") ? styles.strokeWidth : 1,
1444
+ strokeUniform: "strokeUniform" in maskConfig ? maskConfig.strokeUniform : hasStyle("strokeUniform") ? styles.strokeUniform : true
1445
+ };
1446
+ if (hasStyle("strokeDashArray"))
1447
+ maskSettings.strokeDashArray = styles.strokeDashArray;
1448
+ mask.set(maskSettings);
1449
+ mask.setCoords();
1450
+ mask.set({
1451
+ originalAlpha: maskConfig.alpha,
1452
+ originalStroke: mask.stroke || "#ccc",
1453
+ originalStrokeWidth: Number.isFinite(Number(mask.strokeWidth)) ? Number(mask.strokeWidth) : 1
1454
+ });
1455
+ this._rebindMaskEvents(mask);
1456
+ this._expandCanvasToFitObject(mask);
1457
+ this._lastMaskInitialLeft = left;
1458
+ this._lastMaskInitialTop = top;
1459
+ this._lastMaskInitialWidth = resolveValue(maskConfig.width, this.options.defaultMaskWidth);
1460
+ const maskId = ++this.maskCounter;
1461
+ mask.set({
1462
+ maskId,
1463
+ maskName: `${this.options.maskName}${maskId}`
1464
+ });
1465
+ this._lastMask = mask;
1466
+ this.canvas.add(mask);
1467
+ this.canvas.bringToFront(mask);
1468
+ if (maskConfig.selectable)
1469
+ this.canvas.setActiveObject(mask);
1470
+ this._handleSelectionChanged([mask]);
1471
+ this._updateMaskList();
1472
+ this._updateUI();
1473
+ this.canvas.renderAll();
1474
+ this.saveState();
1475
+ if (typeof maskConfig.onCreate === "function")
1476
+ maskConfig.onCreate(mask, this.canvas);
1477
+ return mask;
1478
+ }
1479
+ /**
1480
+ * @deprecated Use createMask() instead.
1481
+ */
1482
+ addMask(config = {}) {
1483
+ return this.createMask(config);
1484
+ }
1485
+ /**
1486
+ * Removes the currently selected mask from the canvas, if any.
1487
+ * The associated label is also removed. UI and mask list are updated.
1488
+ */
1489
+ removeSelectedMask() {
1490
+ const activeObject = this.canvas.getActiveObject();
1491
+ const selectedMasks = this._getModifiedMasks(activeObject);
1492
+ if (!selectedMasks.length)
1493
+ return;
1494
+ this.canvas.discardActiveObject();
1495
+ selectedMasks.forEach((mask) => {
1496
+ this._removeLabelForMask(mask);
1497
+ this.canvas.remove(mask);
1498
+ });
1499
+ const masks = this.canvas.getObjects().filter((object) => object.maskId);
1500
+ this._lastMask = masks.length ? masks[masks.length - 1] : null;
1501
+ if (!this._lastMask) {
1502
+ this._lastMaskInitialLeft = null;
1503
+ this._lastMaskInitialTop = null;
1504
+ this._lastMaskInitialWidth = null;
1505
+ }
1506
+ this._updateMaskList();
1507
+ this._updateUI();
1508
+ this.canvas.renderAll();
1509
+ this.saveState();
1510
+ }
1511
+ /**
1512
+ * Removes all masks from the canvas, including their labels.
1513
+ * UI and internal mask placement memory are reset.
1514
+ */
1515
+ removeAllMasks(options = {}) {
1516
+ const saveHistory = options.saveHistory !== false;
1517
+ const masks = this.canvas.getObjects().filter((object) => object.maskId);
1518
+ masks.forEach((mask) => this._removeLabelForMask(mask));
1519
+ masks.forEach((mask) => this.canvas.remove(mask));
1520
+ this.canvas.discardActiveObject();
1521
+ this._lastMask = null;
1522
+ this._lastMaskInitialLeft = null;
1523
+ this._lastMaskInitialTop = null;
1524
+ this._lastMaskInitialWidth = null;
1525
+ this._updateMaskList();
1526
+ this._updateUI();
1527
+ this.canvas.renderAll();
1528
+ if (saveHistory)
1529
+ this.saveState();
1530
+ }
1531
+ /**
1532
+ * Removes the label associated with the specified mask object, if it exists.
1533
+ *
1534
+ * @param {fabric.Object} mask - The mask object whose label should be removed.
1535
+ * @private
1536
+ */
1537
+ _removeLabelForMask(mask) {
1538
+ if (!mask || !this.canvas)
1539
+ return;
1540
+ if (mask.__label) {
1541
+ try {
1542
+ const canvasObjects = this.canvas.getObjects();
1543
+ if (canvasObjects.includes(mask.__label)) {
1544
+ this.canvas.remove(mask.__label);
1545
+ }
1546
+ } catch (error) {
1547
+ }
1548
+ try {
1549
+ delete mask.__label;
1550
+ } catch (error) {
1551
+ }
1552
+ }
1553
+ }
1554
+ /**
1555
+ * Creates and adds a custom label (fabric.Text or fabric.IText) for the mask.
1556
+ * The label is default bound to the top-left of the mask and managed as a non-interactive overlay.
1557
+ *
1558
+ * @param {fabric.Object} mask - The mask to create a label for.
1559
+ * @private
1560
+ */
1561
+ _createLabelForMask(mask) {
1562
+ if (!mask || !this.options.maskLabelOnSelect)
1563
+ return;
1564
+ this._removeLabelForMask(mask);
1565
+ let textObject = null;
1566
+ if (this.options.label && typeof this.options.label.create === "function") {
1567
+ textObject = this.options.label.create(mask, fabric);
1568
+ }
1569
+ if (!textObject) {
1570
+ let labelText = mask.maskName;
1571
+ let textOptions = {
1572
+ left: 0,
1573
+ top: 0,
1574
+ fontSize: 12,
1575
+ fill: "#fff",
1576
+ backgroundColor: "rgba(0,0,0,0.7)",
1577
+ selectable: false,
1578
+ evented: false,
1579
+ padding: 2,
1580
+ originX: "left",
1581
+ originY: "top"
1582
+ };
1583
+ if (this.options.label) {
1584
+ if (typeof this.options.label.getText === "function") {
1585
+ const masks = this.canvas ? this.canvas.getObjects().filter((object) => object.maskId) : [];
1586
+ const maskIndex = Math.max(0, masks.indexOf(mask));
1587
+ labelText = this.options.label.getText(mask, maskIndex);
1588
+ }
1589
+ if (this.options.label.textOptions) {
1590
+ Object.assign(textOptions, this.options.label.textOptions);
1591
+ }
1592
+ }
1593
+ textObject = new fabric.Text(labelText, textOptions);
1594
+ }
1595
+ textObject.maskLabel = true;
1596
+ mask.__label = textObject;
1597
+ this.canvas.add(textObject);
1598
+ this.canvas.bringToFront(textObject);
1599
+ this._syncMaskLabel(mask);
1600
+ }
1601
+ /**
1602
+ * Hides (removes) all mask labels from the canvas.
1603
+ * Internal label references on mask objects are also deleted.
1604
+ * @private
1605
+ */
1606
+ _hideAllMaskLabels() {
1607
+ if (!this.canvas)
1608
+ return;
1609
+ const canvasObjects = this.canvas.getObjects();
1610
+ const labels = canvasObjects.filter((object) => object.maskLabel);
1611
+ labels.forEach((label) => {
1612
+ try {
1613
+ if (canvasObjects.includes(label))
1614
+ this.canvas.remove(label);
1615
+ } catch (error) {
1616
+ }
1617
+ });
1618
+ canvasObjects.forEach((object) => {
1619
+ if (object.maskId && object.__label) {
1620
+ try {
1621
+ delete object.__label;
1622
+ } catch (error) {
1623
+ }
1624
+ }
1625
+ });
1626
+ }
1627
+ /**
1628
+ * Synchronizes the position, angle, and visibility of the mask's label so that it appears properly above the mask.
1629
+ *
1630
+ * @param {fabric.Object} mask - The mask whose label should be repositioned.
1631
+ * @private
1632
+ */
1633
+ _syncMaskLabel(mask) {
1634
+ if (!mask)
1635
+ return;
1636
+ if (!this.options.maskLabelOnSelect)
1637
+ return;
1638
+ if (!mask.__label)
1639
+ return;
1640
+ const coords = mask.getCoords ? mask.getCoords() : null;
1641
+ if (!coords || coords.length < 4)
1642
+ return;
1643
+ const tl = coords[0];
1644
+ const center = mask.getCenterPoint();
1645
+ const vx = center.x - tl.x;
1646
+ const vy = center.y - tl.y;
1647
+ const dist = Math.sqrt(vx * vx + vy * vy) || 1;
1648
+ const ux = vx / dist;
1649
+ const uy = vy / dist;
1650
+ const offset = Math.max(0, this.options.maskLabelOffset ?? 3);
1651
+ const px = tl.x + ux * offset;
1652
+ const py = tl.y + uy * offset;
1653
+ mask.__label.set({
1654
+ left: Math.round(px),
1655
+ top: Math.round(py),
1656
+ angle: mask.angle || 0,
1657
+ originX: "left",
1658
+ originY: "top",
1659
+ visible: true
1660
+ });
1661
+ mask.__label.setCoords();
1662
+ if (typeof this.canvas.requestRenderAll === "function") {
1663
+ this.canvas.requestRenderAll();
1664
+ } else {
1665
+ this.canvas.renderAll();
1666
+ }
1667
+ }
1668
+ /**
1669
+ * Shows the label for the given mask, creating it if necessary and synchronizing its position.
1670
+ *
1671
+ * @param {fabric.Object} mask - The mask whose label should be shown.
1672
+ * @private
1673
+ */
1674
+ _showLabelForMask(mask) {
1675
+ if (!mask)
1676
+ return;
1677
+ if (!this.options.maskLabelOnSelect)
1678
+ return;
1679
+ if (!mask.__label)
1680
+ this._createLabelForMask(mask);
1681
+ mask.__label.set({ visible: true });
1682
+ this._syncMaskLabel(mask);
1683
+ }
1684
+ /**
1685
+ * Handles changes to the selection of canvas objects (masks),
1686
+ * updates mask stroke and label display, and syncs mask list selection.
1687
+ *
1688
+ * @param {Array<Object>} selected - The currently selected objects (e.g. [mask] or []).
1689
+ * @private
1690
+ */
1691
+ _handleSelectionChanged(selected) {
1692
+ const selectedMask = (selected || []).find((object) => object.maskId);
1693
+ const masks = this.canvas.getObjects().filter((object) => object.maskId);
1694
+ masks.forEach((mask) => {
1695
+ if (mask !== selectedMask) {
1696
+ if (mask.__label) {
1697
+ try {
1698
+ this.canvas.remove(mask.__label);
1699
+ } catch (error) {
1700
+ }
1701
+ delete mask.__label;
1702
+ }
1703
+ const originalStrokeWidth = Number(mask.originalStrokeWidth);
1704
+ mask.set({
1705
+ stroke: mask.originalStroke || "#ccc",
1706
+ strokeWidth: Number.isFinite(originalStrokeWidth) ? originalStrokeWidth : 1
1707
+ });
1708
+ } else {
1709
+ mask.set({ stroke: "#ff0000", strokeWidth: 1 });
1710
+ }
1711
+ });
1712
+ if (selectedMask)
1713
+ this._showLabelForMask(selectedMask);
1714
+ this._updateMaskListSelection(selectedMask);
1715
+ this.canvas.renderAll();
1716
+ this._updateUI();
1717
+ }
1718
+ /**
1719
+ * Updates the mask list in the DOM to reflect the current masks on the canvas.
1720
+ * Each list entry becomes a clickable element for mask selection.
1721
+ * @private
1722
+ */
1723
+ _updateMaskList() {
1724
+ const maskListElement = document.getElementById(this.elements.maskList);
1725
+ if (!maskListElement)
1726
+ return;
1727
+ maskListElement.innerHTML = "";
1728
+ const masks = this.canvas.getObjects().filter((object) => object.maskId);
1729
+ masks.forEach((mask) => {
1730
+ const listItemElement = document.createElement("li");
1731
+ listItemElement.className = "list-group-item mask-item";
1732
+ listItemElement.textContent = mask.maskName;
1733
+ listItemElement.onclick = () => {
1734
+ this.canvas.setActiveObject(mask);
1735
+ this._handleSelectionChanged([mask]);
1736
+ };
1737
+ maskListElement.appendChild(listItemElement);
1738
+ });
1739
+ }
1740
+ /**
1741
+ * Updates the visual selection (CSS 'active') state for the mask list in the DOM.
1742
+ *
1743
+ * @param {Object|null} selectedMask - The currently selected mask, or null if none selected.
1744
+ * @private
1745
+ */
1746
+ _updateMaskListSelection(selectedMask) {
1747
+ const maskListElement = document.getElementById(this.elements.maskList);
1748
+ if (!maskListElement)
1749
+ return;
1750
+ const maskItems = maskListElement.querySelectorAll(".mask-item");
1751
+ maskItems.forEach((item) => {
1752
+ const isSelected = !!selectedMask && item.textContent === selectedMask.maskName;
1753
+ item.classList.toggle("active", isSelected);
1754
+ });
1755
+ }
1756
+ /**
1757
+ * Merges current masks into the image: exports a masked/cropped image, removes all masks, and re-imports the merged image.
1758
+ * Will not run if no original image or no masks exist.
1759
+ * @async
1760
+ * @returns {Promise<void>} Resolves when merge and load are complete.
1761
+ */
1762
+ async mergeMasks() {
1763
+ if (!this.originalImage)
1764
+ return;
1765
+ const masks = this.canvas.getObjects().filter((object) => object.maskId);
1766
+ if (!masks.length)
1767
+ return;
1768
+ this.canvas.discardActiveObject();
1769
+ this.canvas.renderAll();
1770
+ try {
1771
+ const beforeJson = this._serializeCanvasState();
1772
+ const merged = await this.exportImageBase64({ exportImageArea: true, multiplier: this.options.exportMultiplier });
1773
+ this.removeAllMasks({ saveHistory: false });
1774
+ await this.loadImage(merged);
1775
+ const afterJson = this._serializeCanvasState();
1776
+ this._pushStateTransition(beforeJson, afterJson);
1777
+ } catch (err) {
1778
+ this._reportError("merge error", err);
1779
+ }
1780
+ }
1781
+ /**
1782
+ * @deprecated Use mergeMasks() instead.
1783
+ */
1784
+ async merge() {
1785
+ return this.mergeMasks();
1786
+ }
1787
+ /**
1788
+ * Triggers a JPEG image download of the current canvas (image plus masks if configured).
1789
+ * The image area and multiplier are controlled by options.
1790
+ * @param {string} [fileName=this.options.defaultDownloadFileName] - Desired download file name.
1791
+ */
1792
+ downloadImage(fileName = this.options.defaultDownloadFileName) {
1793
+ if (!this.originalImage)
1794
+ return;
1795
+ const exportImageArea = this.options.exportImageAreaByDefault;
1796
+ this.exportImageBase64({ exportImageArea, multiplier: this.options.exportMultiplier }).then((base64) => {
1797
+ const link = document.createElement("a");
1798
+ link.download = fileName;
1799
+ link.href = base64;
1800
+ document.body.appendChild(link);
1801
+ link.click();
1802
+ document.body.removeChild(link);
1803
+ }).catch((err) => this._reportError("download error", err));
1804
+ }
1805
+ /**
1806
+ * Exports the image as a Base64-encoded image data URL.
1807
+ * Can export either the original, or the current view including masks (clipped/cropped).
1808
+ * Will restore masks' state after temporary modifications for export.
1809
+ * @async
1810
+ * @param {Object} [options={}] - Export options.
1811
+ * @param {boolean} [options.exportImageArea] - If true, exports only the image bounding area with masks cropped and blended.
1812
+ * @param {number} [options.multiplier=1] - Scaling multiplier for output (resolution).
1813
+ * @param {number} [options.quality=0.92] - Image quality between 0 and 1 for lossy formats.
1814
+ * @param {string} [options.fileType='jpeg'] - Output file type ('jpeg' | 'png' | 'webp').
1815
+ * @returns {Promise<string>} Promise resolving to an image data URL.
1816
+ * @throws {Error} If there is no image loaded.
1817
+ */
1818
+ async exportImageBase64(options = {}) {
1819
+ if (!this.originalImage)
1820
+ throw new Error("No image loaded");
1821
+ const exportImageArea = typeof options.exportImageArea === "boolean" ? options.exportImageArea : this.options.exportImageAreaByDefault;
1822
+ const multiplier = options.multiplier || this.options.exportMultiplier || 1;
1823
+ const quality = this._normalizeQuality(options.quality ?? this.options.downsampleQuality);
1824
+ const format = this._normalizeImageFormat(options.fileType || options.format);
1825
+ if (!exportImageArea) {
1826
+ const masks2 = this.canvas.getObjects().filter((object) => object.maskId || object.maskLabel);
1827
+ const maskVisibilityBackups = masks2.map((mask) => ({ object: mask, visible: mask.visible }));
1828
+ try {
1829
+ masks2.forEach((mask) => {
1830
+ mask.set({ visible: false });
1831
+ });
1832
+ this.canvas.discardActiveObject();
1833
+ this.canvas.renderAll();
1834
+ this.originalImage.setCoords();
1835
+ const imageBounds = this.originalImage.getBoundingRect(true, true);
1836
+ const { sx, sy, sw, sh } = this._getClampedCanvasRegion(imageBounds, { includePartialPixels: false });
1837
+ return await this._exportCanvasRegionToDataURL({
1838
+ sx,
1839
+ sy,
1840
+ sw,
1841
+ sh,
1842
+ multiplier,
1843
+ quality,
1844
+ format
1845
+ });
1846
+ } finally {
1847
+ maskVisibilityBackups.forEach((backup) => {
1848
+ try {
1849
+ backup.object.set({ visible: backup.visible });
1850
+ } catch (error) {
1851
+ }
1852
+ });
1853
+ this.canvas.renderAll();
1854
+ }
1855
+ }
1856
+ const masks = this.canvas.getObjects().filter((object) => object.maskId);
1857
+ const maskStyleBackups = masks.map((mask) => ({
1858
+ object: mask,
1859
+ opacity: mask.opacity,
1860
+ fill: mask.fill,
1861
+ strokeWidth: mask.strokeWidth,
1862
+ stroke: mask.stroke,
1863
+ selectable: mask.selectable,
1864
+ lockRotation: mask.lockRotation
1865
+ }));
1866
+ let finalBase64;
1867
+ try {
1868
+ masks.forEach((mask) => this._removeLabelForMask(mask));
1869
+ this.canvas.discardActiveObject();
1870
+ this.canvas.renderAll();
1871
+ masks.forEach((mask) => {
1872
+ mask.set({ opacity: 1, fill: "#000000", strokeWidth: 0, stroke: null, selectable: false });
1873
+ mask.setCoords();
1874
+ });
1875
+ this.canvas.renderAll();
1876
+ this.originalImage.setCoords();
1877
+ const imageBounds = this.originalImage.getBoundingRect(true, true);
1878
+ const { sx, sy, sw, sh } = this._getClampedCanvasRegion(imageBounds, { includePartialPixels: false });
1879
+ finalBase64 = await this._exportCanvasRegionToDataURL({
1880
+ sx,
1881
+ sy,
1882
+ sw,
1883
+ sh,
1884
+ multiplier,
1885
+ quality,
1886
+ format
1887
+ });
1888
+ } finally {
1889
+ maskStyleBackups.forEach((backup) => {
1890
+ try {
1891
+ backup.object.set({
1892
+ opacity: backup.opacity,
1893
+ fill: backup.fill,
1894
+ strokeWidth: backup.strokeWidth,
1895
+ stroke: backup.stroke,
1896
+ selectable: backup.selectable,
1897
+ lockRotation: backup.lockRotation
1898
+ });
1899
+ backup.object.setCoords();
1900
+ } catch (error) {
1901
+ }
1902
+ });
1903
+ this.canvas.renderAll();
1904
+ }
1905
+ return finalBase64;
1906
+ }
1907
+ /**
1908
+ * @deprecated Use exportImageBase64() instead.
1909
+ */
1910
+ async getImageBase64(options = {}) {
1911
+ return this.exportImageBase64(options);
1912
+ }
1913
+ /**
1914
+ * Exports the current canvas (with or without masks) as a File object.
1915
+ * Allows you to choose whether to merge masks and specify file type (jpeg/png/webp).
1916
+ *
1917
+ * @async
1918
+ * @param {Object} [options={}] - Export options.
1919
+ * @param {boolean} [options.mergeMask=true] - If true, export image area with masks merged; if false, export the plain image without masks.
1920
+ * @param {string} [options.fileType='jpeg'] - Output file type ('jpeg' | 'png' | 'webp'). Defaults to 'jpeg' on invalid input.
1921
+ * @param {number} [options.quality=0.92] - Image quality for lossy types (0-1, default based on options.downsampleQuality).
1922
+ * @param {number} [options.multiplier=1] - Output resolution multiplier.
1923
+ * @param {string} [options.fileName] - Optional file name (only used for download).
1924
+ * @returns {Promise<File>} Resolves with the exported image as a File object.
1925
+ *
1926
+ * @example
1927
+ * const file = await this.exportImageFile({ mergeMask: false, fileType: 'png' });
1928
+ */
1929
+ async exportImageFile(options = {}) {
1930
+ if (!this.originalImage)
1931
+ throw new Error("No image loaded");
1932
+ const {
1933
+ mergeMask = true,
1934
+ fileType = "jpeg",
1935
+ quality = this.options.downsampleQuality ?? 0.92,
1936
+ multiplier = this.options.exportMultiplier ?? 1,
1937
+ fileName = this.options.defaultDownloadFileName ?? "exported_image.jpg"
1938
+ } = options;
1939
+ const safeFileType = this._normalizeImageFormat(fileType);
1940
+ let base64;
1941
+ if (mergeMask) {
1942
+ base64 = await this.exportImageBase64({
1943
+ exportImageArea: true,
1944
+ multiplier,
1945
+ quality,
1946
+ fileType: safeFileType
1947
+ });
1948
+ } else {
1949
+ base64 = await this.exportImageBase64({
1950
+ exportImageArea: false,
1951
+ multiplier,
1952
+ quality,
1953
+ fileType: safeFileType
1954
+ });
1955
+ }
1956
+ let imageDataUrl = base64;
1957
+ if (!imageDataUrl.startsWith(`data:image/${safeFileType}`)) {
1958
+ imageDataUrl = await new Promise((resolve, reject) => {
1959
+ const imageElement = new window.Image();
1960
+ imageElement.crossOrigin = "Anonymous";
1961
+ imageElement.onload = () => {
1962
+ try {
1963
+ const offscreenCanvas = document.createElement("canvas");
1964
+ offscreenCanvas.width = imageElement.width;
1965
+ offscreenCanvas.height = imageElement.height;
1966
+ const context = offscreenCanvas.getContext("2d");
1967
+ context.drawImage(imageElement, 0, 0);
1968
+ const convertedDataUrl = offscreenCanvas.toDataURL(`image/${safeFileType}`, quality);
1969
+ resolve(convertedDataUrl);
1970
+ } catch (error) {
1971
+ reject(error);
1972
+ }
1973
+ };
1974
+ imageElement.onerror = reject;
1975
+ imageElement.src = base64;
1976
+ });
1977
+ }
1978
+ const binaryString = atob(imageDataUrl.split(",")[1]);
1979
+ const mime = `image/${safeFileType}`;
1980
+ let byteIndex = binaryString.length;
1981
+ const bytes = new Uint8Array(byteIndex);
1982
+ while (byteIndex--) {
1983
+ bytes[byteIndex] = binaryString.charCodeAt(byteIndex);
1984
+ }
1985
+ return new File([bytes], fileName, { type: mime });
1986
+ }
1987
+ _clearMaskPlacementMemory() {
1988
+ this._lastMask = null;
1989
+ this._lastMaskInitialLeft = null;
1990
+ this._lastMaskInitialTop = null;
1991
+ this._lastMaskInitialWidth = null;
1992
+ }
1993
+ async _restoreStateAfterCropFailure(beforeJson, message, error) {
1994
+ this._reportError(message, error);
1995
+ if (this._cropRect && this.canvas)
1996
+ this._removeCropRect();
1997
+ this._cropRect = null;
1998
+ this._cropMode = false;
1999
+ if (this.canvas && this._prevSelectionSetting !== void 0) {
2000
+ this.canvas.selection = !!this._prevSelectionSetting;
2001
+ }
2002
+ this._prevSelectionSetting = void 0;
2003
+ if (beforeJson) {
2004
+ try {
2005
+ await this.loadFromState(beforeJson);
2006
+ } catch (restoreError) {
2007
+ this._reportError("applyCrop: rollback failed", restoreError);
2008
+ }
2009
+ }
2010
+ this._updateUI();
2011
+ if (this.canvas)
2012
+ this.canvas.renderAll();
2013
+ }
2014
+ _restoreCropObjectState() {
2015
+ if (Array.isArray(this._cropPrevEvented)) {
2016
+ this._cropPrevEvented.forEach((state) => {
2017
+ try {
2018
+ state.object.set({
2019
+ evented: state.evented,
2020
+ selectable: state.selectable,
2021
+ visible: state.visible
2022
+ });
2023
+ } catch (error) {
2024
+ }
2025
+ });
2026
+ }
2027
+ this._cropPrevEvented = null;
2028
+ }
2029
+ _removeCropRect() {
2030
+ if (!this._cropRect)
2031
+ return;
2032
+ try {
2033
+ if (this._cropHandlers && this._cropHandlers.length) {
2034
+ this._cropHandlers.forEach((targetHandlers) => {
2035
+ targetHandlers.handlers.forEach((handlerRecord) => {
2036
+ targetHandlers.target.off(handlerRecord.eventName, handlerRecord.handler);
2037
+ });
2038
+ });
2039
+ }
2040
+ } catch (error) {
2041
+ }
2042
+ try {
2043
+ this.canvas.remove(this._cropRect);
2044
+ } catch (error) {
2045
+ }
2046
+ this._cropRect = null;
2047
+ this._cropHandlers = [];
2048
+ }
2049
+ /**
2050
+ * Enter crop mode: create a resizable/movable selection rect on top of the image.
2051
+ * @public
2052
+ */
2053
+ enterCropMode() {
2054
+ if (!this.canvas || !this.originalImage || this._cropMode)
2055
+ return;
2056
+ if (!this.isImageLoaded())
2057
+ return;
2058
+ this._cropMode = true;
2059
+ this._prevSelectionSetting = this.canvas.selection;
2060
+ this.canvas.selection = false;
2061
+ this.canvas.discardActiveObject();
2062
+ this.originalImage.setCoords();
2063
+ const imageBounds = this.originalImage.getBoundingRect(true, true);
2064
+ const padding = this.options.crop && this.options.crop.padding ? this.options.crop.padding : 10;
2065
+ const left = Math.max(0, Math.floor(imageBounds.left + padding));
2066
+ const top = Math.max(0, Math.floor(imageBounds.top + padding));
2067
+ const width = Math.min(this.options.crop.minWidth || 50, Math.floor(imageBounds.width - padding * 2));
2068
+ const height = Math.min(this.options.crop.minHeight || 50, Math.floor(imageBounds.height - padding * 2));
2069
+ const cropRect = new fabric.Rect({
2070
+ left,
2071
+ top,
2072
+ width,
2073
+ height,
2074
+ fill: "rgba(0,0,0,0.12)",
2075
+ stroke: "#00aaff",
2076
+ strokeDashArray: [6, 4],
2077
+ strokeWidth: 1,
2078
+ strokeUniform: true,
2079
+ selectable: true,
2080
+ hasRotatingPoint: !!(this.options.crop && this.options.crop.allowRotationOfCropRect),
2081
+ lockRotation: !(this.options.crop && this.options.crop.allowRotationOfCropRect),
2082
+ cornerSize: 8,
2083
+ objectCaching: false,
2084
+ originX: "left",
2085
+ originY: "top"
2086
+ });
2087
+ this.canvas.add(cropRect);
2088
+ cropRect.isCropRect = true;
2089
+ this.canvas.bringToFront(cropRect);
2090
+ this.canvas.setActiveObject(cropRect);
2091
+ this._cropRect = cropRect;
2092
+ this._cropPrevEvented = [];
2093
+ const shouldHideMasks = !!(this.options.crop && this.options.crop.hideMasksDuringCrop);
2094
+ this.canvas.getObjects().forEach((object) => {
2095
+ if (object !== cropRect) {
2096
+ this._cropPrevEvented.push({ object, evented: object.evented, selectable: object.selectable, visible: object.visible });
2097
+ try {
2098
+ const updates = {
2099
+ evented: false,
2100
+ selectable: false
2101
+ };
2102
+ if (shouldHideMasks && (object.maskId || object.maskLabel))
2103
+ updates.visible = false;
2104
+ object.set(updates);
2105
+ } catch (error) {
2106
+ }
2107
+ }
2108
+ });
2109
+ const handleCropRectModified = () => {
2110
+ try {
2111
+ cropRect.setCoords();
2112
+ this.canvas.requestRenderAll();
2113
+ } catch (error) {
2114
+ }
2115
+ };
2116
+ cropRect.on("modified", handleCropRectModified);
2117
+ cropRect.on("moving", handleCropRectModified);
2118
+ cropRect.on("scaling", handleCropRectModified);
2119
+ this._cropHandlers.push({
2120
+ target: cropRect,
2121
+ handlers: [
2122
+ { eventName: "modified", handler: handleCropRectModified },
2123
+ { eventName: "moving", handler: handleCropRectModified },
2124
+ { eventName: "scaling", handler: handleCropRectModified }
2125
+ ]
2126
+ });
2127
+ this._updateUI();
2128
+ this.canvas.renderAll();
2129
+ }
2130
+ /**
2131
+ * Cancel crop mode and remove the temporary selection rect.
2132
+ * @public
2133
+ */
2134
+ cancelCrop() {
2135
+ if (!this.canvas || !this._cropMode)
2136
+ return;
2137
+ this._removeCropRect();
2138
+ this._restoreCropObjectState();
2139
+ this._cropMode = false;
2140
+ this.canvas.selection = !!this._prevSelectionSetting;
2141
+ this._prevSelectionSetting = void 0;
2142
+ this.canvas.discardActiveObject();
2143
+ this._updateUI();
2144
+ this.canvas.renderAll();
2145
+ }
2146
+ /**
2147
+ * Apply the current crop rectangle.
2148
+ * remove all masks and export canvas snapshot and crop via offscreen canvas
2149
+ * @public
2150
+ */
2151
+ async applyCrop() {
2152
+ if (!this.canvas || !this._cropMode || !this._cropRect)
2153
+ return;
2154
+ this._cropRect.setCoords();
2155
+ const rectBounds = this._cropRect.getBoundingRect(true, true);
2156
+ const { sx, sy, sw, sh } = this._getClampedCanvasRegion(rectBounds);
2157
+ const shouldPreserveMasks = !!(this.options.crop && this.options.crop.preserveMasksAfterCrop);
2158
+ this._restoreCropObjectState();
2159
+ let beforeJson = null;
2160
+ try {
2161
+ beforeJson = this._serializeCanvasState();
2162
+ } catch (error) {
2163
+ this._reportWarning("applyCrop: could not serialize before state", error);
2164
+ beforeJson = null;
2165
+ }
2166
+ const preservedMasks = [];
2167
+ try {
2168
+ const masks = this.canvas.getObjects().filter((object) => object.maskId);
2169
+ if (masks && masks.length) {
2170
+ masks.forEach((mask) => {
2171
+ try {
2172
+ mask.setCoords();
2173
+ const maskBounds = mask.getBoundingRect(true, true);
2174
+ const intersectsCrop = maskBounds.left < sx + sw && maskBounds.left + maskBounds.width > sx && maskBounds.top < sy + sh && maskBounds.top + maskBounds.height > sy;
2175
+ this._removeLabelForMask(mask);
2176
+ this.canvas.remove(mask);
2177
+ if (shouldPreserveMasks && intersectsCrop) {
2178
+ mask.set({
2179
+ left: (mask.left || 0) - sx,
2180
+ top: (mask.top || 0) - sy,
2181
+ visible: true
2182
+ });
2183
+ mask.setCoords();
2184
+ preservedMasks.push(mask);
2185
+ }
2186
+ } catch (error) {
2187
+ this._reportWarning("applyCrop: failed to remove mask", error);
2188
+ }
2189
+ });
2190
+ this._clearMaskPlacementMemory();
2191
+ this.canvas.discardActiveObject();
2192
+ this.canvas.renderAll();
2193
+ }
2194
+ } catch (error) {
2195
+ this._reportWarning("applyCrop: error while removing masks", error);
2196
+ }
2197
+ this._removeCropRect();
2198
+ this._cropMode = false;
2199
+ this.canvas.selection = !!this._prevSelectionSetting;
2200
+ this._prevSelectionSetting = void 0;
2201
+ let croppedBase64;
2202
+ try {
2203
+ croppedBase64 = await this._exportCanvasRegionToDataURL({
2204
+ sx,
2205
+ sy,
2206
+ sw,
2207
+ sh,
2208
+ multiplier: 1,
2209
+ quality: this._normalizeQuality(this.options.downsampleQuality),
2210
+ format: "jpeg"
2211
+ });
2212
+ } catch (error) {
2213
+ await this._restoreStateAfterCropFailure(beforeJson, "applyCrop: failed to create cropped image", error);
2214
+ return;
2215
+ }
2216
+ try {
2217
+ await this.loadImage(croppedBase64);
2218
+ if (preservedMasks.length) {
2219
+ preservedMasks.forEach((mask) => {
2220
+ this._rebindMaskEvents(mask);
2221
+ this.canvas.add(mask);
2222
+ this.canvas.bringToFront(mask);
2223
+ });
2224
+ this._lastMask = preservedMasks[preservedMasks.length - 1];
2225
+ this.maskCounter = preservedMasks.reduce((max, mask) => Math.max(max, mask.maskId || 0), this.maskCounter);
2226
+ this._updateMaskList();
2227
+ this.canvas.renderAll();
2228
+ }
2229
+ } catch (e) {
2230
+ await this._restoreStateAfterCropFailure(beforeJson, "applyCrop: loadImage(croppedBase64) failed", e);
2231
+ return;
2232
+ }
2233
+ let afterJson = null;
2234
+ try {
2235
+ afterJson = this._serializeCanvasState();
2236
+ } catch (e) {
2237
+ this._reportWarning("applyCrop: failed to serialize after state", e);
2238
+ afterJson = null;
2239
+ }
2240
+ try {
2241
+ this._pushStateTransition(beforeJson, afterJson);
2242
+ } catch (e) {
2243
+ this._reportWarning("applyCrop: failed to push history command", e);
2244
+ }
2245
+ this._updateUI();
2246
+ this.canvas.renderAll();
2247
+ }
2248
+ /* ---------- Misc / UI ---------- */
2249
+ /**
2250
+ * Updates the scale input field in the UI to reflect the current scale.
2251
+ * Sets the value (as percentage) if the element is present.
2252
+ * @private
2253
+ */
2254
+ _updateInputs() {
2255
+ const scaleInputElement = document.getElementById(this.elements.scaleRate);
2256
+ if (scaleInputElement)
2257
+ scaleInputElement.value = Math.round(this.currentScale * 100);
2258
+ }
2259
+ /**
2260
+ * Updates the enabled/disabled state of various UI controls (buttons)
2261
+ * based on the current application state (image/mask presence, animation, etc).
2262
+ * @private
2263
+ */
2264
+ _updateUI() {
2265
+ const hasImage = !!this.originalImage;
2266
+ const masks = hasImage ? this.canvas.getObjects().filter((object) => object.maskId) : [];
2267
+ const hasMasks = masks.length > 0;
2268
+ const activeObject = this.canvas.getActiveObject();
2269
+ const hasSelectedMask = activeObject && activeObject.maskId;
2270
+ const isDefaultTransform = this.currentScale === 1 && this.currentRotation === 0;
2271
+ const canUndo = this.historyManager?.canUndo();
2272
+ const canRedo = this.historyManager?.canRedo();
2273
+ const isInCropMode = !!this._cropMode;
2274
+ if (isInCropMode) {
2275
+ for (const key of Object.keys(this.elements || {})) {
2276
+ const element = document.getElementById(this.elements[key]);
2277
+ if (!element)
2278
+ continue;
2279
+ if (key === "applyCropBtn" || key === "cancelCropBtn") {
2280
+ this._setDisabled(key, false);
2281
+ } else {
2282
+ this._setDisabled(key, true);
2283
+ }
2284
+ }
2285
+ return;
2286
+ }
2287
+ this._setDisabled("zoomInBtn", !hasImage || this.isAnimating || this.currentScale >= this.options.maxScale);
2288
+ this._setDisabled("zoomOutBtn", !hasImage || this.isAnimating || this.currentScale <= this.options.minScale);
2289
+ this._setDisabled("rotateLeftBtn", !hasImage || this.isAnimating);
2290
+ this._setDisabled("rotateRightBtn", !hasImage || this.isAnimating);
2291
+ this._setDisabled("addMaskBtn", !hasImage || this.isAnimating);
2292
+ this._setDisabled("removeMaskBtn", !hasSelectedMask || this.isAnimating);
2293
+ this._setDisabled("removeAllMasksBtn", !hasMasks || this.isAnimating);
2294
+ this._setDisabled("mergeBtn", !hasImage || !hasMasks || this.isAnimating);
2295
+ this._setDisabled("downloadBtn", !hasImage || this.isAnimating);
2296
+ this._setDisabled("resetBtn", !hasImage || isDefaultTransform || this.isAnimating);
2297
+ this._setDisabled("undoBtn", !hasImage || this.isAnimating || !canUndo);
2298
+ this._setDisabled("redoBtn", !hasImage || this.isAnimating || !canRedo);
2299
+ this._setDisabled("cropBtn", !hasImage || this.isAnimating);
2300
+ this._setDisabled("applyCropBtn", true);
2301
+ this._setDisabled("cancelCropBtn", true);
2302
+ this._setDisabled("imageInput", this.isAnimating);
2303
+ this._setDisabled("uploadArea", this.isAnimating);
2304
+ }
2305
+ /**
2306
+ * Enables or disables a specific UI element (typically a button) by its key.
2307
+ *
2308
+ * @param {string} key - Key of the element in this.elements (e.g. 'zoomInBtn').
2309
+ * @param {boolean} disabled - If true, disables the element; otherwise enables.
2310
+ * @private
2311
+ */
2312
+ _setDisabled(key, disabled) {
2313
+ const element = document.getElementById(this.elements[key]);
2314
+ if (!element)
2315
+ return;
2316
+ if ("disabled" in element) {
2317
+ element.disabled = !!disabled;
2318
+ return;
2319
+ }
2320
+ if (disabled) {
2321
+ element.setAttribute("aria-disabled", "true");
2322
+ element.style.pointerEvents = "none";
2323
+ } else {
2324
+ element.removeAttribute("aria-disabled");
2325
+ element.style.pointerEvents = "";
2326
+ }
2327
+ }
2328
+ _isElementDisabled(element) {
2329
+ if (!element)
2330
+ return false;
2331
+ if ("disabled" in element)
2332
+ return !!element.disabled;
2333
+ return element.getAttribute("aria-disabled") === "true";
2334
+ }
2335
+ /**
2336
+ * Automatically display and hide placeholders and containers based on the current image content
2337
+ * @private
2338
+ */
2339
+ _updatePlaceholderStatus() {
2340
+ if (!this.options.showPlaceholder)
2341
+ return;
2342
+ this._setPlaceholderVisible(!this.originalImage);
2343
+ }
2344
+ /**
2345
+ * Controls the display/hiding of the Placeholder and Canvas container.
2346
+ * @param {boolean} show - true displays the placeholder, false displays the canvas container
2347
+ * @private
2348
+ */
2349
+ _setPlaceholderVisible(show) {
2350
+ if (!this.placeholderElement)
2351
+ return;
2352
+ if (show) {
2353
+ this.placeholderElement.classList.remove("d-none");
2354
+ this.placeholderElement.classList.add("d-flex");
2355
+ this.containerElement.classList.add("d-none");
2356
+ } else {
2357
+ this.placeholderElement.classList.remove("d-flex");
2358
+ this.placeholderElement.classList.add("d-none");
2359
+ this.containerElement.classList.remove("d-none");
2360
+ }
2361
+ }
2362
+ /**
2363
+ * Cleans up and disposes of the canvas and related references.
2364
+ * Call this method to free memory and remove canvas listeners when the editor is no longer needed.
2365
+ * @public
2366
+ */
2367
+ dispose() {
2368
+ try {
2369
+ for (const key in this._handlersByElementKey || {}) {
2370
+ const handlers = this._handlersByElementKey[key] || [];
2371
+ const element = document.getElementById(this.elements[key]);
2372
+ if (!element)
2373
+ continue;
2374
+ handlers.forEach((handlerRecord) => {
2375
+ try {
2376
+ element.removeEventListener(handlerRecord.eventName, handlerRecord.handler);
2377
+ } catch (error) {
2378
+ }
2379
+ });
2380
+ }
2381
+ } catch (error) {
2382
+ }
2383
+ if (this._cropRect) {
2384
+ try {
2385
+ this.canvas.remove(this._cropRect);
2386
+ } catch (e) {
2387
+ }
2388
+ this._cropRect = null;
2389
+ }
2390
+ if (this.containerElement && this._containerOriginalOverflow !== void 0) {
2391
+ try {
2392
+ this.containerElement.style.overflow = this._containerOriginalOverflow;
2393
+ } catch (e) {
2394
+ }
2395
+ }
2396
+ if (this.canvas) {
2397
+ try {
2398
+ this.canvas.dispose();
2399
+ } catch (e) {
2400
+ }
2401
+ this.canvas = null;
2402
+ this.canvasElement = null;
2403
+ this.isImageLoadedToCanvas = false;
2404
+ }
2405
+ this._handlersByElementKey = {};
2406
+ }
2407
+ };
2408
+ var AnimationQueue = class {
2409
+ /**
2410
+ * Creates a new AnimationQueue.
2411
+ *
2412
+ * @constructor
2413
+ */
2414
+ constructor() {
2415
+ this.queue = [];
2416
+ this.running = false;
2417
+ }
2418
+ /**
2419
+ * Adds an animation function to the queue.
2420
+ *
2421
+ * @param {Function} animationFn A function that returns a Promise or any await-able.
2422
+ * @returns {Promise<*>} A Promise that resolves/rejects with the animation result.
2423
+ */
2424
+ async add(animationFn) {
2425
+ return new Promise((resolve, reject) => {
2426
+ this.queue.push({ fn: animationFn, resolve, reject });
2427
+ if (!this.running) {
2428
+ this.processQueue();
2429
+ }
2430
+ });
2431
+ }
2432
+ /**
2433
+ * Internal helper that processes the animation queue sequentially until it is empty.
2434
+ *
2435
+ * @private
2436
+ * @returns {Promise<void>}
2437
+ */
2438
+ async processQueue() {
2439
+ if (this.queue.length === 0) {
2440
+ this.running = false;
2441
+ return;
2442
+ }
2443
+ this.running = true;
2444
+ const { fn, resolve, reject } = this.queue.shift();
2445
+ try {
2446
+ const result = await fn();
2447
+ resolve(result);
2448
+ } catch (error) {
2449
+ reject(error);
2450
+ }
2451
+ this.processQueue();
2452
+ }
2453
+ };
2454
+ var Command = class {
2455
+ /**
2456
+ * @param {Function} execute The function that performs the action.
2457
+ * @param {Function} undo The function that reverts the action.
2458
+ */
2459
+ constructor(execute, undo) {
2460
+ this.execute = execute;
2461
+ this.undo = undo;
2462
+ }
2463
+ };
2464
+ var HistoryManager = class {
2465
+ /**
2466
+ * @param {number} [maxSize=50] Maximum number of commands to keep in history.
2467
+ */
2468
+ constructor(maxSize = 50) {
2469
+ this.history = [];
2470
+ this.currentIndex = -1;
2471
+ this.maxSize = maxSize;
2472
+ this.pending = Promise.resolve();
2473
+ }
2474
+ enqueue(task) {
2475
+ const run = this.pending.then(task, task);
2476
+ this.pending = run.catch(() => {
2477
+ });
2478
+ return run;
2479
+ }
2480
+ /**
2481
+ * Executes a new command and pushes it onto the history stack.
2482
+ * Truncates any "future" history when branching.
2483
+ *
2484
+ * @param {Command} command The command to execute.
2485
+ * @returns {void}
2486
+ */
2487
+ execute(command) {
2488
+ command.execute();
2489
+ this.push(command);
2490
+ }
2491
+ /**
2492
+ * Pushes an already-applied command onto the history stack.
2493
+ * Truncates any "future" history when branching.
2494
+ *
2495
+ * @param {Command} command The command to push.
2496
+ * @returns {void}
2497
+ */
2498
+ push(command) {
2499
+ if (this.currentIndex < this.history.length - 1) {
2500
+ this.history = this.history.slice(0, this.currentIndex + 1);
2501
+ }
2502
+ this.history.push(command);
2503
+ if (this.history.length > this.maxSize) {
2504
+ this.history.shift();
2505
+ } else {
2506
+ this.currentIndex++;
2507
+ }
2508
+ }
2509
+ /**
2510
+ * Checks whether an undo operation is possible.
2511
+ *
2512
+ * @returns {boolean} True if undo can be performed.
2513
+ */
2514
+ canUndo() {
2515
+ return this.currentIndex >= 0;
2516
+ }
2517
+ /**
2518
+ * Checks whether a redo operation is possible.
2519
+ *
2520
+ * @returns {boolean} True if redo can be performed.
2521
+ */
2522
+ canRedo() {
2523
+ return this.currentIndex < this.history.length - 1;
2524
+ }
2525
+ /**
2526
+ * Undoes the last executed command if possible.
2527
+ *
2528
+ * @returns {void}
2529
+ */
2530
+ undo() {
2531
+ return this.enqueue(async () => {
2532
+ if (this.currentIndex >= 0) {
2533
+ const index = this.currentIndex;
2534
+ await this.history[index].undo();
2535
+ this.currentIndex = index - 1;
2536
+ }
2537
+ });
2538
+ }
2539
+ /**
2540
+ * Redoes the next command in history if possible.
2541
+ *
2542
+ * @returns {void}
2543
+ */
2544
+ redo() {
2545
+ return this.enqueue(async () => {
2546
+ if (this.currentIndex < this.history.length - 1) {
2547
+ const index = this.currentIndex + 1;
2548
+ await this.history[index].execute();
2549
+ this.currentIndex = index;
2550
+ }
2551
+ });
2552
+ }
2553
+ };
2554
+ var image_editor_default = ImageEditor;
2555
+
2556
+ // src/browser.js
2557
+ var scope = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : null;
2558
+ setFabric(scope && scope.fabric);
2559
+ if (scope) {
2560
+ scope.ImageEditor = image_editor_default;
2561
+ }
2562
+ })();
2563
+ //# sourceMappingURL=image-editor.js.map