@bensitu/image-editor 1.0.1 → 1.1.0

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,2101 @@
1
+ /**
2
+ * @file image-editor.js
3
+ * @module image-editor
4
+ * @version 1.1.1
5
+ * @author Ben Situ
6
+ * @license MIT
7
+ * @description Lightweight canvas-based image editor with masking/transform/export support.
8
+ *
9
+ * This source file is free software, available under the MIT license.
10
+ * It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
11
+ * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
+ * See the license files for details.
13
+ */
14
+
15
+ (function (root, factory) {
16
+ if (typeof define === 'function' && define.amd) {
17
+ // AMD / RequireJS
18
+ define([], factory)
19
+ } else if (typeof module === 'object' && module.exports) {
20
+ // CommonJS / Node / webpack (target=commonjs)
21
+ module.exports = factory()
22
+ } else {
23
+ // Browser normal <script> method, hanging to the global
24
+ root.ImageEditor = factory()
25
+ }
26
+ })(typeof self !== 'undefined' ? self : this, function () {
27
+ 'use strict'
28
+ /**
29
+ * ImageEditor
30
+ *
31
+ * A lightweight wrapper around fabric.js providing masking, scaling, rotation,
32
+ * merging/export helpers, and UI integrations for image editing.
33
+ *
34
+ * <b>Note:</b> Requires fabric.js (v5.x) to be loaded on the page before use.
35
+ *
36
+ * <pre>
37
+ * Example usage:
38
+ * const editor = new ImageEditor({ canvasWidth: 1024, canvasHeight: 768 });
39
+ * editor.init();
40
+ * </pre>
41
+ *
42
+ * @class ImageEditor
43
+ * @classdesc Fabric.js-based image editor with simple mask, transform, export and UI features.
44
+ *
45
+ * @param {Object} [options={}] - Customization options to override defaults.
46
+ * @param {number} [options.canvasWidth=800] - The initial canvas width in pixels.
47
+ * @param {number} [options.canvasHeight=600] - The initial canvas height in pixels.
48
+ * @param {string} [options.backgroundColor='#ffffff'] - The canvas background color.
49
+ * @param {number} [options.animationDuration=300] - Duration in ms for scale/rotate animations.
50
+ * @param {number} [options.minScale=0.1] - Minimum image scaling factor.
51
+ * @param {number} [options.maxScale=5.0] - Maximum image scaling factor.
52
+ * @param {number} [options.scaleStep=0.05] - Scale increment/decrement per step.
53
+ * @param {number} [options.rotationStep=90] - Rotation step in degrees.
54
+ * @param {boolean} [options.expandCanvasToImage=true] - If true, expands the canvas to fit image/mask.
55
+ * @param {boolean} [options.fitImageToCanvas=false] - If true, fits loaded image inside canvas.
56
+ * @param {boolean} [options.downsampleOnLoad=true] - Whether to downsample very large images on load.
57
+ * @param {number} [options.downsampleMaxWidth=4000] - Max width for downsampling.
58
+ * @param {number} [options.downsampleMaxHeight=3000] - Max height for downsampling.
59
+ * @param {number} [options.downsampleQuality=0.92] - JPEG quality for downsampling/export.
60
+ * @param {number} [options.exportMultiplier=1] - Scale output image by this multiplier on export.
61
+ * @param {boolean} [options.exportImageAreaByDefault=true] - Export only the image area (clipped to masks).
62
+ * @param {number} [options.defaultMaskWidth=50] - Default width of new mask rectangles.
63
+ * @param {number} [options.defaultMaskHeight=80] - Default height of new masks.
64
+ * @param {boolean} [options.maskRotatable=false] - If true, masks can be rotated.
65
+ * @param {boolean} [options.maskLabelOnSelect=true] - Show label on selected mask.
66
+ * @param {number} [options.maskLabelOffset=3] - Offset for mask labels from top-left corner.
67
+ * @param {string} [options.maskName='mask'] - Prefix for mask names/labels.
68
+ * @param {boolean} [options.showPlaceholder=true] - If true, shows placeholder when no image is loaded.
69
+ * @param {string|null} [options.initialImageBase64=null] - Base64 string to auto-load as initial image, if any.
70
+ * @param {string} [options.defaultDownloadFileName='edited_image.jpg'] - Default file name for downloads.
71
+ * @param {function} [options.onImageLoaded] - Optional callback to invoke after an image loads.
72
+ *
73
+ * @constructor
74
+ */
75
+ class ImageEditor {
76
+ constructor(options = {}) {
77
+ // Verify that fabric.js is present
78
+ this._fabricLoaded = typeof fabric !== 'undefined';
79
+ if (!this._fabricLoaded) {
80
+ console.error('fabric.js is not loaded. Please include fabric.js first. Initialization will be aborted.');
81
+ }
82
+ // Default options (can be overridden via ctor param)
83
+ this.options = {
84
+ canvasWidth: 800,
85
+ canvasHeight: 600,
86
+ backgroundColor: '#ffffff',
87
+
88
+ animationDuration: 300,
89
+ minScale: 0.1,
90
+ maxScale: 5.0,
91
+ scaleStep: 0.05,
92
+ rotationStep: 90,
93
+
94
+ expandCanvasToImage: true,
95
+ fitImageToCanvas: false,
96
+
97
+ downsampleOnLoad: true,
98
+ downsampleMaxWidth: 4000,
99
+ downsampleMaxHeight: 3000,
100
+ downsampleQuality: 0.92,
101
+
102
+ exportMultiplier: 1,
103
+ exportImageAreaByDefault: true,
104
+
105
+ defaultMaskWidth: 50,
106
+ defaultMaskHeight: 80,
107
+ maskRotatable: false,
108
+ maskLabelOnSelect: true,
109
+ maskLabelOffset: 3,
110
+ maskName: 'mask',
111
+
112
+ groupSelection: false,
113
+
114
+ showPlaceholder: true,
115
+ initialImageBase64: null, // Provide a base64 'data:image/...' string here if you want auto-load
116
+
117
+ defaultDownloadFileName: 'edited_image.jpg',
118
+
119
+ ...options
120
+ };
121
+ this.options.label = {
122
+ getText: (mask, maskIndex) => mask.maskName,
123
+ textOptions: {
124
+ fontSize: 12,
125
+ fill: '#fff',
126
+ backgroundColor: 'rgba(0,0,0,0.7)',
127
+ padding: 2,
128
+ fontFamily: "monospace",
129
+ fontWeight: "bold",
130
+ selectable: false,
131
+ evented: false,
132
+ originX: 'left',
133
+ originY: 'top',
134
+ }
135
+ };
136
+ this.options.crop = {
137
+ minWidth: 100,
138
+ minHeight: 100,
139
+ padding: 10,
140
+ hideMasksDuringCrop: true,
141
+ preserveMasksAfterCrop: true,
142
+ allowRotationOfCropRect: false
143
+ };
144
+
145
+ // Runtime state
146
+ this.canvas = null;
147
+ this.canvasEl = null;
148
+ this.containerEl = null;
149
+ this.placeholderEl = null;
150
+
151
+ this.originalImage = null; // fabric.Image
152
+ this.baseImageScale = 1;
153
+ this.currentScale = 1;
154
+ this.currentRotation = 0;
155
+ this.maskCounter = 0;
156
+ this.isAnimating = false;
157
+ this.elements = {};
158
+ this.isImageLoadedToCanvas = false;
159
+ this.maxHistorySize = 50;
160
+
161
+ this._boundHandlers = {};
162
+
163
+ this._lastMaskInitialLeft = null;
164
+ this._lastMaskInitialTop = null;
165
+ this._lastMaskInitialWidth = null;
166
+
167
+ this._cropMode = false;
168
+ this._cropRect = null;
169
+ this._cropHandlers = [];
170
+
171
+ this.onImageLoaded = typeof options.onImageLoaded === 'function' ? options.onImageLoaded : null;
172
+
173
+ this.animQueue = new AnimationQueue();
174
+ this.historyManager = new HistoryManager(this.maxHistorySize);
175
+ }
176
+
177
+ /**
178
+ * Initializes the editor, binds to DOM elements, sets up event handlers,
179
+ * and (optionally) loads an initial image.
180
+ * Use this method to set up the editor UI before interacting with it.
181
+ *
182
+ * @param {Object} [idMap={}] - Optional mapping from logical element names to actual DOM element IDs.
183
+ * Supported keys include: canvas, canvasContainer, imgPlaceholder, scaleRate, rotationLeftInput, rotationRightInput,
184
+ * rotateLeftBtn, rotateRightBtn, addMaskBtn, removeMaskBtn, removeAllMasksBtn, mergeBtn, downloadBtn, maskList,
185
+ * zoomInBtn, zoomOutBtn, resetBtn, imageInput. Unknown keys are ignored.
186
+ *
187
+ * @returns {void}
188
+ *
189
+ * @public
190
+ *
191
+ * @example
192
+ * editor.init({
193
+ * canvas: 'myFabricCanvasId',
194
+ * downloadBtn: 'myDownloadButtonId'
195
+ * });
196
+ */
197
+ init(idMap = {}) {
198
+ if (!this._fabricLoaded) return;
199
+
200
+ const defaults = {
201
+ canvas: 'fabricCanvas',
202
+ canvasContainer: null, // Pass an ID here if you have a scrollable viewport container
203
+ imgPlaceholder: 'imgPlaceholder',
204
+ scaleRate: 'scaleRate',
205
+ rotationLeftInput: 'rotationLeftInput',
206
+ rotationRightInput: 'rotationRightInput',
207
+ rotateLeftBtn: 'rotateLeftBtn',
208
+ rotateRightBtn: 'rotateRightBtn',
209
+ addMaskBtn: 'addMaskBtn',
210
+ removeMaskBtn: 'removeMaskBtn',
211
+ removeAllMasksBtn: 'removeAllMasksBtn',
212
+ mergeBtn: 'mergeBtn',
213
+ downloadBtn: 'downloadBtn',
214
+ maskList: 'maskList',
215
+ zoomInBtn: 'zoomInBtn',
216
+ zoomOutBtn: 'zoomOutBtn',
217
+ resetBtn: 'resetBtn',
218
+ undoBtn: 'undoBtn',
219
+ redoBtn: 'redoBtn',
220
+ imageInput: 'imageInput',
221
+ cropBtn: 'cropBtn',
222
+ applyCropBtn: 'applyCropBtn',
223
+ cancelCropBtn: 'cancelCropBtn'
224
+ };
225
+
226
+ this.elements = { ...defaults, ...idMap };
227
+
228
+ this._initCanvas();
229
+ this._bindEvents();
230
+ this._updateInputs();
231
+ this._updateMaskList();
232
+ this._updateUI();
233
+
234
+ // Auto-load initial image if provided
235
+ if (this.options.initialImageBase64) {
236
+ this.loadImage(this.options.initialImageBase64);
237
+ } else {
238
+ this._updatePlaceholderStatus();
239
+ }
240
+ }
241
+
242
+ /**
243
+ * Canvas setup helpers
244
+ * @private
245
+ */
246
+ _initCanvas() {
247
+ const canvasEl = document.getElementById(this.elements.canvas);
248
+ if (!canvasEl) throw new Error('Canvas is not found: ' + this.elements.canvas);
249
+ this.canvasEl = canvasEl;
250
+
251
+ // Decide which element acts as "viewport" (for width/height fallback)
252
+ if (this.elements.canvasContainer) {
253
+ const ce = document.getElementById(this.elements.canvasContainer);
254
+ this.containerEl = ce || canvasEl.parentElement;
255
+ } else {
256
+ this.containerEl = canvasEl.parentElement;
257
+ }
258
+
259
+ this.placeholderEl = document.getElementById(this.elements.imgPlaceholder) || null;
260
+
261
+ // Initial size — take container size if available
262
+ let initialW = this.options.canvasWidth;
263
+ let initialH = this.options.canvasHeight;
264
+ if (this.containerEl) {
265
+ const cw = Math.floor(this.containerEl.clientWidth);
266
+ const ch = Math.floor(this.containerEl.clientHeight);
267
+ if (cw > 0 && ch > 0) { initialW = cw; initialH = ch; }
268
+ }
269
+
270
+ this.canvas = new fabric.Canvas(canvasEl, {
271
+ width: initialW,
272
+ height: initialH,
273
+ backgroundColor: this.options.backgroundColor,
274
+ selection: this.options.groupSelection,
275
+ preserveObjectStacking: true
276
+ });
277
+
278
+ // Fabric event wiring
279
+ this.canvas.on('selection:created', (e) => this._onSelectionChanged(e.selected));
280
+ this.canvas.on('selection:updated', (e) => this._onSelectionChanged(e.selected));
281
+ this.canvas.on('selection:cleared', () => this._onSelectionChanged([]));
282
+ this.canvas.on('object:moving', (e) => { if (e.target && e.target.maskId) this._syncMaskLabel(e.target); });
283
+ this.canvas.on('object:scaling', (e) => { if (e.target && e.target.maskId) this._syncMaskLabel(e.target); });
284
+ this.canvas.on('object:rotating', (e) => { if (e.target && e.target.maskId) this._syncMaskLabel(e.target); });
285
+ this.canvas.on('object:modified', (e) => { if (e.target && e.target.maskId) this._syncMaskLabel(e.target); });
286
+
287
+ // Avoid inline-element whitespace artefacts
288
+ this.canvasEl.style.display = 'block';
289
+ }
290
+
291
+ /**
292
+ * DOM / UI bindings
293
+ * @private
294
+ */
295
+ _bindEvents() {
296
+ // Click anywhere on the upload area opens the native file dialog
297
+ this._bindIfExists('uploadArea', 'click', () => document.getElementById(this.elements.imageInput)?.click());
298
+ // File-input change
299
+ const inputEl = document.getElementById(this.elements.imageInput);
300
+ if (inputEl) {
301
+ inputEl.addEventListener('change', (e) => {
302
+ const f = e.target.files && e.target.files[0];
303
+ if (f) this._loadImageFile(f);
304
+ });
305
+ }
306
+ // Zoom & reset
307
+ this._bindIfExists('zoomInBtn', 'click', () => this.scaleImage(this.currentScale + this.options.scaleStep));
308
+ this._bindIfExists('zoomOutBtn', 'click', () => this.scaleImage(this.currentScale - this.options.scaleStep));
309
+ this._bindIfExists('resetBtn', 'click', () => { this.reset(); });
310
+ // Mask management
311
+ this._bindIfExists('addMaskBtn', 'click', () => this.addMask());
312
+ this._bindIfExists('removeMaskBtn', 'click', () => this.removeSelectedMask());
313
+ this._bindIfExists('removeAllMasksBtn', 'click', () => this.removeAllMasks());
314
+ // Merge + download
315
+ this._bindIfExists('mergeBtn', 'click', () => this.merge());
316
+ this._bindIfExists('downloadBtn', 'click', () => this.downloadImage());
317
+ // Undo + Redo
318
+ this._bindIfExists('undoBtn', 'click', () => this.undo());
319
+ this._bindIfExists('redoBtn', 'click', () => this.redo());
320
+
321
+ // Rotation buttons (step can be overridden by two input fields)
322
+ const rotLeftBtn = document.getElementById(this.elements.rotateLeftBtn);
323
+ const rotRightBtn = document.getElementById(this.elements.rotateRightBtn);
324
+ if (rotLeftBtn) rotLeftBtn.addEventListener('click', () => {
325
+ const el = document.getElementById(this.elements.rotationLeftInput);
326
+ let step = this.options.rotationStep;
327
+ if (el) { const p = parseFloat(el.value); if (!isNaN(p)) step = p; }
328
+ this.rotateImage(this.currentRotation - step);
329
+ });
330
+ if (rotRightBtn) rotRightBtn.addEventListener('click', () => {
331
+ const el = document.getElementById(this.elements.rotationRightInput);
332
+ let step = this.options.rotationStep;
333
+ if (el) { const p = parseFloat(el.value); if (!isNaN(p)) step = p; }
334
+ this.rotateImage(this.currentRotation + step);
335
+ });
336
+
337
+ // Crop bindings (optional: bound only if element IDs exist in elements)
338
+ this._bindIfExists('cropBtn', 'click', () => this.enterCropMode());
339
+ this._bindIfExists('applyCropBtn', 'click', () => { this.applyCrop().catch(e => console.error('applyCrop failed', e)); });
340
+ this._bindIfExists('cancelCropBtn', 'click', () => this.cancelCrop());
341
+ }
342
+
343
+ /**
344
+ * Event binding element check
345
+ *
346
+ * @param {*} event
347
+ * @param {*} handler
348
+ * @param {*} key
349
+ * @private
350
+ */
351
+ _bindIfExists(key, event, handler) {
352
+ const el = document.getElementById(this.elements[key]);
353
+ if (el) {
354
+ el.addEventListener(event, handler);
355
+ this._boundHandlers = this._boundHandlers || {};
356
+ if (!this._boundHandlers[key]) this._boundHandlers[key] = [];
357
+ this._boundHandlers[key].push({ event, handler });
358
+ }
359
+ }
360
+
361
+ /**
362
+ * Image loading helpers
363
+ *
364
+ * @param {File} file
365
+ * @private
366
+ */
367
+ _loadImageFile(file) {
368
+ if (!file || !file.type.startsWith('image/')) return;
369
+ const reader = new FileReader();
370
+ reader.onload = (e) => this.loadImage(e.target.result);
371
+ reader.onerror = (e) => { console.error(`[ImageEditor: fileReadError]`, e); }
372
+ reader.readAsDataURL(file);
373
+ }
374
+
375
+ /**
376
+ * Load a base64 encoded image string into fabric.
377
+ * @async
378
+ * @param {String} base64
379
+ */
380
+ async loadImage(base64) {
381
+ if (!this._fabricLoaded) return;
382
+ if (!base64 || typeof base64 !== 'string' || !base64.startsWith('data:image/')) return;
383
+
384
+ this._setPlaceholderVisible(false);
385
+
386
+ const imgEl = await this._createImageElement(base64);
387
+
388
+ let loadSrc = base64;
389
+ if (this.options.downsampleOnLoad) {
390
+ const needResize =
391
+ imgEl.naturalWidth > this.options.downsampleMaxWidth ||
392
+ imgEl.naturalHeight > this.options.downsampleMaxHeight;
393
+ if (needResize) {
394
+ const ratio = Math.min(
395
+ this.options.downsampleMaxWidth / imgEl.naturalWidth,
396
+ this.options.downsampleMaxHeight / imgEl.naturalHeight
397
+ );
398
+ const tw = Math.round(imgEl.naturalWidth * ratio);
399
+ const th = Math.round(imgEl.naturalHeight * ratio);
400
+ loadSrc = this._resampleImageToDataURL(imgEl, tw, th, this.options.downsampleQuality);
401
+ }
402
+ }
403
+
404
+ // Create fabric.Image from URL
405
+ fabric.Image.fromURL(loadSrc, (fimg) => {
406
+ this.canvas.discardActiveObject();
407
+ this._hideAllMaskLabels();
408
+ this.canvas.clear();
409
+ this.canvas.setBackgroundColor(this.options.backgroundColor, this.canvas.renderAll.bind(this.canvas));
410
+
411
+ fimg.set({ originX: 'left', originY: 'top', selectable: false, evented: false });
412
+
413
+ const imgW = fimg.width;
414
+ const imgH = fimg.height;
415
+
416
+ const minW = this.containerEl ? Math.floor(this.containerEl.clientWidth || this.options.canvasWidth) : this.options.canvasWidth;
417
+ const minH = this.containerEl ? Math.floor(this.containerEl.clientHeight || this.options.canvasHeight) : this.options.canvasHeight;
418
+
419
+ if (this.options.fitImageToCanvas) {
420
+ // Fit into current canvas (shrink only)
421
+ const cw = Math.max(this.options.canvasWidth, minW);
422
+ const ch = Math.max(this.options.canvasHeight, minH);
423
+ this._setCanvasSizeInt(cw, ch);
424
+ const fitScale = Math.min(cw / imgW, ch / imgH, 1);
425
+ fimg.set({ left: (cw - imgW * fitScale) / 2, top: (ch - imgH * fitScale) / 2 });
426
+ fimg.scale(fitScale);
427
+ this.baseImageScale = fimg.scaleX || 1;
428
+ } else if (this.options.expandCanvasToImage) {
429
+ // Expand canvas so that it fully contains the image
430
+ const cw = Math.max(minW, Math.floor(imgW));
431
+ const ch = Math.max(minH, Math.floor(imgH));
432
+ this._setCanvasSizeInt(cw, ch);
433
+ fimg.set({ left: 0, top: 0 });
434
+ fimg.scale(1);
435
+ this.baseImageScale = 1;
436
+ } else {
437
+ // Keep existing canvas size and center the image
438
+ const cw = Math.max(this.options.canvasWidth, minW);
439
+ const ch = Math.max(this.options.canvasHeight, minH);
440
+ this._setCanvasSizeInt(cw, ch);
441
+ const fitScale = Math.min(cw / imgW, ch / imgH, 1);
442
+ fimg.set({ left: (cw - imgW * fitScale) / 2, top: (ch - imgH * fitScale) / 2 });
443
+ fimg.scale(fitScale);
444
+ this.baseImageScale = fimg.scaleX || 1;
445
+ }
446
+ // Put the image onto the canvas
447
+ this.originalImage = fimg;
448
+ this.canvas.add(fimg);
449
+ this.canvas.sendToBack(fimg);
450
+
451
+ // Reset mask placement memory
452
+ this._lastMaskInitialLeft = null;
453
+ this._lastMaskInitialTop = null;
454
+ this._lastMaskInitialWidth = null;
455
+
456
+ this.maskCounter = 0;
457
+ this.currentScale = 1;
458
+ this.currentRotation = 0;
459
+
460
+ this._updateInputs();
461
+ this._updateMaskList();
462
+ this._updateUI();
463
+ this.canvas.renderAll();
464
+ this.isImageLoadedToCanvas = true;
465
+
466
+ if (typeof this.onImageLoaded === 'function') {
467
+ this.onImageLoaded();
468
+ }
469
+ }, { crossOrigin: 'anonymous' });
470
+ }
471
+
472
+ /**
473
+ * Checks whether there is a loaded image on the current canvas.
474
+ * @returns {boolean} true if loaded, false if not
475
+ */
476
+ isImageLoaded() {
477
+ return !!(
478
+ this.originalImage &&
479
+ this.originalImage instanceof fabric.Image &&
480
+ this.originalImage.width > 0 &&
481
+ this.originalImage.height > 0
482
+ );
483
+ }
484
+
485
+ /**
486
+ * Creates an HTMLImageElement from a given data URL.
487
+ *
488
+ * @param {string} dataURL - A data URL representing the image (e.g., "data:image/png;base64,...").
489
+ * @returns {Promise<HTMLImageElement>} A promise that resolves to the created image element when loaded, or rejects on error.
490
+ * @private
491
+ */
492
+ _createImageElement(dataURL) {
493
+ return new Promise((res, rej) => {
494
+ const img = new Image();
495
+ img.onload = () => {
496
+ img.onload = null;
497
+ img.onerror = null;
498
+ res(img);
499
+ };
500
+ img.onerror = (e) => {
501
+ img.onload = null;
502
+ img.onerror = null;
503
+ rej(e);
504
+ };
505
+ img.src = dataURL;
506
+ });
507
+ }
508
+
509
+ /**
510
+ * Resamples the given image element to a new width and height and returns the result as a JPEG data URL.
511
+ *
512
+ * @param {HTMLImageElement} imgEl - The image element to resample.
513
+ * @param {number} w - Target width (in pixels) for the resampled image.
514
+ * @param {number} h - Target height (in pixels) for the resampled image.
515
+ * @param {number} [quality=0.92] - JPEG image quality between 0 and 1 (optional, default 0.92).
516
+ * @returns {string} A data URL representing the resampled image as JPEG.
517
+ * @private
518
+ */
519
+ _resampleImageToDataURL(imgEl, w, h, quality = 0.92) {
520
+ const oc = document.createElement('canvas');
521
+ oc.width = w;
522
+ oc.height = h;
523
+ const ctx = oc.getContext('2d');
524
+ ctx.drawImage(imgEl, 0, 0, imgEl.naturalWidth, imgEl.naturalHeight, 0, 0, w, h);
525
+ return oc.toDataURL('image/jpeg', quality);
526
+ }
527
+
528
+ /**
529
+ * Sets canvas size to integer width and height values to prevent scrollbars due to sub-pixel rendering.
530
+ * Also updates the corresponding style attributes.
531
+ *
532
+ * @param {number} w - Canvas width (in pixels).
533
+ * @param {number} h - Canvas height (in pixels).
534
+ * @private
535
+ */
536
+ _setCanvasSizeInt(w, h) {
537
+ const iw = Math.max(1, Math.round(Number(w) || 1));
538
+ const ih = Math.max(1, Math.round(Number(h) || 1));
539
+ // Set fabric internal and also style attributes to keep DOM consistent
540
+ this.canvas.setWidth(iw);
541
+ this.canvas.setHeight(ih);
542
+ if (typeof this.canvas.calcOffset === 'function') this.canvas.calcOffset();
543
+ // Keep DOM element in sync (avoid fractional CSS pixels)
544
+ if (this.canvasEl) {
545
+ this.canvasEl.style.width = iw + 'px';
546
+ this.canvasEl.style.height = ih + 'px';
547
+ this.canvasEl.style.maxWidth = 'none';
548
+ }
549
+ }
550
+
551
+ /**
552
+ * Gets the top-left corner coordinates of the given object.
553
+ * Used for geometry calculations (e.g., scale, rotate).
554
+ *
555
+ * @param {Object} obj - The object for which to get the top-left coordinates. Should support setCoords and getCoords/getBoundingRect methods.
556
+ * @returns {{x: number, y: number}} The top-left corner point as an object with x and y properties.
557
+ * @private
558
+ */
559
+ _getObjectTopLeftPoint(obj) {
560
+ if (!obj) return { x: 0, y: 0 };
561
+ obj.setCoords();
562
+ const coords = typeof obj.getCoords === 'function' ? obj.getCoords() : null;
563
+ if (coords && coords.length) return coords[0];
564
+ const br = obj.getBoundingRect(true, true);
565
+ return { x: br.left, y: br.top };
566
+ }
567
+
568
+ /**
569
+ * Sets the object's origin at the specified origin point, keeping a reference point fixed in position.
570
+ *
571
+ * @param {Object} obj - The object to modify. Should support set, setPositionByOrigin, and setCoords.
572
+ * @param {string} originX - The new originX ("left", "center", "right", etc.).
573
+ * @param {string} originY - The new originY ("top", "center", "bottom", etc.).
574
+ * @param {{x: number, y: number}} refPoint - The point to keep fixed while setting the new origins.
575
+ * @private
576
+ */
577
+ _setObjectOriginKeepingPosition(obj, originX, originY, refPoint) {
578
+ if (!obj || !refPoint || !obj.setPositionByOrigin) return;
579
+ obj.set({ originX, originY });
580
+ obj.setPositionByOrigin(refPoint, originX, originY);
581
+ obj.setCoords();
582
+ }
583
+
584
+ /**
585
+ * Moves the object so its bounding box aligns with the canvas's top-left corner (0, 0).
586
+ *
587
+ * @param {Object} obj - The object to align.
588
+ * @private
589
+ */
590
+ _alignObjectBoundingBoxToCanvasTopLeft(obj) {
591
+ if (!obj) return;
592
+ obj.setCoords();
593
+ const br = obj.getBoundingRect(true, true);
594
+ const dx = br.left;
595
+ const dy = br.top;
596
+ obj.set({ left: (obj.left || 0) - dx, top: (obj.top || 0) - dy });
597
+ obj.setCoords();
598
+ this.canvas.renderAll();
599
+ }
600
+
601
+ /**
602
+ * Updates the canvas size to match the bounding box of the original image,
603
+ * ensuring that the canvas is always at least as large as its container.
604
+ * @private
605
+ */
606
+ _updateCanvasSizeToImageBounds() {
607
+ if (!this.originalImage) return;
608
+ this.originalImage.setCoords();
609
+ const br = this.originalImage.getBoundingRect(true, true);
610
+
611
+ // Container integer sizes
612
+ const containerW = this.containerEl ? Math.ceil(this.containerEl.clientWidth || 0) : 0;
613
+ const containerH = this.containerEl ? Math.ceil(this.containerEl.clientHeight || 0) : 0;
614
+
615
+ // If image smaller or equal than container in BOTH dims => keep canvas equal to container
616
+ if (containerW > 0 && containerH > 0 && br.width <= containerW && br.height <= containerH) {
617
+ this._setCanvasSizeInt(containerW, containerH);
618
+ return;
619
+ }
620
+
621
+ // Else canvas follows image bounding box but not smaller than container dims individually
622
+ const newW = Math.max(containerW || 0, Math.floor(br.width));
623
+ const newH = Math.max(containerH || 0, Math.floor(br.height));
624
+ this._setCanvasSizeInt(newW, newH);
625
+ }
626
+
627
+ /**
628
+ * Scales the original image by a given factor, with animation.
629
+ * Returns a promise that resolves when the scale animation is complete.
630
+ * @param {number} factor - The scaling factor (will be clamped between `options.minScale` and `options.maxScale`).
631
+ * @returns {Promise<void>} Promise that resolves once the scaling animation finishes.
632
+ * @public
633
+ */
634
+ scaleImage(factor) {
635
+ return this.animQueue.add(() => this._scaleImageImpl(factor));
636
+ }
637
+
638
+ /**
639
+ * Scales the original image by a given factor, with animation.
640
+ * Returns a promise that resolves when the scale animation is complete.
641
+ * @param {number} factor - The scaling factor (will be clamped between `options.minScale` and `options.maxScale`).
642
+ * @returns {Promise<void>} Promise that resolves once the scaling animation finishes.
643
+ * @private
644
+ */
645
+ _scaleImageImpl(factor) {
646
+ if (!this.originalImage) return Promise.resolve();
647
+ if (this.isAnimating) return Promise.resolve();
648
+ factor = Math.max(this.options.minScale, Math.min(this.options.maxScale, factor));
649
+ this.currentScale = factor;
650
+ this.isAnimating = true;
651
+ this._updateUI();
652
+
653
+ const targetAbs = this.baseImageScale * factor;
654
+
655
+ // Scale around current top-left (recompute)
656
+ const topLeft = this._getObjectTopLeftPoint(this.originalImage);
657
+ this._setObjectOriginKeepingPosition(this.originalImage, 'left', 'top', topLeft);
658
+
659
+ const p1 = new Promise((res) => {
660
+ this.originalImage.animate('scaleX', targetAbs, {
661
+ duration: this.options.animationDuration,
662
+ onChange: this.canvas.renderAll.bind(this.canvas),
663
+ onComplete: res
664
+ });
665
+ });
666
+ const p2 = new Promise((res) => {
667
+ this.originalImage.animate('scaleY', targetAbs, {
668
+ duration: this.options.animationDuration,
669
+ onChange: this.canvas.renderAll.bind(this.canvas),
670
+ onComplete: res
671
+ });
672
+ });
673
+
674
+ return Promise.all([p1, p2]).then(() => {
675
+ this.originalImage.set({ scaleX: targetAbs, scaleY: targetAbs });
676
+ this.originalImage.setCoords();
677
+
678
+ if (this.options.expandCanvasToImage) this._updateCanvasSizeToImageBounds();
679
+
680
+ this._alignObjectBoundingBoxToCanvasTopLeft(this.originalImage);
681
+
682
+ // Sync mask labels
683
+ this.canvas.getObjects().forEach(o => { if (o.maskId) this._syncMaskLabel(o); });
684
+
685
+ this.isAnimating = false;
686
+ this._updateInputs();
687
+ this._updateUI();
688
+ this.saveState();
689
+ }).catch(() => {
690
+ this.isAnimating = false;
691
+ this._updateUI();
692
+ });
693
+ }
694
+
695
+ /**
696
+ * Rotates the original image by a given number of degrees, with animation.
697
+ * Returns a promise that resolves when the rotation animation is complete.
698
+ * @param {number} degrees - The angle in degrees to rotate the image.
699
+ * @returns {Promise<void>} Promise that resolves once the rotation animation finishes.
700
+ * @public
701
+ */
702
+ rotateImage(deg) {
703
+ return this.animQueue.add(() => this._rotateImageImpl(deg));
704
+ }
705
+
706
+ /**
707
+ * Rotates the original image by a given number of degrees, with animation.
708
+ * Returns a promise that resolves when the rotation animation is complete.
709
+ * @param {number} degrees - The angle in degrees to rotate the image.
710
+ * @returns {Promise<void>} Promise that resolves once the rotation animation finishes.
711
+ * @private
712
+ */
713
+ _rotateImageImpl(degrees) {
714
+ if (!this.originalImage) return Promise.resolve();
715
+ if (this.isAnimating) return Promise.resolve();
716
+ if (isNaN(degrees)) return Promise.resolve();
717
+ this.currentRotation = degrees;
718
+ this.isAnimating = true;
719
+ this._updateUI();
720
+
721
+ const center = this.originalImage.getCenterPoint();
722
+ this._setObjectOriginKeepingPosition(this.originalImage, 'center', 'center', center);
723
+
724
+ const p = new Promise((res) => {
725
+ this.originalImage.animate('angle', degrees, {
726
+ duration: this.options.animationDuration,
727
+ onChange: this.canvas.renderAll.bind(this.canvas),
728
+ onComplete: res
729
+ });
730
+ });
731
+
732
+ return p.then(() => {
733
+ this.originalImage.set('angle', degrees);
734
+ this.originalImage.setCoords();
735
+
736
+ if (this.options.expandCanvasToImage) this._updateCanvasSizeToImageBounds();
737
+
738
+ this._alignObjectBoundingBoxToCanvasTopLeft(this.originalImage);
739
+
740
+ const newTopLeft = this._getObjectTopLeftPoint(this.originalImage);
741
+ this._setObjectOriginKeepingPosition(this.originalImage, 'left', 'top', newTopLeft);
742
+
743
+ // Sync mask labels
744
+ this.canvas.getObjects().forEach(o => { if (o.maskId) this._syncMaskLabel(o); });
745
+
746
+ this.isAnimating = false;
747
+ this._updateInputs();
748
+ this._updateUI();
749
+ this.saveState();
750
+ }).catch(() => {
751
+ this.isAnimating = false;
752
+ this._updateUI();
753
+ });
754
+ }
755
+
756
+ /**
757
+ * Resets the image: scales to 1 and rotates to 0 degrees.
758
+ * @returns {Promise<void>} Promise that resolves when reset is complete.
759
+ */
760
+ reset() {
761
+ if (!this.originalImage) return Promise.resolve();
762
+
763
+ return this.scaleImage(1)
764
+ .then(() => this.rotateImage(0))
765
+ .then(() => {
766
+ this.saveState();
767
+ })
768
+ .catch(err => {
769
+ console.error('reset() failed', err);
770
+ });
771
+ }
772
+
773
+ /**
774
+ * Restores a canvas state that was previously stored by saveState().
775
+ * @param {string} jsonString - the JSON string returned by fabric.toJSON().
776
+ */
777
+ loadFromState(jsonString) {
778
+ if (!jsonString || !this.canvas) return;
779
+
780
+ try {
781
+ const json = (typeof jsonString === 'string')
782
+ ? JSON.parse(jsonString)
783
+ : jsonString;
784
+
785
+ this.canvas.loadFromJSON(json, () => {
786
+ this._hideAllMaskLabels();
787
+ const objs = this.canvas.getObjects();
788
+ this.originalImage = objs.find(o => o.type === 'image' && !o.maskId) || null;
789
+
790
+ this.originalImage.set({ originX: 'left', originY: 'top', selectable: false, evented: false, hasControls: false, hoverCursor: 'default' });
791
+ this.canvas.sendToBack(this.originalImage);
792
+
793
+ const masks = objs.filter(o => o.maskId);
794
+ this.maskCounter = masks.reduce((max, m) =>
795
+ Math.max(max, m.maskId), 0);
796
+
797
+ this.canvas.renderAll();
798
+ this._updateMaskList();
799
+ this._updateUI();
800
+ });
801
+
802
+ } catch (e) {
803
+ console.error('loadFromState() failed', e);
804
+ }
805
+ }
806
+
807
+ /**
808
+ * Saves the current state of the canvas to history, storing any mask/raster label information.
809
+ */
810
+ saveState() {
811
+ if (!this.canvas) return;
812
+ const activeObj = this.canvas.getActiveObject();
813
+ this._hideAllMaskLabels();
814
+
815
+ try {
816
+ // request JSON including the custom flag 'isCropRect' so we can filter it out
817
+ const jsonObj = this.canvas.toJSON(['maskId', 'maskName', 'isCropRect']);
818
+ if (Array.isArray(jsonObj.objects)) {
819
+ // filter out crop-rect objects before stringifying
820
+ jsonObj.objects = jsonObj.objects.filter(o => !o.isCropRect);
821
+ }
822
+ const after = JSON.stringify(jsonObj);
823
+ const before = this._lastSnapshot || after;
824
+ let executedOnce = false;
825
+
826
+ const cmd = new Command(
827
+ () => {
828
+ if (executedOnce) {
829
+ this.loadFromState(after);
830
+ }
831
+ executedOnce = true;
832
+ },
833
+ () => {
834
+ this.loadFromState(before);
835
+ }
836
+ );
837
+
838
+ this.historyManager.execute(cmd);
839
+ this._lastSnapshot = after;
840
+ if (activeObj && activeObj.maskId) {
841
+ this._showLabelForMask(activeObj);
842
+ }
843
+ this._updateUI();
844
+ } catch (err) {
845
+ console.warn('saveState: failed to save canvas snapshot', err);
846
+ }
847
+ }
848
+
849
+ /**
850
+ * Undo the last state change, if possible.
851
+ */
852
+ undo() {
853
+ this.historyManager.undo();
854
+ }
855
+
856
+ /**
857
+ * Redo the next state change, if possible.
858
+ */
859
+ redo() {
860
+ this.historyManager.redo();
861
+ }
862
+
863
+ /**
864
+ * Adds a rectangular mask to the canvas.
865
+ * Mask placement and properties are determined by the provided config and instance options.
866
+ * Canvas and list UI are updated accordingly.
867
+ * @param {Object} [config={}] - Optional mask configuration overrides:
868
+ * @param {string} [config.shape='rect'] - 'rect', 'circle', 'ellipse', 'polygon', ...
869
+ * @param {Object|Array} [config.points] - Required for polygon: [{x, y}, ...] or [[x, y], ...]
870
+ * @param {number|function} [config.width/height/rx/ry/radius] - Can be number or function(canvas, options)
871
+ * @param {number|string|function} [config.left/top] - Absolute, %, or function
872
+ * @param {number|string} [config.angle] - Rotation angle (degree)
873
+ * @param {string} [config.color] - Fill color in CSS color format (default 'rgba(0,0,0,0.5)')
874
+ * @param {number} [config.alpha] - Opacity, from 0 to 1 (default 0.5)
875
+ * @param {boolean} [config.selectable=true]
876
+ * @param {Object} [config.styles] - Custom styles (stroke, dashArray, etc)
877
+ * @param {function} [config.onCreate] - Callback after mask created (receives Fabric object)
878
+ * @param {function} [config.fabricGenerator] - (cfg) => new FabricObj
879
+ * @returns {fabric.Rect|null} The created mask object, or null if canvas is not available.
880
+ * @public
881
+ */
882
+ addMask(config = {}) {
883
+ if (!this.canvas) return null;
884
+ const shapeType = config.shape || 'rect';
885
+ // Default config
886
+ const cfg = {
887
+ shape: shapeType,
888
+ width: this.options.defaultMaskWidth,
889
+ height: this.options.defaultMaskHeight,
890
+ color: 'rgba(0,0,0,0.5)',
891
+ alpha: 0.5,
892
+ gap: 5,
893
+ left: undefined,
894
+ top: undefined,
895
+ angle: 0,
896
+ selectable: true,
897
+ ...config
898
+ };
899
+
900
+ // Always start placement relative to canvas left/top.
901
+ const firstOffset = 10;
902
+ let left = firstOffset;
903
+ let top = firstOffset;
904
+
905
+ const resolveValue = (val, fallback) => {
906
+ if (typeof val === 'function')
907
+ return val(this.canvas, this.options); // This context is this of addMask
908
+ if (typeof val === 'string' && val.endsWith('%')) {
909
+ const percent = parseFloat(val) / 100;
910
+ return Math.floor((this.canvas ? this.canvas.getWidth() : 0) * percent);
911
+ }
912
+ return val != null ? val : fallback;
913
+ }
914
+
915
+ if (cfg.left === undefined && this._lastMask) {
916
+ const prev = this._lastMask;
917
+ let prevRight = prev.left;
918
+
919
+ if (prev.getScaledWidth) {
920
+ prevRight += prev.getScaledWidth();
921
+ } else if (prev.width) {
922
+ prevRight += prev.width * (prev.scaleX ?? 1);
923
+ }
924
+ left = Math.round(prevRight + cfg.gap);
925
+ top = prev.top ?? firstOffset;
926
+ } else {
927
+ left = resolveValue(cfg.left, firstOffset);
928
+ top = resolveValue(cfg.top, firstOffset);
929
+ }
930
+
931
+ cfg.width = resolveValue(cfg.width, this.options.defaultMaskWidth);
932
+ cfg.height = resolveValue(cfg.height, this.options.defaultMaskHeight);
933
+
934
+ // If expandCanvasToImage mode, ensure canvas large enough to hold mask initial placement
935
+ if (this.options.expandCanvasToImage && shapeType === 'rect') {
936
+ const requiredW = Math.ceil(left + cfg.width + 10);
937
+ const requiredH = Math.ceil(top + cfg.height + 10);
938
+ const minW = this.containerEl ? Math.floor(this.containerEl.clientWidth || 0) : 0;
939
+ const minH = this.containerEl ? Math.floor(this.containerEl.clientHeight || 0) : 0;
940
+ const newW = Math.max(this.canvas.getWidth(), minW, requiredW);
941
+ const newH = Math.max(this.canvas.getHeight(), minH, requiredH);
942
+ this._setCanvasSizeInt(newW, newH);
943
+ }
944
+
945
+ let mask;
946
+ if (typeof cfg.fabricGenerator === 'function') {
947
+ mask = cfg.fabricGenerator(cfg, this.canvas, this.options);
948
+ } else {
949
+ switch (shapeType) {
950
+ case 'circle':
951
+ mask = new fabric.Circle({
952
+ left, top,
953
+ radius: resolveValue(cfg.radius, Math.min(cfg.width, cfg.height) / 2),
954
+ fill: cfg.color,
955
+ opacity: cfg.alpha,
956
+ angle: cfg.angle,
957
+ ...cfg.styles
958
+ });
959
+ break;
960
+ case 'ellipse':
961
+ mask = new fabric.Ellipse({
962
+ left, top,
963
+ rx: resolveValue(cfg.rx, cfg.width / 2),
964
+ ry: resolveValue(cfg.ry, cfg.height / 2),
965
+ fill: cfg.color,
966
+ opacity: cfg.alpha,
967
+ angle: cfg.angle,
968
+ ...cfg.styles
969
+ });
970
+ break;
971
+ case 'polygon':
972
+ let polyPoints = cfg.points || [];
973
+ if (Array.isArray(polyPoints) && polyPoints.length && typeof polyPoints[0] === 'object') {
974
+ // Ensure numeric {x,y} objects for fabric.Polygon
975
+ polyPoints = polyPoints.map(pt => ({ x: Number(pt.x), y: Number(pt.y) }));
976
+ }
977
+ mask = new fabric.Polygon(polyPoints, {
978
+ left, top,
979
+ fill: cfg.color,
980
+ opacity: cfg.alpha,
981
+ angle: cfg.angle,
982
+ ...cfg.styles
983
+ });
984
+ break;
985
+ case 'rect':
986
+ default:
987
+ mask = new fabric.Rect({
988
+ left, top,
989
+ width: resolveValue(cfg.width, this.options.defaultMaskWidth),
990
+ height: resolveValue(cfg.height, this.options.defaultMaskHeight),
991
+ fill: cfg.color,
992
+ opacity: cfg.alpha,
993
+ angle: cfg.angle,
994
+ rx: cfg.rx, // Rounded Corners
995
+ ry: cfg.ry,
996
+ ...cfg.styles
997
+ });
998
+ }
999
+ }
1000
+
1001
+ mask.selectable = cfg.selectable !== false;
1002
+ mask.hasControls = ('hasControls' in cfg) ? cfg.hasControls : true;
1003
+ mask.lockRotation = !this.options.maskRotatable;
1004
+ mask.borderColor = cfg.borderColor || 'red';
1005
+ mask.cornerColor = cfg.cornerColor || 'black';
1006
+ mask.cornerSize = cfg.cornerSize || 8;
1007
+ mask.transparentCorners = ('transparentCorners' in cfg) ? cfg.transparentCorners : false;
1008
+ mask.stroke = (cfg.styles && cfg.styles.stroke) || '#ccc';
1009
+ mask.strokeWidth = (cfg.styles && cfg.styles.strokeWidth) || 1;
1010
+ mask.strokeUniform = ('strokeUniform' in cfg) ? cfg.strokeUniform : true;
1011
+ if (cfg.styles && cfg.styles.strokeDashArray) mask.strokeDashArray = cfg.styles.strokeDashArray;
1012
+
1013
+ mask.originalAlpha = cfg.alpha;
1014
+ const normalStyle = { stroke: mask.stroke, strokeWidth: mask.strokeWidth, opacity: mask.originalAlpha };
1015
+ const hoverStyle = { stroke: '#ff5500', strokeWidth: 2, opacity: Math.min(mask.originalAlpha + 0.2, 1) };
1016
+
1017
+ mask.on('mouseover', () => {
1018
+ mask.set(hoverStyle);
1019
+ mask.canvas.requestRenderAll();
1020
+ });
1021
+
1022
+ mask.on('mouseout', () => {
1023
+ mask.set(normalStyle);
1024
+ mask.canvas.requestRenderAll();
1025
+ });
1026
+
1027
+ // Remember initial for next one
1028
+ this._lastMaskInitialLeft = left;
1029
+ this._lastMaskInitialTop = top;
1030
+ this._lastMaskInitialWidth = resolveValue(cfg.width, this.options.defaultMaskWidth);
1031
+
1032
+ mask.maskId = ++this.maskCounter;
1033
+ mask.maskName = `${this.options.maskName}${mask.maskId}`;
1034
+ this._lastMask = mask;
1035
+
1036
+ this.canvas.add(mask);
1037
+ this.canvas.bringToFront(mask);
1038
+ if (cfg.selectable) this.canvas.setActiveObject(mask);
1039
+ this._onSelectionChanged([mask]);
1040
+ this._updateMaskList();
1041
+ this._updateUI();
1042
+ this.canvas.renderAll();
1043
+ this.saveState();
1044
+
1045
+ if (typeof cfg.onCreate === 'function') cfg.onCreate(mask, this.canvas);
1046
+ return mask;
1047
+ }
1048
+
1049
+ /**
1050
+ * Removes the currently selected mask from the canvas, if any.
1051
+ * The associated label is also removed. UI and mask list are updated.
1052
+ */
1053
+ removeSelectedMask() {
1054
+ const active = this.canvas.getActiveObject();
1055
+ if (!active || !active.maskId) return;
1056
+ this._removeLabelForMask(active);
1057
+ this.canvas.remove(active);
1058
+ this.canvas.discardActiveObject();
1059
+ this._updateMaskList();
1060
+ this._updateUI();
1061
+ this.canvas.renderAll();
1062
+ this.saveState();
1063
+ }
1064
+
1065
+ /**
1066
+ * Removes all masks from the canvas, including their labels.
1067
+ * UI and internal mask placement memory are reset.
1068
+ */
1069
+ removeAllMasks() {
1070
+ const masks = this.canvas.getObjects().filter(o => o.maskId);
1071
+ masks.forEach(m => this._removeLabelForMask(m));
1072
+ masks.forEach(m => this.canvas.remove(m));
1073
+ this.canvas.discardActiveObject();
1074
+ this._lastMaskInitialLeft = null;
1075
+ this._lastMaskInitialTop = null;
1076
+ this._lastMaskInitialWidth = null;
1077
+ this._updateMaskList();
1078
+ this._updateUI();
1079
+ this.canvas.renderAll();
1080
+ this.saveState();
1081
+ }
1082
+
1083
+ /**
1084
+ * Removes the label associated with the specified mask object, if it exists.
1085
+ *
1086
+ * @param {fabric.Object} mask - The mask object whose label should be removed.
1087
+ * @private
1088
+ */
1089
+ _removeLabelForMask(mask) {
1090
+ if (!mask || !this.canvas) return;
1091
+ if (mask.__label) {
1092
+ try {
1093
+ const objs = this.canvas.getObjects();
1094
+ if (objs.includes(mask.__label)) {
1095
+ this.canvas.remove(mask.__label);
1096
+ }
1097
+ } catch (e) { /* ignore */ }
1098
+ try { delete mask.__label; } catch (e) { }
1099
+ }
1100
+ }
1101
+
1102
+ /**
1103
+ * Creates and adds a custom label (fabric.Text or fabric.IText) for the mask.
1104
+ * The label is default bound to the top-left of the mask and managed as a non-interactive overlay.
1105
+ *
1106
+ * @param {fabric.Object} mask - The mask to create a label for.
1107
+ * @private
1108
+ */
1109
+ _createLabelForMask(mask) {
1110
+ if (!mask || !this.options.maskLabelOnSelect) return;
1111
+ this._removeLabelForMask(mask);
1112
+ let textObj = null;
1113
+ if (this.options.label && typeof this.options.label.create === 'function') {
1114
+ textObj = this.options.label.create(mask, fabric);
1115
+ }
1116
+ if (!textObj) {
1117
+ let txt = mask.maskName; // Default
1118
+ let textOptions = {
1119
+ left: 0,
1120
+ top: 0,
1121
+ fontSize: 12,
1122
+ fill: '#fff',
1123
+ backgroundColor: 'rgba(0,0,0,0.7)',
1124
+ selectable: false,
1125
+ evented: false,
1126
+ padding: 2,
1127
+ originX: 'left',
1128
+ originY: 'top'
1129
+ };
1130
+ if (this.options.label) {
1131
+ if (typeof this.options.label.getText === 'function') {
1132
+ txt = this.options.label.getText(mask, this.maskCounter);
1133
+ }
1134
+ // Merge external styles
1135
+ if (this.options.label.textOptions) {
1136
+ Object.assign(textOptions, this.options.label.textOptions);
1137
+ }
1138
+ }
1139
+ textObj = new fabric.Text(txt, textOptions);
1140
+ }
1141
+
1142
+ textObj.maskLabel = true;
1143
+ mask.__label = textObj;
1144
+ this.canvas.add(textObj);
1145
+ this.canvas.bringToFront(textObj);
1146
+ this._syncMaskLabel(mask);
1147
+ }
1148
+
1149
+ /**
1150
+ * Hides (removes) all mask labels from the canvas.
1151
+ * Internal label references on mask objects are also deleted.
1152
+ * @private
1153
+ */
1154
+ _hideAllMaskLabels() {
1155
+ if (!this.canvas) return;
1156
+ const objs = this.canvas.getObjects();
1157
+ const labels = objs.filter(o => o.maskLabel);
1158
+ labels.forEach(l => {
1159
+ try {
1160
+ if (objs.includes(l)) this.canvas.remove(l);
1161
+ } catch (e) { }
1162
+ });
1163
+ objs.forEach(o => { if (o.maskId && o.__label) { try { delete o.__label; } catch (e) { } } });
1164
+ }
1165
+
1166
+ /**
1167
+ * Synchronizes the position, angle, and visibility of the mask's label so that it appears properly above the mask.
1168
+ *
1169
+ * @param {fabric.Object} mask - The mask whose label should be repositioned.
1170
+ * @private
1171
+ */
1172
+ _syncMaskLabel(mask) {
1173
+ if (!mask) return;
1174
+ if (!this.options.maskLabelOnSelect) return;
1175
+ if (!mask.__label) return;
1176
+
1177
+ const coords = mask.getCoords ? mask.getCoords() : null;
1178
+ if (!coords || coords.length < 4) return;
1179
+
1180
+ const tl = coords[0];
1181
+ const center = mask.getCenterPoint();
1182
+
1183
+ const vx = center.x - tl.x;
1184
+ const vy = center.y - tl.y;
1185
+ const dist = Math.sqrt(vx * vx + vy * vy) || 1;
1186
+ const ux = vx / dist;
1187
+ const uy = vy / dist;
1188
+
1189
+ const offset = Math.max(0, this.options.maskLabelOffset ?? 3);
1190
+
1191
+ const px = tl.x + ux * offset;
1192
+ const py = tl.y + uy * offset;
1193
+
1194
+ mask.__label.set({
1195
+ left: Math.round(px),
1196
+ top: Math.round(py),
1197
+ angle: mask.angle || 0,
1198
+ originX: 'left',
1199
+ originY: 'top',
1200
+ visible: true
1201
+ });
1202
+ mask.__label.setCoords();
1203
+ this.canvas.renderAll();
1204
+ }
1205
+
1206
+ /**
1207
+ * Shows the label for the given mask, creating it if necessary and synchronizing its position.
1208
+ *
1209
+ * @param {fabric.Object} mask - The mask whose label should be shown.
1210
+ * @private
1211
+ */
1212
+ _showLabelForMask(mask) {
1213
+ if (!mask) return;
1214
+ if (!this.options.maskLabelOnSelect) return;
1215
+ if (!mask.__label) this._createLabelForMask(mask);
1216
+ mask.__label.visible = true;
1217
+ this._syncMaskLabel(mask);
1218
+ }
1219
+
1220
+ /**
1221
+ * Handles changes to the selection of canvas objects (masks),
1222
+ * updates mask stroke and label display, and syncs mask list selection.
1223
+ *
1224
+ * @param {Array<Object>} selected - The currently selected objects (e.g. [mask] or []).
1225
+ * @private
1226
+ */
1227
+ _onSelectionChanged(selected) {
1228
+ const selectedMask = (selected || []).find(o => o.maskId);
1229
+ const masks = this.canvas.getObjects().filter(o => o.maskId);
1230
+ masks.forEach(m => {
1231
+ if (m !== selectedMask) {
1232
+ if (m.__label) {
1233
+ try { this.canvas.remove(m.__label); } catch (e) { }
1234
+ delete m.__label;
1235
+ }
1236
+ m.set({ stroke: '#ccc', strokeWidth: 1 });
1237
+ } else {
1238
+ m.set({ stroke: '#ff0000', strokeWidth: 1 });
1239
+ }
1240
+ });
1241
+
1242
+ if (selectedMask) this._showLabelForMask(selectedMask);
1243
+
1244
+ this._updateMaskListSelection(selectedMask);
1245
+ this.canvas.renderAll();
1246
+ this._updateUI();
1247
+ }
1248
+
1249
+ /**
1250
+ * Updates the mask list in the DOM to reflect the current masks on the canvas.
1251
+ * Each list entry becomes a clickable element for mask selection.
1252
+ * @private
1253
+ */
1254
+ _updateMaskList() {
1255
+ const listEl = document.getElementById(this.elements.maskList);
1256
+ if (!listEl) return;
1257
+ listEl.innerHTML = '';
1258
+ const masks = this.canvas.getObjects().filter(o => o.maskId);
1259
+ masks.forEach(mask => {
1260
+ const li = document.createElement('li');
1261
+ li.className = 'list-group-item mask-item';
1262
+ li.textContent = mask.maskName;
1263
+ li.onclick = () => { this.canvas.setActiveObject(mask); this._onSelectionChanged([mask]); };
1264
+ listEl.appendChild(li);
1265
+ });
1266
+ }
1267
+
1268
+ /**
1269
+ * Updates the visual selection (CSS 'active') state for the mask list in the DOM.
1270
+ *
1271
+ * @param {Object|null} selectedMask - The currently selected mask, or null if none selected.
1272
+ * @private
1273
+ */
1274
+ _updateMaskListSelection(selectedMask) {
1275
+ const listEl = document.getElementById(this.elements.maskList);
1276
+ if (!listEl) return;
1277
+ const items = listEl.querySelectorAll('.mask-item');
1278
+ items.forEach(item => {
1279
+ const isSelected = !!selectedMask && item.textContent === selectedMask.maskName;
1280
+ item.classList.toggle('active', isSelected);
1281
+ });
1282
+ }
1283
+
1284
+ /**
1285
+ * Merges current masks into the image: exports a masked/cropped image, removes all masks, and re-imports the merged image.
1286
+ * Will not run if no original image or no masks exist.
1287
+ * @async
1288
+ * @returns {Promise<void>} Resolves when merge and load are complete.
1289
+ */
1290
+ async merge() {
1291
+ if (!this.originalImage) return;
1292
+ const masks = this.canvas.getObjects().filter(o => o.maskId);
1293
+ if (!masks.length) return;
1294
+
1295
+ this.canvas.discardActiveObject();
1296
+ this.canvas.renderAll();
1297
+
1298
+ try {
1299
+ const merged = await this.getImageBase64({ exportImageArea: true, multiplier: this.options.exportMultiplier });
1300
+ this.removeAllMasks();
1301
+ await this.loadImage(merged);
1302
+ this.saveState();
1303
+ } catch (err) {
1304
+ console.error('merge error', err);
1305
+ if (this.canvasEl) this.canvasEl.style.visibility = '';
1306
+ }
1307
+ }
1308
+
1309
+ /**
1310
+ * Triggers a JPEG image download of the current canvas (image plus masks if configured).
1311
+ * The image area and multiplier are controlled by options.
1312
+ * @param {string} [fileName=this.options.defaultDownloadFileName] - Desired download file name.
1313
+ */
1314
+ downloadImage(fileName = this.options.defaultDownloadFileName) {
1315
+ if (!this.originalImage) return;
1316
+ const exportImageArea = this.options.exportImageAreaByDefault;
1317
+ this.getImageBase64({ exportImageArea, multiplier: this.options.exportMultiplier })
1318
+ .then(base64 => {
1319
+ const link = document.createElement('a');
1320
+ link.download = fileName;
1321
+ link.href = base64;
1322
+ document.body.appendChild(link);
1323
+ link.click();
1324
+ document.body.removeChild(link);
1325
+ })
1326
+ .catch(err => console.error('download error', err));
1327
+ }
1328
+
1329
+ /**
1330
+ * Exports the image as a Base64-encoded JPEG.
1331
+ * Can export either the original, or the current view including masks (clipped/cropped).
1332
+ * Will restore masks' state after temporary modifications for export.
1333
+ * @async
1334
+ * @param {Object} [opts={}] - Export options.
1335
+ * @param {boolean} [opts.exportImageArea] - If true, exports only the image bounding area with masks cropped and blended.
1336
+ * @param {number} [opts.multiplier=1] - Scaling multiplier for output (resolution).
1337
+ * @returns {Promise<string>} Promise resolving to a JPEG image data URL.
1338
+ * @throws {Error} If there is no image loaded.
1339
+ */
1340
+ async getImageBase64(opts = {}) {
1341
+ if (!this.originalImage) throw new Error('No image loaded');
1342
+ const exportImageArea = typeof opts.exportImageArea === 'boolean' ? opts.exportImageArea : this.options.exportImageAreaByDefault;
1343
+ const multiplier = opts.multiplier || this.options.exportMultiplier || 1;
1344
+
1345
+ if (!exportImageArea) {
1346
+ // Export original image pixels
1347
+ const imgEl = this.originalImage.getElement ? this.originalImage.getElement() : (this.originalImage._element || null);
1348
+ if (!imgEl) return this.canvas.toDataURL({ format: 'jpeg', quality: this.options.downsampleQuality, multiplier });
1349
+ const w = this.originalImage.width;
1350
+ const h = this.originalImage.height;
1351
+ const oc = document.createElement('canvas');
1352
+ oc.width = w;
1353
+ oc.height = h;
1354
+ const ctx = oc.getContext('2d');
1355
+ ctx.drawImage(imgEl, 0, 0, w, h);
1356
+ return oc.toDataURL('image/jpeg', this.options.downsampleQuality);
1357
+ }
1358
+
1359
+ // Export current scaled image area (masks clipped)
1360
+ const masks = this.canvas.getObjects().filter(o => o.maskId);
1361
+ const masksBackup = masks.map(m => ({
1362
+ obj: m,
1363
+ opacity: m.opacity,
1364
+ fill: m.fill,
1365
+ strokeWidth: m.strokeWidth,
1366
+ stroke: m.stroke,
1367
+ selectable: m.selectable,
1368
+ lockRotation: m.lockRotation
1369
+ }));
1370
+
1371
+ // Remove labels, deselect
1372
+ masks.forEach(m => this._removeLabelForMask(m));
1373
+ this.canvas.discardActiveObject();
1374
+ this.canvas.renderAll();
1375
+
1376
+ // Set masks to opaque black no border
1377
+ masks.forEach(m => {
1378
+ m.set({ opacity: 1, fill: '#000000', strokeWidth: 0, stroke: null, selectable: false });
1379
+ m.setCoords();
1380
+ });
1381
+ this.canvas.renderAll();
1382
+
1383
+ // Compute integer bounding box for image
1384
+ this.originalImage.setCoords();
1385
+ const imgBr = this.originalImage.getBoundingRect(true, true);
1386
+ const sx = Math.max(0, Math.round(imgBr.left));
1387
+ const sy = Math.max(0, Math.round(imgBr.top));
1388
+ const sw = Math.max(1, Math.round(imgBr.width));
1389
+ const sh = Math.max(1, Math.round(imgBr.height));
1390
+
1391
+ // Crop precisely in offscreen canvas
1392
+ const finalBase64 = await new Promise((resolve, reject) => {
1393
+ try {
1394
+ const fullDataUrl = this.canvas.toDataURL({
1395
+ format: 'jpeg',
1396
+ quality: this.options.downsampleQuality,
1397
+ multiplier: multiplier
1398
+ });
1399
+
1400
+ const img = new Image();
1401
+ img.onload = () => {
1402
+ try {
1403
+ const sxM = Math.round(sx * multiplier);
1404
+ const syM = Math.round(sy * multiplier);
1405
+ const swM = Math.round(sw * multiplier);
1406
+ const shM = Math.round(sh * multiplier);
1407
+
1408
+ const oc = document.createElement('canvas');
1409
+ oc.width = swM;
1410
+ oc.height = shM;
1411
+ const ctx = oc.getContext('2d');
1412
+
1413
+ ctx.drawImage(img, sxM, syM, swM, shM, 0, 0, swM, shM);
1414
+ const out = oc.toDataURL('image/jpeg', this.options.downsampleQuality);
1415
+ resolve(out);
1416
+ } catch (e) { reject(e); }
1417
+ };
1418
+ img.onerror = reject;
1419
+ img.src = fullDataUrl;
1420
+ } catch (e) { reject(e); }
1421
+ });
1422
+
1423
+ // Restore masks
1424
+ masksBackup.forEach(b => {
1425
+ try {
1426
+ b.obj.set({
1427
+ opacity: b.opacity,
1428
+ fill: b.fill,
1429
+ strokeWidth: b.strokeWidth,
1430
+ stroke: b.stroke,
1431
+ selectable: b.selectable,
1432
+ lockRotation: b.lockRotation
1433
+ });
1434
+ b.obj.setCoords();
1435
+ } catch (e) { }
1436
+ });
1437
+
1438
+ this.canvas.renderAll();
1439
+ return finalBase64;
1440
+ }
1441
+
1442
+ /**
1443
+ * Exports the current canvas (with or without masks) as a File object.
1444
+ * Allows you to choose whether to merge masks and specify file type (jpeg/png/webp).
1445
+ *
1446
+ * @async
1447
+ * @param {Object} [opts={}] - Export options.
1448
+ * @param {boolean} [opts.mergeMask=true] - If true, export image area with masks merged; if false, export the plain image without masks.
1449
+ * @param {string} [opts.fileType='jpeg'] - Output file type ('jpeg' | 'png' | 'webp'). Defaults to 'jpeg' on invalid input.
1450
+ * @param {number} [opts.quality=0.92] - Image quality for lossy types (0-1, default based on options.downsampleQuality).
1451
+ * @param {number} [opts.multiplier=1] - Output resolution multiplier.
1452
+ * @param {string} [opts.fileName] - Optional file name (only used for download).
1453
+ * @returns {Promise<File>} Resolves with the exported image as a File object.
1454
+ *
1455
+ * @example
1456
+ * const file = await this.exportImageFile({ mergeMask: false, fileType: 'png' });
1457
+ */
1458
+ async exportImageFile(opts = {}) {
1459
+ if (!this.originalImage) throw new Error('No image loaded');
1460
+ const {
1461
+ mergeMask = true,
1462
+ fileType = 'jpeg',
1463
+ quality = this.options.downsampleQuality ?? 0.92,
1464
+ multiplier = this.options.exportMultiplier ?? 1,
1465
+ fileName = this.options.defaultDownloadFileName ?? 'exported_image.jpg'
1466
+ } = opts;
1467
+
1468
+ const typeMapping = {
1469
+ 'jpeg': 'jpeg',
1470
+ 'jpg': 'jpeg',
1471
+ 'image/jpeg': 'jpeg',
1472
+ 'png': 'png',
1473
+ 'image/png': 'png',
1474
+ 'webp': 'webp',
1475
+ 'image/webp': 'webp'
1476
+ };
1477
+ const safeFileType = typeMapping[String(fileType).toLowerCase()] || 'jpeg';
1478
+
1479
+ // Get Base64
1480
+ let base64;
1481
+ if (mergeMask) {
1482
+ base64 = await this.getImageBase64({
1483
+ exportImageArea: true,
1484
+ multiplier,
1485
+ });
1486
+ } else {
1487
+ base64 = await this.getImageBase64({
1488
+ exportImageArea: false,
1489
+ multiplier,
1490
+ });
1491
+ }
1492
+
1493
+ // Convert to the required image format
1494
+ let imageDataUrl = base64;
1495
+ if (!imageDataUrl.startsWith(`data:image/${safeFileType}`)) {
1496
+ // Redraw if not required format
1497
+ imageDataUrl = await new Promise((resolve, reject) => {
1498
+ const img = new window.Image();
1499
+ img.crossOrigin = "Anonymous";
1500
+ img.onload = () => {
1501
+ try {
1502
+ const oc = document.createElement('canvas');
1503
+ oc.width = img.width;
1504
+ oc.height = img.height;
1505
+ const ctx = oc.getContext('2d');
1506
+ ctx.drawImage(img, 0, 0);
1507
+ const durl = oc.toDataURL(`image/${safeFileType}`, quality);
1508
+ resolve(durl);
1509
+ } catch (e) { reject(e); }
1510
+ };
1511
+ img.onerror = reject;
1512
+ img.src = base64;
1513
+ });
1514
+ }
1515
+
1516
+ // Convert DataURL to Blob and then to File
1517
+ const bstr = atob(imageDataUrl.split(',')[1]);
1518
+ const mime = `image/${safeFileType}`;
1519
+ let n = bstr.length;
1520
+ const u8arr = new Uint8Array(n);
1521
+ while (n--) {
1522
+ u8arr[n] = bstr.charCodeAt(n);
1523
+ }
1524
+ const file = new File([u8arr], fileName, { type: mime });
1525
+ return file;
1526
+ }
1527
+
1528
+ /**
1529
+ * Enter crop mode: create a resizable/movable selection rect on top of the image.
1530
+ * @public
1531
+ */
1532
+ enterCropMode() {
1533
+ if (!this.canvas || !this.originalImage || this._cropMode) return;
1534
+ if (!this.isImageLoaded()) return;
1535
+ this._cropMode = true;
1536
+
1537
+ // Disable canvas group selection to avoid accidental group selection while cropping
1538
+ this._prevSelectionSetting = this.canvas.selection;
1539
+ this.canvas.selection = false;
1540
+
1541
+ // Make sure no active object
1542
+ this.canvas.discardActiveObject();
1543
+
1544
+ // Create initial crop rect centered on the image bounding box
1545
+ this.originalImage.setCoords();
1546
+ const imgBr = this.originalImage.getBoundingRect(true, true);
1547
+ // Provide small inset so user can see a margin
1548
+ const padding = (this.options.crop && this.options.crop.padding) ? this.options.crop.padding : 10;
1549
+ const left = Math.max(0, Math.floor(imgBr.left + padding));
1550
+ const top = Math.max(0, Math.floor(imgBr.top + padding));
1551
+ const width = Math.min(this.options.crop.minWidth || 50, Math.floor(imgBr.width - padding * 2));
1552
+ const height = Math.min(this.options.crop.minHeight || 50, Math.floor(imgBr.height - padding * 2));
1553
+
1554
+ // Visual style: translucent fill + dashed stroke
1555
+ const cropRect = new fabric.Rect({
1556
+ left, top,
1557
+ width, height,
1558
+ fill: 'rgba(0,0,0,0.12)',
1559
+ stroke: '#00aaff',
1560
+ strokeDashArray: [6, 4],
1561
+ strokeWidth: 1,
1562
+ strokeUniform: true,
1563
+ selectable: true,
1564
+ hasRotatingPoint: !!(this.options.crop && this.options.crop.allowRotationOfCropRect),
1565
+ lockRotation: !(this.options.crop && this.options.crop.allowRotationOfCropRect),
1566
+ cornerSize: 8,
1567
+ objectCaching: false,
1568
+ originX: 'left',
1569
+ originY: 'top'
1570
+ });
1571
+
1572
+ // Ensure the crop rect is above everything
1573
+ this.canvas.add(cropRect);
1574
+ cropRect.isCropRect = true;
1575
+ this.canvas.bringToFront(cropRect);
1576
+ this.canvas.setActiveObject(cropRect);
1577
+
1578
+ // Keep reference
1579
+ this._cropRect = cropRect;
1580
+
1581
+ // While in crop mode: we want only the cropRect to be interactive
1582
+ // but still allow moving/scaling it. To be safe, set other objects evented=false temporarily.
1583
+ this._cropPrevEvented = [];
1584
+ this.canvas.getObjects().forEach(o => {
1585
+ if (o !== cropRect) {
1586
+ this._cropPrevEvented.push({ obj: o, evented: o.evented, selectable: o.selectable });
1587
+ try { o.evented = false; o.selectable = false; } catch (e) { /* ignore */ }
1588
+ }
1589
+ });
1590
+
1591
+ // When the crop rect changes, re-render
1592
+ const onModified = () => { try { cropRect.setCoords(); this.canvas.requestRenderAll(); } catch (e) { } };
1593
+ cropRect.on('modified', onModified);
1594
+ cropRect.on('moving', onModified);
1595
+ cropRect.on('scaling', onModified);
1596
+
1597
+ // Keep handlers to remove later
1598
+ this._cropHandlers.push({ target: cropRect, handlers: [{ evt: 'modified', fn: onModified }, { evt: 'moving', fn: onModified }, { evt: 'scaling', fn: onModified }] });
1599
+
1600
+ this._updateUI();
1601
+ this.canvas.renderAll();
1602
+ }
1603
+
1604
+ /**
1605
+ * Cancel crop mode and remove the temporary selection rect.
1606
+ * @public
1607
+ */
1608
+ cancelCrop() {
1609
+ if (!this.canvas || !this._cropMode) return;
1610
+ // Remove handlers if any and remove object
1611
+ if (this._cropRect) {
1612
+ try {
1613
+ if (this._cropHandlers && this._cropHandlers.length) {
1614
+ this._cropHandlers.forEach(h => {
1615
+ h.handlers.forEach(rec => h.target.off(rec.evt, rec.fn));
1616
+ });
1617
+ }
1618
+ } catch (e) { /* ignore */ }
1619
+
1620
+ try { this.canvas.remove(this._cropRect); } catch (e) { }
1621
+ this._cropRect = null;
1622
+ }
1623
+ // restore evented/selectable flags
1624
+ if (Array.isArray(this._cropPrevEvented)) {
1625
+ this._cropPrevEvented.forEach(i => {
1626
+ try { i.obj.evented = i.evented; i.obj.selectable = i.selectable; } catch (e) { }
1627
+ });
1628
+ }
1629
+ this._cropPrevEvented = null;
1630
+ this._cropHandlers = [];
1631
+ this._cropMode = false;
1632
+ // restore selection setting
1633
+ this.canvas.selection = !!this._prevSelectionSetting;
1634
+ this._prevSelectionSetting = undefined;
1635
+
1636
+ this.canvas.discardActiveObject();
1637
+ this._updateUI();
1638
+ this.canvas.renderAll();
1639
+ }
1640
+
1641
+ /**
1642
+ * Apply the current crop rectangle.
1643
+ * remove all masks and export canvas snapshot and crop via offscreen canvas
1644
+ * @public
1645
+ */
1646
+ async applyCrop() {
1647
+ if (!this.canvas || !this._cropMode || !this._cropRect) return;
1648
+
1649
+ // Ensure crop rect coords are fresh
1650
+ this._cropRect.setCoords();
1651
+ const rectBounds = this._cropRect.getBoundingRect(true, true);
1652
+
1653
+ // Compute integer crop region clamped to canvas
1654
+ const sx = Math.max(0, Math.round(rectBounds.left));
1655
+ const sy = Math.max(0, Math.round(rectBounds.top));
1656
+ const sw = Math.max(1, Math.round(Math.min(rectBounds.width, this.canvas.getWidth() - sx)));
1657
+ const sh = Math.max(1, Math.round(Math.min(rectBounds.height, this.canvas.getHeight() - sy)));
1658
+
1659
+ // Include isCropRect in toJSON whitelist so we can detect and filter them out.
1660
+ let beforeJson = null;
1661
+ try {
1662
+ const jsonObj = this.canvas.toJSON(['maskId', 'maskName', 'isCropRect']);
1663
+ if (Array.isArray(jsonObj.objects)) {
1664
+ jsonObj.objects = jsonObj.objects.filter(o => !o.isCropRect);
1665
+ }
1666
+ beforeJson = JSON.stringify(jsonObj);
1667
+ } catch (e) {
1668
+ console.warn('applyCrop: could not serialize before state', e);
1669
+ beforeJson = null;
1670
+ }
1671
+
1672
+
1673
+ // Remove ALL un-merged masks so they won't be baked into exported pixels
1674
+ try {
1675
+ const masks = this.canvas.getObjects().filter(o => o.maskId);
1676
+ if (masks && masks.length) {
1677
+ masks.forEach(m => {
1678
+ try {
1679
+ this._removeLabelForMask(m);
1680
+ this.canvas.remove(m);
1681
+ } catch (err) {
1682
+ console.warn('applyCrop: failed to remove mask', err);
1683
+ }
1684
+ });
1685
+ this.canvas.discardActiveObject();
1686
+ this.canvas.renderAll();
1687
+ }
1688
+ } catch (e) {
1689
+ console.warn('applyCrop: error while removing masks', e);
1690
+ }
1691
+
1692
+ try {
1693
+ if (this._cropRect) {
1694
+ try {
1695
+ if (this._cropHandlers && this._cropHandlers.length) {
1696
+ this._cropHandlers.forEach(h => {
1697
+ h.handlers.forEach(rec => h.target.off(rec.evt, rec.fn));
1698
+ });
1699
+ }
1700
+ } catch (e) { /* ignore */ }
1701
+ try { this.canvas.remove(this._cropRect); } catch (e) { /* ignore */ }
1702
+ this._cropRect = null;
1703
+ }
1704
+ } catch (e) { /* ignore */ }
1705
+
1706
+ // End crop mode
1707
+ this._cropMode = false;
1708
+ this.canvas.selection = !!this._prevSelectionSetting;
1709
+ this._prevSelectionSetting = undefined;
1710
+
1711
+ // Export full canvas and crop on offscreen canvas
1712
+ let croppedBase64;
1713
+ try {
1714
+ const fullDataUrl = this.canvas.toDataURL({
1715
+ format: 'jpeg',
1716
+ quality: this.options.downsampleQuality || 0.92,
1717
+ multiplier: 1
1718
+ });
1719
+
1720
+ croppedBase64 = await new Promise((resolve, reject) => {
1721
+ const img = new Image();
1722
+ img.onload = () => {
1723
+ try {
1724
+ const oc = document.createElement('canvas');
1725
+ oc.width = sw;
1726
+ oc.height = sh;
1727
+ const ctx = oc.getContext('2d');
1728
+ ctx.drawImage(img, sx, sy, sw, sh, 0, 0, sw, sh);
1729
+ const out = oc.toDataURL('image/jpeg', this.options.downsampleQuality || 0.92);
1730
+ resolve(out);
1731
+ } catch (err) {
1732
+ reject(err);
1733
+ }
1734
+ };
1735
+ img.onerror = (e) => reject(e);
1736
+ img.src = fullDataUrl;
1737
+ });
1738
+ } catch (e) {
1739
+ console.error('applyCrop: failed to create cropped image', e);
1740
+ this._updateUI();
1741
+ return;
1742
+ }
1743
+
1744
+ // Load the cropped image as the new base image
1745
+ try {
1746
+ await this.loadImage(croppedBase64);
1747
+ } catch (e) {
1748
+ console.error('applyCrop: loadImage(croppedBase64) failed', e);
1749
+ this._updateUI();
1750
+ return;
1751
+ }
1752
+
1753
+ // Create "after" snapshot (also exclude crop rect if any) and push history command
1754
+ let afterJson = null;
1755
+ try {
1756
+ const jsonObj2 = this.canvas.toJSON(['maskId', 'maskName', 'isCropRect']);
1757
+ if (Array.isArray(jsonObj2.objects)) {
1758
+ jsonObj2.objects = jsonObj2.objects.filter(o => !o.isCropRect);
1759
+ }
1760
+ afterJson = JSON.stringify(jsonObj2);
1761
+ } catch (e) {
1762
+ console.warn('applyCrop: failed to serialize after state', e);
1763
+ afterJson = null;
1764
+ }
1765
+
1766
+ try {
1767
+ const self = this;
1768
+ const cmd = new Command(
1769
+ () => { if (afterJson) self.loadFromState(afterJson); },
1770
+ () => { if (beforeJson) self.loadFromState(beforeJson); }
1771
+ );
1772
+
1773
+ if (!this.historyManager) this.historyManager = new HistoryManager(this.maxHistorySize || 50);
1774
+
1775
+ // trim future redo history
1776
+ if (this.historyManager.currentIndex < this.historyManager.history.length - 1) {
1777
+ this.historyManager.history = this.historyManager.history.slice(0, this.historyManager.currentIndex + 1);
1778
+ }
1779
+
1780
+ this.historyManager.history.push(cmd);
1781
+ if (this.historyManager.history.length > this.historyManager.maxSize) {
1782
+ this.historyManager.history.shift();
1783
+ } else {
1784
+ this.historyManager.currentIndex++;
1785
+ }
1786
+ } catch (e) {
1787
+ console.warn('applyCrop: failed to push history command', e);
1788
+ }
1789
+
1790
+ // Final UI update
1791
+ this._updateUI();
1792
+ this.canvas.renderAll();
1793
+ }
1794
+
1795
+
1796
+ /* ---------- Misc / UI ---------- */
1797
+
1798
+ /**
1799
+ * Updates the scale input field in the UI to reflect the current scale.
1800
+ * Sets the value (as percentage) if the element is present.
1801
+ * @private
1802
+ */
1803
+ _updateInputs() {
1804
+ const scaleEl = document.getElementById(this.elements.scaleRate);
1805
+ if (scaleEl) scaleEl.value = Math.round(this.currentScale * 100);
1806
+ }
1807
+
1808
+ /**
1809
+ * Updates the enabled/disabled state of various UI controls (buttons)
1810
+ * based on the current application state (image/mask presence, animation, etc).
1811
+ * @private
1812
+ */
1813
+ _updateUI() {
1814
+ const hasImg = !!this.originalImage;
1815
+ const masks = hasImg ? this.canvas.getObjects().filter(o => o.maskId) : [];
1816
+ const hasMasks = masks.length > 0;
1817
+ const active = this.canvas.getActiveObject();
1818
+ const hasSelectedMask = active && active.maskId;
1819
+ const isDefault = this.currentScale === 1 && this.currentRotation === 0;
1820
+ const canUndo = this.historyManager?.canUndo();
1821
+ const canRedo = this.historyManager?.canRedo();
1822
+ const inCrop = !!this._cropMode;
1823
+
1824
+ if (inCrop) {
1825
+ // iterate all element keys and disable unless key is applyCropBtn or cancelCropBtn
1826
+ for (const k of Object.keys(this.elements || {})) {
1827
+ const el = document.getElementById(this.elements[k]);
1828
+ if (!el) continue;
1829
+ if (k === 'applyCropBtn' || k === 'cancelCropBtn') {
1830
+ el.disabled = false;
1831
+ } else {
1832
+ el.disabled = true;
1833
+ }
1834
+ }
1835
+ return;
1836
+ }
1837
+
1838
+ this._setDisabled('zoomInBtn', !hasImg || this.isAnimating || this.currentScale >= this.options.maxScale);
1839
+ this._setDisabled('zoomOutBtn', !hasImg || this.isAnimating || this.currentScale <= this.options.minScale);
1840
+ this._setDisabled('rotateLeftBtn', !hasImg || this.isAnimating);
1841
+ this._setDisabled('rotateRightBtn', !hasImg || this.isAnimating);
1842
+ this._setDisabled('addMaskBtn', !hasImg || this.isAnimating);
1843
+ this._setDisabled('removeMaskBtn', !hasSelectedMask || this.isAnimating);
1844
+ this._setDisabled('removeAllMasksBtn', !hasMasks || this.isAnimating);
1845
+ this._setDisabled('mergeBtn', !hasImg || !hasMasks || this.isAnimating);
1846
+ this._setDisabled('downloadBtn', !hasImg || this.isAnimating);
1847
+ this._setDisabled('resetBtn', !hasImg || isDefault || this.isAnimating);
1848
+ this._setDisabled('undoBtn', !hasImg || this.isAnimating || !canUndo);
1849
+ this._setDisabled('redoBtn', !hasImg || this.isAnimating || !canRedo);
1850
+ this._setDisabled('cropBtn', !hasImg || this.isAnimating);
1851
+ this._setDisabled('applyCropBtn', true);
1852
+ this._setDisabled('cancelCropBtn', true);
1853
+ }
1854
+
1855
+ /**
1856
+ * Enables or disables a specific UI element (typically a button) by its key.
1857
+ *
1858
+ * @param {string} key - Key of the element in this.elements (e.g. 'zoomInBtn').
1859
+ * @param {boolean} disabled - If true, disables the element; otherwise enables.
1860
+ * @private
1861
+ */
1862
+ _setDisabled(key, disabled) {
1863
+ const el = document.getElementById(this.elements[key]);
1864
+ if (el) el.disabled = !!disabled;
1865
+ }
1866
+
1867
+ /**
1868
+ * Automatically display and hide placeholders and containers based on the current image content
1869
+ * @private
1870
+ */
1871
+ _updatePlaceholderStatus() {
1872
+ if (!this.options.showPlaceholder) return;
1873
+ this._setPlaceholderVisible(!this.originalImage);
1874
+ }
1875
+
1876
+ /**
1877
+ * Controls the display/hiding of the Placeholder and Canvas container.
1878
+ * @param {boolean} show - true displays the placeholder, false displays the canvas container
1879
+ * @private
1880
+ */
1881
+ _setPlaceholderVisible(show) {
1882
+ if (!this.placeholderEl) return;
1883
+ if (show) {
1884
+ this.placeholderEl.classList.remove('d-none');
1885
+ this.placeholderEl.classList.add('d-flex');
1886
+ this.containerEl.classList.add('d-none');
1887
+ } else {
1888
+ this.placeholderEl.classList.remove('d-flex');
1889
+ this.placeholderEl.classList.add('d-none');
1890
+ this.containerEl.classList.remove('d-none');
1891
+ }
1892
+ }
1893
+
1894
+ /**
1895
+ * Cleans up and disposes of the canvas and related references.
1896
+ * Call this method to free memory and remove canvas listeners when the editor is no longer needed.
1897
+ * @public
1898
+ */
1899
+ dispose() {
1900
+ // Remove bound DOM event listeners
1901
+ try {
1902
+ for (const key in (this._boundHandlers || {})) {
1903
+ const handlers = this._boundHandlers[key] || [];
1904
+ const el = document.getElementById(this.elements[key]);
1905
+ if (!el) continue;
1906
+ handlers.forEach(h => {
1907
+ try { el.removeEventListener(h.event, h.handler); } catch (e) { }
1908
+ });
1909
+ }
1910
+ } catch (e) { }
1911
+
1912
+ if (this._cropRect) {
1913
+ try { this.canvas.remove(this._cropRect); } catch (e) { }
1914
+ this._cropRect = null;
1915
+ }
1916
+
1917
+ if (this.canvas) {
1918
+ try { this.canvas.dispose(); } catch (e) { }
1919
+ this.canvas = null;
1920
+ this.canvasEl = null;
1921
+ this.isImageLoadedToCanvas = false;
1922
+ }
1923
+ this._boundHandlers = {};
1924
+ }
1925
+ }
1926
+
1927
+ /**
1928
+ * A simple FIFO queue that guarantees animations are executed sequentially.
1929
+ * @class AnimationQueue
1930
+ */
1931
+ class AnimationQueue {
1932
+ /**
1933
+ * Creates a new AnimationQueue.
1934
+ *
1935
+ * @constructor
1936
+ */
1937
+ constructor() {
1938
+ /**
1939
+ * Internal queue holding animation descriptors.
1940
+ * @type {Array<{fn: Function, resolve: Function, reject: Function}>}
1941
+ */
1942
+ this.queue = [];
1943
+ /**
1944
+ * Flag indicating whether an animation is currently running.
1945
+ * @type {boolean}
1946
+ */
1947
+ this.running = false;
1948
+ }
1949
+
1950
+ /**
1951
+ * Adds an animation function to the queue.
1952
+ *
1953
+ * @param {Function} animationFn A function that returns a Promise or any await-able.
1954
+ * @returns {Promise<*>} A Promise that resolves/rejects with the animation result.
1955
+ */
1956
+ async add(animationFn) {
1957
+ return new Promise((resolve, reject) => {
1958
+ // Push the animation into the queue.
1959
+ this.queue.push({ fn: animationFn, resolve, reject });
1960
+ // Start processing if it's not already running.
1961
+ if (!this.running) {
1962
+ this.processQueue();
1963
+ }
1964
+ });
1965
+ }
1966
+
1967
+ /**
1968
+ * Internal helper that processes the animation queue sequentially until it is empty.
1969
+ *
1970
+ * @private
1971
+ * @returns {Promise<void>}
1972
+ */
1973
+ async processQueue() {
1974
+ if (this.queue.length === 0) {
1975
+ this.running = false;
1976
+ return;
1977
+ }
1978
+
1979
+ this.running = true;
1980
+ const { fn, resolve, reject } = this.queue.shift();
1981
+
1982
+ try {
1983
+ const result = await fn();
1984
+ resolve(result);
1985
+ } catch (error) {
1986
+ reject(error);
1987
+ }
1988
+
1989
+ this.processQueue();
1990
+ }
1991
+ }
1992
+
1993
+ /**
1994
+ * Command object encapsulating an executable action and its corresponding undo operation.
1995
+ * @class Command
1996
+ */
1997
+ class Command {
1998
+ /**
1999
+ * @param {Function} execute The function that performs the action.
2000
+ * @param {Function} undo The function that reverts the action.
2001
+ */
2002
+ constructor(execute, undo) {
2003
+ /**
2004
+ * Executes the command.
2005
+ * @type {Function}
2006
+ */
2007
+ this.execute = execute;
2008
+ /**
2009
+ * Undoes the command.
2010
+ * @type {Function}
2011
+ */
2012
+ this.undo = undo;
2013
+ }
2014
+ }
2015
+
2016
+ /**
2017
+ * Manages a history of Command objects enabling undo/redo functionality.
2018
+ * @class HistoryManager
2019
+ */
2020
+ class HistoryManager {
2021
+ /**
2022
+ * @param {number} [maxSize=50] Maximum number of commands to keep in history.
2023
+ */
2024
+ constructor(maxSize = 50) {
2025
+ this.history = [];
2026
+ this.currentIndex = -1;
2027
+ this.maxSize = maxSize;
2028
+ }
2029
+
2030
+ /**
2031
+ * Executes a new command and pushes it onto the history stack.
2032
+ * Truncates any "future" history when branching.
2033
+ *
2034
+ * @param {Command} command The command to execute.
2035
+ * @returns {void}
2036
+ */
2037
+ execute(command) {
2038
+ // Perform the command.
2039
+ command.execute();
2040
+
2041
+ // Remove any commands that are ahead of the current index.
2042
+ if (this.currentIndex < this.history.length - 1) {
2043
+ this.history = this.history.slice(0, this.currentIndex + 1);
2044
+ }
2045
+
2046
+ // Add the new command.
2047
+ this.history.push(command);
2048
+
2049
+ // Maintain the max size of the buffer.
2050
+ if (this.history.length > this.maxSize) {
2051
+ this.history.shift(); // Remove the oldest command.
2052
+ } else {
2053
+ this.currentIndex++;
2054
+ }
2055
+ }
2056
+
2057
+ /**
2058
+ * Checks whether an undo operation is possible.
2059
+ *
2060
+ * @returns {boolean} True if undo can be performed.
2061
+ */
2062
+ canUndo() {
2063
+ return this.currentIndex >= 0;
2064
+ }
2065
+
2066
+ /**
2067
+ * Checks whether a redo operation is possible.
2068
+ *
2069
+ * @returns {boolean} True if redo can be performed.
2070
+ */
2071
+ canRedo() {
2072
+ return this.currentIndex < this.history.length - 1;
2073
+ }
2074
+
2075
+ /**
2076
+ * Undoes the last executed command if possible.
2077
+ *
2078
+ * @returns {void}
2079
+ */
2080
+ undo() {
2081
+ if (this.currentIndex >= 0) {
2082
+ this.history[this.currentIndex].undo();
2083
+ this.currentIndex--;
2084
+ }
2085
+ }
2086
+
2087
+ /**
2088
+ * Redoes the next command in history if possible.
2089
+ *
2090
+ * @returns {void}
2091
+ */
2092
+ redo() {
2093
+ if (this.currentIndex < this.history.length - 1) {
2094
+ this.currentIndex++;
2095
+ this.history[this.currentIndex].execute();
2096
+ }
2097
+ }
2098
+ }
2099
+
2100
+ return ImageEditor
2101
+ })