@bensitu/image-editor 1.5.2 → 2.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.
Files changed (166) hide show
  1. package/README.md +460 -509
  2. package/dist/cjs/index.cjs +6892 -0
  3. package/dist/cjs/index.cjs.map +1 -0
  4. package/dist/esm/animation/animation-queue.js +74 -0
  5. package/dist/esm/animation/animation-queue.js.map +1 -0
  6. package/dist/esm/core/callback-reporter.js +23 -0
  7. package/dist/esm/core/callback-reporter.js.map +1 -0
  8. package/dist/esm/core/default-options.js +529 -0
  9. package/dist/esm/core/default-options.js.map +1 -0
  10. package/dist/esm/core/errors.js +156 -0
  11. package/dist/esm/core/errors.js.map +1 -0
  12. package/dist/esm/core/operation-guard.js +157 -0
  13. package/dist/esm/core/operation-guard.js.map +1 -0
  14. package/dist/esm/core/public-types.js +4 -0
  15. package/dist/esm/core/public-types.js.map +1 -0
  16. package/dist/esm/core/state-serializer.js +252 -0
  17. package/dist/esm/core/state-serializer.js.map +1 -0
  18. package/dist/esm/crop/crop-controller.js +405 -0
  19. package/dist/esm/crop/crop-controller.js.map +1 -0
  20. package/dist/esm/export/export-format.js +53 -0
  21. package/dist/esm/export/export-format.js.map +1 -0
  22. package/dist/esm/export/export-service.js +607 -0
  23. package/dist/esm/export/export-service.js.map +1 -0
  24. package/dist/esm/fabric/fabric-adapter.js +37 -0
  25. package/dist/esm/fabric/fabric-adapter.js.map +1 -0
  26. package/dist/esm/fabric/fabric-animation.js +89 -0
  27. package/dist/esm/fabric/fabric-animation.js.map +1 -0
  28. package/dist/esm/history/command.js +2 -0
  29. package/dist/esm/history/command.js.map +1 -0
  30. package/dist/esm/history/history-manager.js +103 -0
  31. package/dist/esm/history/history-manager.js.map +1 -0
  32. package/dist/esm/image/image-loader.js +238 -0
  33. package/dist/esm/image/image-loader.js.map +1 -0
  34. package/dist/esm/image/image-resampler.js +60 -0
  35. package/dist/esm/image/image-resampler.js.map +1 -0
  36. package/dist/esm/image/layout-manager.js +206 -0
  37. package/dist/esm/image/layout-manager.js.map +1 -0
  38. package/dist/esm/image/transform-controller.js +132 -0
  39. package/dist/esm/image/transform-controller.js.map +1 -0
  40. package/dist/esm/image-editor.js +2076 -0
  41. package/dist/esm/image-editor.js.map +1 -0
  42. package/dist/esm/index.js +5 -0
  43. package/dist/esm/index.js.map +1 -0
  44. package/dist/esm/mask/mask-factory.js +356 -0
  45. package/dist/esm/mask/mask-factory.js.map +1 -0
  46. package/dist/esm/mask/mask-label-manager.js +120 -0
  47. package/dist/esm/mask/mask-label-manager.js.map +1 -0
  48. package/dist/esm/mask/mask-list.js +53 -0
  49. package/dist/esm/mask/mask-list.js.map +1 -0
  50. package/dist/esm/mask/mask-style.js +182 -0
  51. package/dist/esm/mask/mask-style.js.map +1 -0
  52. package/dist/esm/mosaic/mosaic-controller.js +670 -0
  53. package/dist/esm/mosaic/mosaic-controller.js.map +1 -0
  54. package/dist/esm/mosaic/mosaic-geometry.js +81 -0
  55. package/dist/esm/mosaic/mosaic-geometry.js.map +1 -0
  56. package/dist/esm/mosaic/mosaic-pixelate.js +71 -0
  57. package/dist/esm/mosaic/mosaic-pixelate.js.map +1 -0
  58. package/dist/esm/ui/dom-bindings.js +67 -0
  59. package/dist/esm/ui/dom-bindings.js.map +1 -0
  60. package/dist/esm/ui/ui-state.js +25 -0
  61. package/dist/esm/ui/ui-state.js.map +1 -0
  62. package/dist/esm/ui/visibility-state.js +11 -0
  63. package/dist/esm/ui/visibility-state.js.map +1 -0
  64. package/dist/esm/utils/canvas-region.js +100 -0
  65. package/dist/esm/utils/canvas-region.js.map +1 -0
  66. package/dist/esm/utils/dom.js +6 -0
  67. package/dist/esm/utils/dom.js.map +1 -0
  68. package/dist/esm/utils/file.js +53 -0
  69. package/dist/esm/utils/file.js.map +1 -0
  70. package/dist/esm/utils/number.js +24 -0
  71. package/dist/esm/utils/number.js.map +1 -0
  72. package/dist/esm/utils/timeout.js +17 -0
  73. package/dist/esm/utils/timeout.js.map +1 -0
  74. package/dist/types/animation/animation-queue.d.ts +111 -0
  75. package/dist/types/animation/animation-queue.d.ts.map +1 -0
  76. package/dist/types/core/callback-reporter.d.ts +125 -0
  77. package/dist/types/core/callback-reporter.d.ts.map +1 -0
  78. package/dist/types/core/default-options.d.ts +84 -0
  79. package/dist/types/core/default-options.d.ts.map +1 -0
  80. package/dist/types/core/errors.d.ts +142 -0
  81. package/dist/types/core/errors.d.ts.map +1 -0
  82. package/dist/types/core/operation-guard.d.ts +194 -0
  83. package/dist/types/core/operation-guard.d.ts.map +1 -0
  84. package/dist/types/core/public-types.d.ts +788 -0
  85. package/dist/types/core/public-types.d.ts.map +1 -0
  86. package/dist/types/core/state-serializer.d.ts +303 -0
  87. package/dist/types/core/state-serializer.d.ts.map +1 -0
  88. package/dist/types/crop/crop-controller.d.ts +407 -0
  89. package/dist/types/crop/crop-controller.d.ts.map +1 -0
  90. package/dist/types/export/export-format.d.ts +136 -0
  91. package/dist/types/export/export-format.d.ts.map +1 -0
  92. package/dist/types/export/export-service.d.ts +333 -0
  93. package/dist/types/export/export-service.d.ts.map +1 -0
  94. package/dist/types/fabric/fabric-adapter.d.ts +74 -0
  95. package/dist/types/fabric/fabric-adapter.d.ts.map +1 -0
  96. package/dist/types/fabric/fabric-animation.d.ts +141 -0
  97. package/dist/types/fabric/fabric-animation.d.ts.map +1 -0
  98. package/dist/types/history/command.d.ts +16 -0
  99. package/dist/types/history/command.d.ts.map +1 -0
  100. package/dist/types/history/history-manager.d.ts +129 -0
  101. package/dist/types/history/history-manager.d.ts.map +1 -0
  102. package/dist/types/image/image-loader.d.ts +263 -0
  103. package/dist/types/image/image-loader.d.ts.map +1 -0
  104. package/dist/types/image/image-resampler.d.ts +139 -0
  105. package/dist/types/image/image-resampler.d.ts.map +1 -0
  106. package/dist/types/image/layout-manager.d.ts +211 -0
  107. package/dist/types/image/layout-manager.d.ts.map +1 -0
  108. package/dist/types/image/transform-controller.d.ts +286 -0
  109. package/dist/types/image/transform-controller.d.ts.map +1 -0
  110. package/dist/types/image-editor.d.ts +661 -0
  111. package/dist/types/image-editor.d.ts.map +1 -0
  112. package/dist/types/index.d.cts +31 -0
  113. package/dist/types/index.d.cts.map +1 -0
  114. package/dist/types/index.d.ts +31 -0
  115. package/dist/types/index.d.ts.map +1 -0
  116. package/dist/types/mask/mask-factory.d.ts +212 -0
  117. package/dist/types/mask/mask-factory.d.ts.map +1 -0
  118. package/dist/types/mask/mask-label-manager.d.ts +171 -0
  119. package/dist/types/mask/mask-label-manager.d.ts.map +1 -0
  120. package/dist/types/mask/mask-list.d.ts +144 -0
  121. package/dist/types/mask/mask-list.d.ts.map +1 -0
  122. package/dist/types/mask/mask-style.d.ts +338 -0
  123. package/dist/types/mask/mask-style.d.ts.map +1 -0
  124. package/dist/types/mosaic/mosaic-controller.d.ts +82 -0
  125. package/dist/types/mosaic/mosaic-controller.d.ts.map +1 -0
  126. package/dist/types/mosaic/mosaic-geometry.d.ts +29 -0
  127. package/dist/types/mosaic/mosaic-geometry.d.ts.map +1 -0
  128. package/dist/types/mosaic/mosaic-pixelate.d.ts +23 -0
  129. package/dist/types/mosaic/mosaic-pixelate.d.ts.map +1 -0
  130. package/dist/types/ui/dom-bindings.d.ts +105 -0
  131. package/dist/types/ui/dom-bindings.d.ts.map +1 -0
  132. package/dist/types/ui/ui-state.d.ts +112 -0
  133. package/dist/types/ui/ui-state.d.ts.map +1 -0
  134. package/dist/types/ui/visibility-state.d.ts +77 -0
  135. package/dist/types/ui/visibility-state.d.ts.map +1 -0
  136. package/dist/types/utils/canvas-region.d.ts +177 -0
  137. package/dist/types/utils/canvas-region.d.ts.map +1 -0
  138. package/dist/types/utils/dom.d.ts +26 -0
  139. package/dist/types/utils/dom.d.ts.map +1 -0
  140. package/dist/types/utils/file.d.ts +80 -0
  141. package/dist/types/utils/file.d.ts.map +1 -0
  142. package/dist/types/utils/number.d.ts +131 -0
  143. package/dist/types/utils/number.d.ts.map +1 -0
  144. package/dist/types/utils/timeout.d.ts +84 -0
  145. package/dist/types/utils/timeout.d.ts.map +1 -0
  146. package/dist/umd/image-editor.umd.js +2 -0
  147. package/dist/umd/image-editor.umd.js.map +1 -0
  148. package/package.json +72 -66
  149. package/dist/image-editor.cjs +0 -4407
  150. package/dist/image-editor.cjs.map +0 -7
  151. package/dist/image-editor.esm.js +0 -4376
  152. package/dist/image-editor.esm.js.map +0 -7
  153. package/dist/image-editor.esm.min.js +0 -9
  154. package/dist/image-editor.esm.min.js.map +0 -7
  155. package/dist/image-editor.esm.min.mjs +0 -9
  156. package/dist/image-editor.esm.min.mjs.map +0 -7
  157. package/dist/image-editor.esm.mjs +0 -4376
  158. package/dist/image-editor.esm.mjs.map +0 -7
  159. package/dist/image-editor.js +0 -4373
  160. package/dist/image-editor.js.map +0 -7
  161. package/dist/image-editor.min.js +0 -9
  162. package/dist/image-editor.min.js.map +0 -7
  163. package/image-editor.d.ts +0 -271
  164. package/src/browser.js +0 -11
  165. package/src/esm.js +0 -9
  166. package/src/image-editor.js +0 -5013
@@ -1,4407 +0,0 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, { get: all[name], enumerable: true });
10
- };
11
- var __copyProps = (to, from, except, desc) => {
12
- if (from && typeof from === "object" || typeof from === "function") {
13
- for (let key of __getOwnPropNames(from))
14
- if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
- }
17
- return to;
18
- };
19
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
- // If the importer is in node compatibility mode or this is not an ESM
21
- // file that has been converted to a CommonJS file using a Babel-
22
- // compatible transform (i.e. "__esModule" has not been set), then set
23
- // "default" to the CommonJS "module.exports" for node compatibility.
24
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
- mod
26
- ));
27
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
-
29
- // src/esm.js
30
- var esm_exports = {};
31
- __export(esm_exports, {
32
- ImageEditor: () => image_editor_default,
33
- default: () => esm_default
34
- });
35
- module.exports = __toCommonJS(esm_exports);
36
- var import_fabric = __toESM(require("fabric"));
37
-
38
- // src/image-editor.js
39
- /**
40
- * @file image-editor.js
41
- * @module image-editor
42
- * @version 1.5.2
43
- * @author Ben Situ
44
- * @license MIT
45
- * @description Lightweight canvas-based image editor with masking/transform/export support.
46
- */
47
- var fabric = null;
48
- var INTERNAL_OPERATION_TOKEN = /* @__PURE__ */ Symbol.for("ImageEditorInternalOperation");
49
- function getGlobalScope() {
50
- if (typeof globalThis !== "undefined") return globalThis;
51
- if (typeof self !== "undefined") return self;
52
- if (typeof window !== "undefined") return window;
53
- return null;
54
- }
55
- function getGlobalFabric() {
56
- const scope = getGlobalScope();
57
- return scope && scope.fabric ? scope.fabric : null;
58
- }
59
- function setFabric(fabricInstance2) {
60
- fabric = fabricInstance2 || getGlobalFabric();
61
- return fabric;
62
- }
63
- function ensureFabric() {
64
- if (!fabric) setFabric();
65
- return fabric;
66
- }
67
- var ImageEditor = class {
68
- constructor(options = {}) {
69
- const defaultLabel = {
70
- getText: (mask) => mask.maskName,
71
- textOptions: {
72
- fontSize: 12,
73
- fill: "#fff",
74
- backgroundColor: "rgba(0,0,0,0.7)",
75
- padding: 2,
76
- fontFamily: "monospace",
77
- fontWeight: "bold",
78
- selectable: false,
79
- evented: false,
80
- originX: "left",
81
- originY: "top"
82
- }
83
- };
84
- const defaultCrop = {
85
- minWidth: 100,
86
- minHeight: 100,
87
- padding: 10,
88
- hideMasksDuringCrop: true,
89
- preserveMasksAfterCrop: false,
90
- allowRotationOfCropRect: false
91
- };
92
- const userLabel = options.label || {};
93
- const userCrop = options.crop || {};
94
- this.options = {
95
- canvasWidth: 800,
96
- canvasHeight: 600,
97
- backgroundColor: "transparent",
98
- animationDuration: 300,
99
- minScale: 0.1,
100
- maxScale: 5,
101
- scaleStep: 0.05,
102
- rotationStep: 90,
103
- expandCanvasToImage: true,
104
- fitImageToCanvas: false,
105
- coverImageToCanvas: false,
106
- downsampleOnLoad: true,
107
- downsampleMaxWidth: 4e3,
108
- downsampleMaxHeight: 3e3,
109
- downsampleQuality: 0.92,
110
- preserveSourceFormat: true,
111
- downsampleMimeType: null,
112
- imageLoadTimeoutMs: 3e4,
113
- exportMultiplier: 1,
114
- maxExportPixels: 5e7,
115
- maxHistorySize: 50,
116
- exportImageAreaByDefault: true,
117
- defaultMaskWidth: 50,
118
- defaultMaskHeight: 80,
119
- maskRotatable: false,
120
- maskLabelOnSelect: true,
121
- maskLabelOffset: 3,
122
- maskName: "mask",
123
- groupSelection: false,
124
- showPlaceholder: true,
125
- initialImageBase64: null,
126
- // Provide a base64 'data:image/...' string here if you want auto-load
127
- defaultDownloadFileName: "edited_image.jpg",
128
- onError: null,
129
- onWarning: null,
130
- ...options,
131
- label: {
132
- ...defaultLabel,
133
- ...userLabel,
134
- textOptions: {
135
- ...defaultLabel.textOptions,
136
- ...userLabel.textOptions || {}
137
- }
138
- },
139
- crop: {
140
- ...defaultCrop,
141
- ...userCrop
142
- }
143
- };
144
- this._normalizeOptions();
145
- this._fabricLoaded = !!ensureFabric();
146
- if (!this._fabricLoaded) {
147
- this._reportError("fabric.js is not loaded. Please include fabric.js first. Initialization will be aborted.");
148
- }
149
- this.canvas = null;
150
- this.canvasElement = null;
151
- this.containerElement = null;
152
- this.placeholderElement = null;
153
- this.originalImage = null;
154
- this.baseImageScale = 1;
155
- this.currentScale = 1;
156
- this.currentRotation = 0;
157
- this.maskCounter = 0;
158
- this.isAnimating = false;
159
- this._isLoading = false;
160
- this._activeOperationName = null;
161
- this._activeOperationToken = null;
162
- this.elements = {};
163
- this.isImageLoadedToCanvas = false;
164
- this.maxHistorySize = this.options.maxHistorySize;
165
- this._handlersByElementKey = {};
166
- this._elementCache = {};
167
- this._elementOriginalPointerEvents = /* @__PURE__ */ new Map();
168
- this._elementOriginalDisabledState = /* @__PURE__ */ new Map();
169
- this._lastMask = null;
170
- this._lastMaskInitialLeft = null;
171
- this._lastMaskInitialTop = null;
172
- this._lastMaskInitialWidth = null;
173
- this._lastSnapshot = null;
174
- this._cropMode = false;
175
- this._isApplyingCrop = false;
176
- this._cropRect = null;
177
- this._cropHandlers = [];
178
- this._cropPrevEvented = null;
179
- this._prevSelectionSetting = void 0;
180
- this._containerOriginalOverflow = null;
181
- this._lastContainerViewportSize = null;
182
- this._canvasElementOriginalStyle = null;
183
- this._visibilityStateByElement = /* @__PURE__ */ new WeakMap();
184
- this._scrollbarSizeCache = null;
185
- this._activeAnimationRejectors = /* @__PURE__ */ new Set();
186
- this._disposed = false;
187
- this._initialized = false;
188
- this._deprecatedElementKeyWarnings = /* @__PURE__ */ new Set();
189
- this._cropRotationWarningEmitted = false;
190
- this.onImageLoaded = typeof this.options.onImageLoaded === "function" ? this.options.onImageLoaded : null;
191
- this.animationQueue = new AnimationQueue();
192
- this.historyManager = new HistoryManager(this.maxHistorySize);
193
- }
194
- /**
195
- * Backward-compatible alias for {@link ImageEditor#canvasElement}.
196
- *
197
- * @deprecated Use canvasElement instead. This alias will be removed in v2.0.0.
198
- * @returns {HTMLCanvasElement|null} The canvas element currently owned by the editor.
199
- */
200
- get canvasEl() {
201
- return this.canvasElement;
202
- }
203
- set canvasEl(value) {
204
- this.canvasElement = value;
205
- }
206
- /**
207
- * Backward-compatible alias for {@link ImageEditor#containerElement}.
208
- *
209
- * @deprecated Use containerElement instead. This alias will be removed in v2.0.0.
210
- * @returns {HTMLElement|null} The canvas viewport/container element.
211
- */
212
- get containerEl() {
213
- return this.containerElement;
214
- }
215
- set containerEl(value) {
216
- this.containerElement = value;
217
- }
218
- /**
219
- * Backward-compatible alias for {@link ImageEditor#placeholderElement}.
220
- *
221
- * @deprecated Use placeholderElement instead. This alias will be removed in v2.0.0.
222
- * @returns {HTMLElement|null} The placeholder element shown before an image loads.
223
- */
224
- get placeholderEl() {
225
- return this.placeholderElement;
226
- }
227
- set placeholderEl(value) {
228
- this.placeholderElement = value;
229
- }
230
- /**
231
- * Initializes the editor, binds to DOM elements, sets up event handlers,
232
- * and (optionally) loads an initial image.
233
- * Use this method to set up the editor UI before interacting with it.
234
- *
235
- * @param {Object} [idMap={}] - Optional mapping from logical element names to actual DOM element IDs.
236
- * Supported keys include: canvas, canvasContainer, imagePlaceholder, scalePercentageInput,
237
- * rotateLeftDegreesInput, rotateRightDegreesInput, rotateLeftButton, rotateRightButton,
238
- * createMaskButton, removeSelectedMaskButton, removeAllMasksButton, mergeMasksButton,
239
- * downloadImageButton, maskList, zoomInButton, zoomOutButton, resetImageTransformButton,
240
- * undoButton, redoButton, imageInput, uploadArea, enterCropModeButton, applyCropButton,
241
- * and cancelCropButton. Deprecated 1.x names remain supported as aliases.
242
- *
243
- * @returns {void}
244
- *
245
- * @public
246
- *
247
- * @example
248
- * editor.init({
249
- * canvas: 'myFabricCanvasId',
250
- * downloadImageButton: 'myDownloadButtonId'
251
- * });
252
- */
253
- init(idMap = {}) {
254
- if (!this._fabricLoaded) {
255
- this._fabricLoaded = !!ensureFabric();
256
- if (!this._fabricLoaded) {
257
- this._reportError("fabric.js is not loaded. Please include fabric.js first. Initialization will be aborted.");
258
- return;
259
- }
260
- }
261
- if (this._initialized || this.canvas) this.dispose();
262
- this._disposed = false;
263
- this._initialized = true;
264
- this.animationQueue = new AnimationQueue();
265
- this.historyManager = new HistoryManager(this.maxHistorySize);
266
- this._visibilityStateByElement = /* @__PURE__ */ new WeakMap();
267
- this._activeAnimationRejectors = /* @__PURE__ */ new Set();
268
- this._isLoading = false;
269
- this._activeOperationName = null;
270
- this._activeOperationToken = null;
271
- this._elementOriginalPointerEvents = /* @__PURE__ */ new Map();
272
- this._elementOriginalDisabledState = /* @__PURE__ */ new Map();
273
- this._isApplyingCrop = false;
274
- this._containerOriginalOverflow = null;
275
- this._lastContainerViewportSize = null;
276
- this._canvasElementOriginalStyle = null;
277
- const defaults = {
278
- canvas: "fabricCanvas",
279
- canvasContainer: null,
280
- // Pass an ID here if you have a scrollable viewport container
281
- imagePlaceholder: "imagePlaceholder",
282
- imgPlaceholder: null,
283
- scalePercentageInput: "scalePercentageInput",
284
- scaleRate: null,
285
- rotateLeftDegreesInput: "rotateLeftDegreesInput",
286
- rotationLeftInput: null,
287
- rotateRightDegreesInput: "rotateRightDegreesInput",
288
- rotationRightInput: null,
289
- rotateLeftButton: "rotateLeftButton",
290
- rotateLeftBtn: null,
291
- rotateRightButton: "rotateRightButton",
292
- rotateRightBtn: null,
293
- createMaskButton: "createMaskButton",
294
- addMaskBtn: null,
295
- removeSelectedMaskButton: "removeSelectedMaskButton",
296
- removeMaskBtn: null,
297
- removeAllMasksButton: "removeAllMasksButton",
298
- removeAllMasksBtn: null,
299
- mergeMasksButton: "mergeMasksButton",
300
- mergeBtn: null,
301
- downloadImageButton: "downloadImageButton",
302
- downloadBtn: null,
303
- maskList: "maskList",
304
- zoomInButton: "zoomInButton",
305
- zoomInBtn: null,
306
- zoomOutButton: "zoomOutButton",
307
- zoomOutBtn: null,
308
- resetImageTransformButton: "resetImageTransformButton",
309
- resetBtn: null,
310
- undoButton: "undoButton",
311
- undoBtn: null,
312
- redoButton: "redoButton",
313
- redoBtn: null,
314
- imageInput: "imageInput",
315
- uploadArea: null,
316
- enterCropModeButton: "enterCropModeButton",
317
- cropBtn: null,
318
- applyCropButton: "applyCropButton",
319
- applyCropBtn: null,
320
- cancelCropButton: "cancelCropButton",
321
- cancelCropBtn: null
322
- };
323
- this.elements = this._resolveElementIdMap(idMap || {}, defaults);
324
- this._elementCache = {};
325
- this._initCanvas();
326
- this._bindEvents();
327
- this._updateInputs();
328
- this._updateMaskList();
329
- this._updateUI();
330
- if (this.options.initialImageBase64) {
331
- this.loadImage(this.options.initialImageBase64).catch((error) => this._reportError("initialImageBase64 could not be loaded", error));
332
- } else {
333
- this._updatePlaceholderStatus();
334
- }
335
- }
336
- _resolveElementIdMap(idMap, defaults) {
337
- const resolved = { ...defaults, ...idMap };
338
- this._resolveElementAliases(resolved, idMap, defaults, "imagePlaceholder", ["imgPlaceholder"]);
339
- this._resolveElementAliases(resolved, idMap, defaults, "scalePercentageInput", ["scaleRate"]);
340
- this._resolveElementAliases(resolved, idMap, defaults, "rotateLeftDegreesInput", ["rotationLeftInput"]);
341
- this._resolveElementAliases(resolved, idMap, defaults, "rotateRightDegreesInput", ["rotationRightInput"]);
342
- this._resolveElementAlias(resolved, idMap, defaults, "rotateLeftButton", "rotateLeftBtn");
343
- this._resolveElementAlias(resolved, idMap, defaults, "rotateRightButton", "rotateRightBtn");
344
- this._resolveElementAlias(resolved, idMap, defaults, "createMaskButton", "addMaskBtn");
345
- this._resolveElementAliases(resolved, idMap, defaults, "removeSelectedMaskButton", ["removeMaskBtn"]);
346
- this._resolveElementAlias(resolved, idMap, defaults, "removeAllMasksButton", "removeAllMasksBtn");
347
- this._resolveElementAlias(resolved, idMap, defaults, "mergeMasksButton", "mergeBtn");
348
- this._resolveElementAliases(resolved, idMap, defaults, "downloadImageButton", ["downloadBtn"]);
349
- this._resolveElementAlias(resolved, idMap, defaults, "zoomInButton", "zoomInBtn");
350
- this._resolveElementAlias(resolved, idMap, defaults, "zoomOutButton", "zoomOutBtn");
351
- this._resolveElementAlias(resolved, idMap, defaults, "resetImageTransformButton", "resetBtn");
352
- this._resolveElementAlias(resolved, idMap, defaults, "undoButton", "undoBtn");
353
- this._resolveElementAlias(resolved, idMap, defaults, "redoButton", "redoBtn");
354
- this._resolveElementAliases(resolved, idMap, defaults, "enterCropModeButton", ["cropBtn"]);
355
- this._resolveElementAlias(resolved, idMap, defaults, "applyCropButton", "applyCropBtn");
356
- this._resolveElementAlias(resolved, idMap, defaults, "cancelCropButton", "cancelCropBtn");
357
- return resolved;
358
- }
359
- _resolveElementAlias(resolved, idMap, defaults, canonicalKey, deprecatedKey) {
360
- this._resolveElementAliases(resolved, idMap, defaults, canonicalKey, [deprecatedKey]);
361
- }
362
- _resolveElementAliases(resolved, idMap, defaults, canonicalKey, deprecatedKeys) {
363
- const hasCanonicalKey = Object.prototype.hasOwnProperty.call(idMap, canonicalKey);
364
- if (hasCanonicalKey) {
365
- resolved[canonicalKey] = idMap[canonicalKey];
366
- return;
367
- }
368
- let deprecatedValue;
369
- let hasDeprecatedValue = false;
370
- for (const deprecatedKey of deprecatedKeys) {
371
- if (Object.prototype.hasOwnProperty.call(idMap, deprecatedKey)) {
372
- if (!hasDeprecatedValue) {
373
- deprecatedValue = idMap[deprecatedKey];
374
- hasDeprecatedValue = true;
375
- }
376
- this._warnDeprecatedElementIdKey(deprecatedKey, canonicalKey);
377
- }
378
- }
379
- if (hasDeprecatedValue) {
380
- resolved[canonicalKey] = deprecatedValue;
381
- return;
382
- }
383
- resolved[canonicalKey] = defaults[canonicalKey];
384
- }
385
- _warnDeprecatedElementIdKey(deprecatedKey, canonicalKey) {
386
- if (!this._deprecatedElementKeyWarnings) this._deprecatedElementKeyWarnings = /* @__PURE__ */ new Set();
387
- if (this._deprecatedElementKeyWarnings.has(deprecatedKey)) return;
388
- this._deprecatedElementKeyWarnings.add(deprecatedKey);
389
- this._reportWarning(
390
- `ElementIdMap.${deprecatedKey} is deprecated. Use ${canonicalKey} instead. This alias will be removed in v2.0.0.`
391
- );
392
- }
393
- _normalizeFiniteNumber(value, fallback) {
394
- const numericValue = Number(value);
395
- return Number.isFinite(numericValue) ? numericValue : fallback;
396
- }
397
- _normalizePositiveNumber(value, fallback) {
398
- const numericValue = this._normalizeFiniteNumber(value, fallback);
399
- return numericValue > 0 ? numericValue : fallback;
400
- }
401
- _normalizeNonNegativeNumber(value, fallback) {
402
- const numericValue = this._normalizeFiniteNumber(value, fallback);
403
- return numericValue >= 0 ? numericValue : fallback;
404
- }
405
- _normalizePositiveInteger(value, fallback) {
406
- const numericValue = this._normalizePositiveNumber(value, fallback);
407
- return Math.max(1, Math.floor(numericValue));
408
- }
409
- _normalizeOptions() {
410
- const options = this.options || {};
411
- options.canvasWidth = this._normalizePositiveNumber(options.canvasWidth, 800);
412
- options.canvasHeight = this._normalizePositiveNumber(options.canvasHeight, 600);
413
- options.animationDuration = this._normalizeNonNegativeNumber(options.animationDuration, 300);
414
- const minScale = this._normalizePositiveNumber(options.minScale, 0.1);
415
- const maxScale = this._normalizePositiveNumber(options.maxScale, 5);
416
- if (minScale > maxScale) {
417
- options.minScale = 0.1;
418
- options.maxScale = 5;
419
- } else {
420
- options.minScale = minScale;
421
- options.maxScale = maxScale;
422
- }
423
- options.scaleStep = this._normalizePositiveNumber(options.scaleStep, 0.05);
424
- options.rotationStep = this._normalizeFiniteNumber(options.rotationStep, 90);
425
- options.downsampleMaxWidth = this._normalizePositiveNumber(options.downsampleMaxWidth, 4e3);
426
- options.downsampleMaxHeight = this._normalizePositiveNumber(options.downsampleMaxHeight, 3e3);
427
- options.downsampleQuality = options.downsampleQuality == null ? 0.92 : Math.max(0, Math.min(1, this._normalizeFiniteNumber(options.downsampleQuality, 0.92)));
428
- options.imageLoadTimeoutMs = this._normalizePositiveNumber(options.imageLoadTimeoutMs, 3e4);
429
- options.exportMultiplier = this._normalizePositiveNumber(options.exportMultiplier, 1);
430
- options.maxExportPixels = this._normalizePositiveInteger(options.maxExportPixels, 5e7);
431
- options.maxHistorySize = this._normalizePositiveInteger(options.maxHistorySize, 50);
432
- options.defaultMaskWidth = this._normalizePositiveNumber(options.defaultMaskWidth, 50);
433
- options.defaultMaskHeight = this._normalizePositiveNumber(options.defaultMaskHeight, 80);
434
- options.maskLabelOffset = this._normalizeNonNegativeNumber(options.maskLabelOffset, 3);
435
- if (options.crop) {
436
- options.crop.minWidth = this._normalizePositiveNumber(options.crop.minWidth, 100);
437
- options.crop.minHeight = this._normalizePositiveNumber(options.crop.minHeight, 100);
438
- options.crop.padding = this._normalizeNonNegativeNumber(options.crop.padding, 10);
439
- }
440
- }
441
- _reportError(message, error = null) {
442
- const handler = this.options && this.options.onError;
443
- if (typeof handler !== "function") return;
444
- try {
445
- handler(error, message);
446
- } catch {
447
- }
448
- }
449
- _reportWarning(message, error = null) {
450
- const handler = this.options && this.options.onWarning;
451
- if (typeof handler !== "function") return;
452
- try {
453
- handler(error, message);
454
- } catch {
455
- }
456
- }
457
- _emitSafeCallback(callback, message) {
458
- if (typeof callback !== "function") return;
459
- try {
460
- callback();
461
- } catch (error) {
462
- this._reportWarning(message, error);
463
- }
464
- }
465
- _notifyImageLoaded() {
466
- const optionsCallback = this.options && this.options.onImageLoaded;
467
- const callback = typeof optionsCallback === "function" ? optionsCallback : this.onImageLoaded;
468
- this._emitSafeCallback(callback, "onImageLoaded callback failed");
469
- }
470
- /**
471
- * Initializes the Fabric canvas, viewport elements, and selection event handlers.
472
- *
473
- * @returns {void}
474
- * @private
475
- */
476
- _initCanvas() {
477
- const canvasElement = this._getElement("canvas");
478
- if (!canvasElement) throw new Error("Canvas is not found: " + this.elements.canvas);
479
- this.canvasElement = canvasElement;
480
- this._canvasElementOriginalStyle = {
481
- display: canvasElement.style.display || "",
482
- width: canvasElement.style.width || "",
483
- height: canvasElement.style.height || "",
484
- maxWidth: canvasElement.style.maxWidth || ""
485
- };
486
- if (this.elements.canvasContainer) {
487
- const containerElement = this._getElement("canvasContainer");
488
- this.containerElement = containerElement || canvasElement.parentElement;
489
- } else {
490
- this.containerElement = canvasElement.parentElement;
491
- }
492
- this.placeholderElement = this._getElement("imagePlaceholder") || null;
493
- let initialWidth = this.options.canvasWidth;
494
- let initialHeight = this.options.canvasHeight;
495
- if (this.containerElement) {
496
- const containerWidth = Math.floor(this.containerElement.clientWidth);
497
- const containerHeight = Math.floor(this.containerElement.clientHeight);
498
- if (containerWidth > 0 && containerHeight > 0) {
499
- initialWidth = containerWidth;
500
- initialHeight = containerHeight;
501
- this._lastContainerViewportSize = {
502
- width: containerWidth,
503
- height: containerHeight
504
- };
505
- }
506
- }
507
- this.canvas = new fabric.Canvas(canvasElement, {
508
- width: initialWidth,
509
- height: initialHeight,
510
- backgroundColor: this.options.backgroundColor,
511
- selection: this.options.groupSelection,
512
- preserveObjectStacking: true
513
- });
514
- this.canvas.on("selection:created", (event) => this._handleSelectionChanged(event.selected));
515
- this.canvas.on("selection:updated", (event) => this._handleSelectionChanged(event.selected));
516
- this.canvas.on("selection:cleared", () => this._handleSelectionChanged([]));
517
- this.canvas.on("object:moving", (event) => {
518
- if (event.target && event.target.maskId) this._syncMaskLabel(event.target);
519
- });
520
- this.canvas.on("object:scaling", (event) => {
521
- if (event.target && event.target.maskId) this._syncMaskLabel(event.target);
522
- });
523
- this.canvas.on("object:rotating", (event) => {
524
- if (event.target && event.target.maskId) this._syncMaskLabel(event.target);
525
- });
526
- this.canvas.on("object:modified", (event) => this._handleObjectModified(event.target));
527
- this.canvasElement.style.display = "block";
528
- }
529
- /**
530
- * Returns a configured DOM element and caches lookups for hot UI paths.
531
- *
532
- * @param {string} key - Key in the configured element map.
533
- * @returns {HTMLElement|null} The configured element, or null when missing.
534
- * @private
535
- */
536
- _getElement(key) {
537
- const id = this.elements && this.elements[key];
538
- if (!id) return null;
539
- if (this._elementCache && Object.prototype.hasOwnProperty.call(this._elementCache, key)) {
540
- return this._elementCache[key];
541
- }
542
- const element = document.getElementById(id);
543
- if (this._elementCache) this._elementCache[key] = element || null;
544
- return element || null;
545
- }
546
- /**
547
- * Records a history entry after Fabric finishes modifying one or more masks.
548
- *
549
- * @param {fabric.Object|fabric.ActiveSelection|null} target - Modified Fabric object or selection.
550
- * @returns {void}
551
- * @private
552
- */
553
- _handleObjectModified(target) {
554
- const masks = this._getModifiedMasks(target);
555
- if (!masks.length) return;
556
- masks.forEach((mask) => {
557
- if (typeof mask.setCoords === "function") mask.setCoords();
558
- this._syncMaskLabel(mask);
559
- });
560
- this._expandCanvasToFitObjects(masks);
561
- this.saveState();
562
- }
563
- /**
564
- * Extracts editable mask objects from a Fabric modification target.
565
- *
566
- * @param {fabric.Object|fabric.ActiveSelection|null} target - Fabric object or active selection.
567
- * @returns {Array<fabric.Object>} Modified mask objects.
568
- * @private
569
- */
570
- _getModifiedMasks(target) {
571
- if (!target) return [];
572
- if (target.maskId) return [target];
573
- const objects = typeof target.getObjects === "function" ? target.getObjects() : [];
574
- return Array.isArray(objects) ? objects.filter((object) => object && object.maskId) : [];
575
- }
576
- /**
577
- * Updates container overflow behavior for fit and cover image modes.
578
- *
579
- * @param {Object} [options={}] - Overflow update options.
580
- * @param {boolean} [options.preserveScroll=false] - If true, keeps the current scroll offsets.
581
- * @returns {void}
582
- * @private
583
- */
584
- _syncContainerOverflow(options = {}) {
585
- if (!this.containerElement || !this.containerElement.style) return;
586
- this._captureContainerOverflowState();
587
- const shouldPreserveScroll = options.preserveScroll === true;
588
- const layoutMode = this._getImageLayoutMode();
589
- if (layoutMode === "cover") {
590
- this.containerElement.style.overflow = "scroll";
591
- if (!shouldPreserveScroll) {
592
- this.containerElement.scrollLeft = 0;
593
- this.containerElement.scrollTop = 0;
594
- }
595
- } else if (layoutMode === "fit") {
596
- this.containerElement.style.overflow = "auto";
597
- if (!shouldPreserveScroll) {
598
- this.containerElement.scrollLeft = 0;
599
- this.containerElement.scrollTop = 0;
600
- }
601
- } else {
602
- this._restoreContainerOverflowState();
603
- }
604
- }
605
- _captureContainerOverflowState() {
606
- if (!this.containerElement || !this.containerElement.style || this._containerOriginalOverflow) return;
607
- this._containerOriginalOverflow = {
608
- overflow: this.containerElement.style.overflow || "",
609
- overflowX: this.containerElement.style.overflowX || "",
610
- overflowY: this.containerElement.style.overflowY || ""
611
- };
612
- }
613
- _restoreContainerOverflowState() {
614
- if (!this.containerElement || !this.containerElement.style || !this._containerOriginalOverflow) return;
615
- this.containerElement.style.overflow = this._containerOriginalOverflow.overflow;
616
- this.containerElement.style.overflowX = this._containerOriginalOverflow.overflowX;
617
- this.containerElement.style.overflowY = this._containerOriginalOverflow.overflowY;
618
- }
619
- _restoreContainerOverflowSnapshot(snapshot) {
620
- if (!this.containerElement || !this.containerElement.style || !snapshot) return;
621
- this.containerElement.style.overflow = snapshot.overflow || "";
622
- this.containerElement.style.overflowX = snapshot.overflowX || "";
623
- this.containerElement.style.overflowY = snapshot.overflowY || "";
624
- }
625
- /**
626
- * DOM / UI bindings
627
- * @private
628
- */
629
- _bindEvents() {
630
- this._bindIfExists("uploadArea", "click", () => {
631
- const uploadAreaElement = this._getElement("uploadArea");
632
- if (this._isElementDisabled(uploadAreaElement)) return;
633
- this._getElement("imageInput")?.click();
634
- });
635
- this._bindIfExists("imageInput", "change", (event) => {
636
- const file = event.target.files && event.target.files[0];
637
- if (file) {
638
- this._loadImageFile(file).catch((error) => this._reportError("Image file could not be loaded", error)).finally(() => {
639
- event.target.value = "";
640
- });
641
- }
642
- });
643
- this._bindIfExists("zoomInButton", "click", () => this.scaleImage(this.currentScale + this.options.scaleStep).catch((error) => this._reportError("scaleImage failed", error)));
644
- this._bindIfExists("zoomOutButton", "click", () => this.scaleImage(this.currentScale - this.options.scaleStep).catch((error) => this._reportError("scaleImage failed", error)));
645
- this._bindIfExists("resetImageTransformButton", "click", () => {
646
- this.resetImageTransform().catch((error) => this._reportError("resetImageTransform failed", error));
647
- });
648
- this._bindIfExists("createMaskButton", "click", () => this.createMask());
649
- this._bindIfExists("removeSelectedMaskButton", "click", () => this.removeSelectedMask());
650
- this._bindIfExists("removeAllMasksButton", "click", () => this.removeAllMasks());
651
- this._bindIfExists("mergeMasksButton", "click", () => this.mergeMasks().catch((error) => this._reportError("merge error", error)));
652
- this._bindIfExists("downloadImageButton", "click", () => this.downloadImage());
653
- this._bindIfExists("undoButton", "click", () => this.undo().catch((error) => this._reportError("undo failed", error)));
654
- this._bindIfExists("redoButton", "click", () => this.redo().catch((error) => this._reportError("redo failed", error)));
655
- this._bindIfExists("rotateLeftButton", "click", () => {
656
- const rotationInputElement = this._getElement("rotateLeftDegreesInput");
657
- let step = this.options.rotationStep;
658
- if (rotationInputElement) {
659
- const parsedStep = parseFloat(rotationInputElement.value);
660
- if (!isNaN(parsedStep)) step = parsedStep;
661
- }
662
- this.rotateImage(this.currentRotation - step).catch((error) => this._reportError("rotateImage failed", error));
663
- });
664
- this._bindIfExists("rotateRightButton", "click", () => {
665
- const rotationInputElement = this._getElement("rotateRightDegreesInput");
666
- let step = this.options.rotationStep;
667
- if (rotationInputElement) {
668
- const parsedStep = parseFloat(rotationInputElement.value);
669
- if (!isNaN(parsedStep)) step = parsedStep;
670
- }
671
- this.rotateImage(this.currentRotation + step).catch((error) => this._reportError("rotateImage failed", error));
672
- });
673
- this._bindIfExists("enterCropModeButton", "click", () => this.enterCropMode());
674
- this._bindIfExists("applyCropButton", "click", () => {
675
- this.applyCrop().catch((error) => this._reportError("applyCrop failed", error));
676
- });
677
- this._bindIfExists("cancelCropButton", "click", () => this.cancelCrop());
678
- this._bindIfExists("maskList", "click", (event) => this._handleMaskListClick(event));
679
- }
680
- /**
681
- * Binds a DOM event listener when the configured element exists and records it for disposal.
682
- *
683
- * @param {string} key - Key in this.elements for the target DOM element.
684
- * @param {string} eventName - DOM event name to listen for.
685
- * @param {EventListener} handler - Event listener callback.
686
- * @private
687
- */
688
- _bindIfExists(key, eventName, handler) {
689
- const element = this._getElement(key);
690
- if (element) {
691
- element.addEventListener(eventName, handler);
692
- this._handlersByElementKey = this._handlersByElementKey || {};
693
- if (!this._handlersByElementKey[key]) this._handlersByElementKey[key] = [];
694
- this._handlersByElementKey[key].push({ eventName, handler });
695
- }
696
- }
697
- /**
698
- * Reads an image File as a data URL and loads it into the Fabric canvas.
699
- *
700
- * @param {File} file - Image file selected by the user.
701
- * @returns {Promise<void>} Resolves after the selected file is loaded.
702
- * @private
703
- */
704
- _loadImageFile(file) {
705
- if (!this._isSupportedImageFile(file)) {
706
- const error = new Error("Selected file is not a supported image");
707
- return Promise.reject(error);
708
- }
709
- return new Promise((resolve, reject) => {
710
- const reader = new FileReader();
711
- reader.onload = (event) => {
712
- this.loadImage(event.target.result).then(resolve).catch(reject);
713
- };
714
- reader.onerror = (event) => {
715
- const error = new Error("Image file could not be read");
716
- this._reportError("Image file could not be read", event);
717
- reject(error);
718
- };
719
- reader.readAsDataURL(file);
720
- });
721
- }
722
- _isSupportedImageFile(file) {
723
- if (!file) return false;
724
- if (typeof file.type === "string" && file.type.startsWith("image/")) return true;
725
- const fileName = String(file.name || "");
726
- return /\.(avif|bmp|gif|jpe?g|png|webp)$/i.test(fileName);
727
- }
728
- /**
729
- * Warns when more than one mutually exclusive image layout mode is enabled.
730
- *
731
- * @returns {void}
732
- * @private
733
- */
734
- _warnOnImageLayoutOptionConflict() {
735
- const activeModes = [
736
- ["fitImageToCanvas", this.options.fitImageToCanvas],
737
- ["coverImageToCanvas", this.options.coverImageToCanvas],
738
- ["expandCanvasToImage", this.options.expandCanvasToImage]
739
- ].filter(([, isEnabled]) => !!isEnabled).map(([name]) => name);
740
- if (activeModes.length <= 1) return;
741
- this._reportWarning(
742
- `Only one image layout mode should be enabled. Active modes: ${activeModes.join(", ")}.`
743
- );
744
- }
745
- _getImageLayoutMode() {
746
- if (this.options.fitImageToCanvas) return "fit";
747
- if (this.options.coverImageToCanvas) return "cover";
748
- if (this.options.expandCanvasToImage) return "expand";
749
- return "contain";
750
- }
751
- /**
752
- * Loads a base64 data URL into the Fabric canvas as the base image.
753
- *
754
- * @async
755
- * @param {string} imageBase64 - Image data URL beginning with `data:image/`.
756
- * @param {LoadImageOptions} [options={}] - Optional load behavior.
757
- * @returns {Promise<void>} Resolves after the Fabric image is added to the canvas.
758
- * @public
759
- */
760
- async loadImage(imageBase64, options = {}) {
761
- if (!this._fabricLoaded) return;
762
- if (!this.canvas || this._disposed) return;
763
- if (!imageBase64 || typeof imageBase64 !== "string" || !imageBase64.startsWith("data:image/")) return;
764
- options = options || {};
765
- this._assertIdleForOperation("loadImage", options);
766
- const isNestedOperation = this._isOwnInternalOperation(options);
767
- const operationToken = isNestedOperation ? this._getInternalOperationToken(options) : this._beginBusyOperation("loadImage");
768
- let transaction = null;
769
- let shouldNotifyImageLoaded;
770
- try {
771
- this._isLoading = true;
772
- this._updateUI();
773
- this._warnOnImageLayoutOptionConflict();
774
- transaction = this._captureLoadImageTransaction();
775
- const imageElement = await this._createImageElement(imageBase64);
776
- if (this._disposed || !this.canvas) throw new Error("Editor was disposed while loading image");
777
- let loadSource = imageBase64;
778
- const downsampleMaxWidth = Number(this.options.downsampleMaxWidth);
779
- const downsampleMaxHeight = Number(this.options.downsampleMaxHeight);
780
- if (this.options.downsampleOnLoad && downsampleMaxWidth > 0 && downsampleMaxHeight > 0) {
781
- const shouldResize = imageElement.naturalWidth > downsampleMaxWidth || imageElement.naturalHeight > downsampleMaxHeight;
782
- if (shouldResize) {
783
- const ratio = Math.min(
784
- downsampleMaxWidth / imageElement.naturalWidth,
785
- downsampleMaxHeight / imageElement.naturalHeight
786
- );
787
- const targetWidth = Math.round(imageElement.naturalWidth * ratio);
788
- const targetHeight = Math.round(imageElement.naturalHeight * ratio);
789
- loadSource = this._resampleImageToDataURL(
790
- imageElement,
791
- targetWidth,
792
- targetHeight,
793
- this._normalizeQuality(this.options.downsampleQuality),
794
- imageBase64
795
- );
796
- }
797
- } else if (this.options.downsampleOnLoad) {
798
- this._reportWarning("loadImage: downsample limits must be positive numbers; using the original image");
799
- }
800
- const fabricImage = await this._createFabricImageFromURL(loadSource);
801
- if (this._disposed || !this.canvas) throw new Error("Editor was disposed while loading image");
802
- this.canvas.discardActiveObject();
803
- this._hideAllMaskLabels();
804
- this.canvas.clear();
805
- this.canvas.setBackgroundColor(this.options.backgroundColor, this.canvas.renderAll.bind(this.canvas));
806
- fabricImage.set({ originX: "left", originY: "top", selectable: false, evented: false });
807
- this._setPlaceholderVisible(false);
808
- this._syncContainerOverflow({ preserveScroll: options.preserveScroll === true });
809
- const imageWidth = fabricImage.width;
810
- const imageHeight = fabricImage.height;
811
- const viewport = this._getContainerViewportSize();
812
- const minWidth = viewport.width;
813
- const minHeight = viewport.height;
814
- const layoutMode = this._getImageLayoutMode();
815
- if (layoutMode === "fit") {
816
- const canvasWidth = Math.max(1, minWidth - 1);
817
- const canvasHeight = Math.max(1, minHeight - 1);
818
- this._setCanvasSizeInt(canvasWidth, canvasHeight);
819
- const fitScale = Math.min(canvasWidth / imageWidth, canvasHeight / imageHeight, 1);
820
- fabricImage.set({ left: 0, top: 0 });
821
- fabricImage.scale(fitScale);
822
- this.baseImageScale = fabricImage.scaleX || 1;
823
- } else if (layoutMode === "cover") {
824
- const layout = this._calculateCoverCanvasLayout(imageWidth, imageHeight);
825
- this._setCanvasSizeInt(layout.canvasWidth, layout.canvasHeight);
826
- fabricImage.set({ left: 0, top: 0 });
827
- fabricImage.scale(layout.scale);
828
- this.baseImageScale = fabricImage.scaleX || 1;
829
- } else if (layoutMode === "expand") {
830
- const canvasWidth = Math.max(minWidth, Math.floor(imageWidth));
831
- const canvasHeight = Math.max(minHeight, Math.floor(imageHeight));
832
- this._setCanvasSizeInt(canvasWidth, canvasHeight);
833
- fabricImage.set({ left: 0, top: 0 });
834
- fabricImage.scale(1);
835
- this.baseImageScale = 1;
836
- } else {
837
- const canvasWidth = Math.max(this.options.canvasWidth, minWidth);
838
- const canvasHeight = Math.max(this.options.canvasHeight, minHeight);
839
- this._setCanvasSizeInt(canvasWidth, canvasHeight);
840
- const fitScale = Math.min(canvasWidth / imageWidth, canvasHeight / imageHeight, 1);
841
- fabricImage.set({ left: 0, top: 0 });
842
- fabricImage.scale(fitScale);
843
- this.baseImageScale = fabricImage.scaleX || 1;
844
- }
845
- this.originalImage = fabricImage;
846
- this.canvas.add(fabricImage);
847
- this.canvas.sendToBack(fabricImage);
848
- this._clearMaskPlacementMemory();
849
- if (options.resetMaskCounter !== false) this.maskCounter = 0;
850
- this.currentScale = 1;
851
- this.currentRotation = 0;
852
- this._updateInputs();
853
- this._updateMaskList();
854
- this.isImageLoadedToCanvas = true;
855
- this._updateUI();
856
- this.canvas.renderAll();
857
- this._lastSnapshot = this._captureCanvasStateOrThrow("loadImage");
858
- shouldNotifyImageLoaded = true;
859
- } catch (error) {
860
- await this._rollbackLoadImageTransaction(
861
- transaction,
862
- this._withInternalOperationOptions(operationToken)
863
- );
864
- throw error;
865
- } finally {
866
- this._isLoading = false;
867
- if (!isNestedOperation) this._endBusyOperation(operationToken);
868
- if (!this._disposed && this.canvas) this._updateUI();
869
- }
870
- if (shouldNotifyImageLoaded && !this._disposed && this.canvas) {
871
- this._notifyImageLoaded();
872
- }
873
- }
874
- /**
875
- * Checks whether there is a loaded image on the current canvas.
876
- * @returns {boolean} true if loaded, false if not
877
- */
878
- isImageLoaded() {
879
- const fabricInstance2 = ensureFabric();
880
- return !!(this.originalImage && fabricInstance2 && this.originalImage instanceof fabricInstance2.Image && this.originalImage.width > 0 && this.originalImage.height > 0);
881
- }
882
- /**
883
- * Checks whether the editor is in a temporary non-mutating state.
884
- *
885
- * @returns {boolean} True while loading, animating, cropping, or running a compound operation.
886
- * @public
887
- */
888
- isBusy() {
889
- return !!(this.isAnimating || this._cropMode || this._isApplyingCrop || this._isLoading || this._activeOperationToken || this.animationQueue && this.animationQueue.isBusy());
890
- }
891
- /**
892
- * Creates an HTMLImageElement from a given data URL.
893
- *
894
- * @param {string} dataUrl - A data URL representing the image (e.g., "data:image/png;base64,...").
895
- * @param {number} [timeoutMs=this.options.imageLoadTimeoutMs] - Maximum decode time before rejecting.
896
- * @returns {Promise<HTMLImageElement>} A promise that resolves to the created image element when loaded, or rejects on error.
897
- * @private
898
- */
899
- _createImageElement(dataUrl, timeoutMs = this.options.imageLoadTimeoutMs) {
900
- return new Promise((resolve, reject) => {
901
- const imageElement = new Image();
902
- let isSettled = false;
903
- const safeTimeoutMs = Number.isFinite(Number(timeoutMs)) && Number(timeoutMs) > 0 ? Number(timeoutMs) : 3e4;
904
- let timerId;
905
- const settle = (callback) => {
906
- if (isSettled) return;
907
- isSettled = true;
908
- clearTimeout(timerId);
909
- imageElement.onload = null;
910
- imageElement.onerror = null;
911
- callback();
912
- };
913
- timerId = setTimeout(() => {
914
- settle(() => reject(new Error("Image load timed out")));
915
- try {
916
- imageElement.src = "";
917
- } catch (error) {
918
- this._reportWarning("Image timeout cleanup failed", error);
919
- }
920
- }, safeTimeoutMs);
921
- imageElement.onload = () => settle(() => resolve(imageElement));
922
- imageElement.onerror = (error) => settle(() => reject(error));
923
- imageElement.src = dataUrl;
924
- });
925
- }
926
- _createFabricImageFromURL(dataUrl, timeoutMs = this.options.imageLoadTimeoutMs) {
927
- return new Promise((resolve, reject) => {
928
- const safeTimeoutMs = this._getSafeTimeoutMs(timeoutMs);
929
- let isSettled = false;
930
- let timerId;
931
- const settle = (callback) => {
932
- if (isSettled) return;
933
- isSettled = true;
934
- clearTimeout(timerId);
935
- callback();
936
- };
937
- timerId = setTimeout(() => {
938
- settle(() => reject(new Error("Fabric image load timed out")));
939
- }, safeTimeoutMs);
940
- try {
941
- fabric.Image.fromURL(dataUrl, (fabricImage) => {
942
- settle(() => {
943
- if (!fabricImage) {
944
- reject(new Error("Image could not be loaded"));
945
- return;
946
- }
947
- resolve(fabricImage);
948
- });
949
- }, { crossOrigin: "anonymous" });
950
- } catch (error) {
951
- settle(() => reject(error));
952
- }
953
- });
954
- }
955
- _getSafeTimeoutMs(timeoutMs) {
956
- const safeTimeoutMs = Number(timeoutMs);
957
- return Number.isFinite(safeTimeoutMs) && safeTimeoutMs > 0 ? safeTimeoutMs : 3e4;
958
- }
959
- _captureLoadImageTransaction() {
960
- return {
961
- canvasState: this._serializeCanvasState(),
962
- baseImageScale: this.baseImageScale,
963
- currentScale: this.currentScale,
964
- currentRotation: this.currentRotation,
965
- maskCounter: this.maskCounter,
966
- isImageLoadedToCanvas: this.isImageLoadedToCanvas,
967
- lastSnapshot: this._lastSnapshot,
968
- lastMask: this._lastMask,
969
- lastMaskInitialLeft: this._lastMaskInitialLeft,
970
- lastMaskInitialTop: this._lastMaskInitialTop,
971
- lastMaskInitialWidth: this._lastMaskInitialWidth,
972
- containerOverflow: this.containerElement && this.containerElement.style ? {
973
- overflow: this.containerElement.style.overflow || "",
974
- overflowX: this.containerElement.style.overflowX || "",
975
- overflowY: this.containerElement.style.overflowY || ""
976
- } : null,
977
- scrollLeft: this.containerElement ? this.containerElement.scrollLeft : 0,
978
- scrollTop: this.containerElement ? this.containerElement.scrollTop : 0,
979
- placeholderVisibility: this._captureElementVisibility(this.placeholderElement),
980
- canvasVisibility: this._captureElementVisibility(this._getCanvasVisibilityElement())
981
- };
982
- }
983
- async _rollbackLoadImageTransaction(transaction, options = {}) {
984
- if (!transaction || !this.canvas || this._disposed) return;
985
- let didRestoreCanvasState = false;
986
- let didFailCanvasRestore = false;
987
- try {
988
- if (transaction.canvasState) {
989
- await this.loadFromState(transaction.canvasState, options);
990
- didRestoreCanvasState = true;
991
- }
992
- } catch (error) {
993
- this._lastMask = null;
994
- didFailCanvasRestore = true;
995
- this._reportError("loadImage rollback failed", error);
996
- }
997
- if (didFailCanvasRestore) {
998
- this._reconcileEditorStateFromCanvas();
999
- } else {
1000
- this.baseImageScale = transaction.baseImageScale;
1001
- this.currentScale = transaction.currentScale;
1002
- this.currentRotation = transaction.currentRotation;
1003
- this.maskCounter = transaction.maskCounter;
1004
- this.isImageLoadedToCanvas = transaction.isImageLoadedToCanvas;
1005
- this._lastSnapshot = transaction.lastSnapshot;
1006
- if (didRestoreCanvasState) {
1007
- this._restoreLastMaskReference(transaction.lastMask);
1008
- } else {
1009
- this._lastMask = null;
1010
- }
1011
- this._lastMaskInitialLeft = transaction.lastMaskInitialLeft;
1012
- this._lastMaskInitialTop = transaction.lastMaskInitialTop;
1013
- this._lastMaskInitialWidth = transaction.lastMaskInitialWidth;
1014
- }
1015
- this._restoreElementVisibility(this.placeholderElement, transaction.placeholderVisibility);
1016
- this._restoreElementVisibility(this._getCanvasVisibilityElement(), transaction.canvasVisibility);
1017
- if (this.containerElement) {
1018
- this.containerElement.scrollLeft = transaction.scrollLeft;
1019
- this.containerElement.scrollTop = transaction.scrollTop;
1020
- this._restoreContainerOverflowSnapshot(transaction.containerOverflow);
1021
- }
1022
- this._updateInputs();
1023
- this._updateMaskList();
1024
- this._updateUI();
1025
- if (this.canvas) this.canvas.renderAll();
1026
- }
1027
- _reconcileEditorStateFromCanvas() {
1028
- if (!this.canvas) {
1029
- this.originalImage = null;
1030
- this.baseImageScale = 1;
1031
- this.currentScale = 1;
1032
- this.currentRotation = 0;
1033
- this.maskCounter = 0;
1034
- this.isImageLoadedToCanvas = false;
1035
- this._lastSnapshot = null;
1036
- this._clearMaskPlacementMemory();
1037
- return;
1038
- }
1039
- const canvasObjects = this.canvas.getObjects();
1040
- this.originalImage = canvasObjects.find((object) => object.type === "image" && !object.maskId) || null;
1041
- if (this.originalImage) {
1042
- const imageScale = Number(this.originalImage.scaleX) || 1;
1043
- this.baseImageScale = imageScale;
1044
- this.currentScale = 1;
1045
- this.currentRotation = Number(this.originalImage.angle) || 0;
1046
- } else {
1047
- this.baseImageScale = 1;
1048
- this.currentScale = 1;
1049
- this.currentRotation = 0;
1050
- }
1051
- const masks = canvasObjects.filter((object) => object.maskId);
1052
- this.maskCounter = masks.reduce((max, mask) => Math.max(max, Number(mask.maskId) || 0), 0);
1053
- this._lastMask = masks[masks.length - 1] || null;
1054
- if (!this._lastMask) {
1055
- this._lastMaskInitialLeft = null;
1056
- this._lastMaskInitialTop = null;
1057
- this._lastMaskInitialWidth = null;
1058
- }
1059
- this.isImageLoadedToCanvas = !!this.originalImage;
1060
- try {
1061
- this._lastSnapshot = this._serializeCanvasState();
1062
- } catch (error) {
1063
- this._lastSnapshot = null;
1064
- this._reportWarning("loadImage rollback: failed to reconcile canvas snapshot", error);
1065
- }
1066
- }
1067
- _restoreLastMaskReference(previousLastMask) {
1068
- if (!this.canvas) {
1069
- this._lastMask = null;
1070
- return;
1071
- }
1072
- const masks = this.canvas.getObjects().filter((object) => object.maskId);
1073
- const previousMaskId = previousLastMask && previousLastMask.maskId;
1074
- this._lastMask = masks.find((mask) => mask.maskId === previousMaskId) || masks[masks.length - 1] || null;
1075
- if (!this._lastMask) {
1076
- this._lastMaskInitialLeft = null;
1077
- this._lastMaskInitialTop = null;
1078
- this._lastMaskInitialWidth = null;
1079
- }
1080
- }
1081
- /**
1082
- * Resamples the given image element to a new width and height and returns the result as a data URL.
1083
- *
1084
- * @param {HTMLImageElement} imageElement - The image element to resample.
1085
- * @param {number} targetWidth - Target width (in pixels) for the resampled image.
1086
- * @param {number} targetHeight - Target height (in pixels) for the resampled image.
1087
- * @param {number} [quality=0.92] - Image quality between 0 and 1 for lossy formats.
1088
- * @param {string|null} [sourceDataUrl=null] - Source data URL used to preserve alpha-capable formats.
1089
- * @returns {string} A data URL representing the resampled image.
1090
- * @private
1091
- */
1092
- _resampleImageToDataURL(imageElement, targetWidth, targetHeight, quality = 0.92, sourceDataUrl = null) {
1093
- const sourceWidth = Math.max(1, Number(imageElement && (imageElement.naturalWidth || imageElement.width)) || 0);
1094
- const sourceHeight = Math.max(1, Number(imageElement && (imageElement.naturalHeight || imageElement.height)) || 0);
1095
- const safeTargetWidth = Math.round(Number(targetWidth));
1096
- const safeTargetHeight = Math.round(Number(targetHeight));
1097
- if (!Number.isFinite(safeTargetWidth) || !Number.isFinite(safeTargetHeight) || safeTargetWidth <= 0 || safeTargetHeight <= 0) {
1098
- throw new Error("Invalid image resample target dimensions");
1099
- }
1100
- const offscreenCanvas = document.createElement("canvas");
1101
- offscreenCanvas.width = safeTargetWidth;
1102
- offscreenCanvas.height = safeTargetHeight;
1103
- const context = offscreenCanvas.getContext("2d");
1104
- if (!context) throw new Error("2D canvas context is unavailable");
1105
- context.drawImage(imageElement, 0, 0, sourceWidth, sourceHeight, 0, 0, safeTargetWidth, safeTargetHeight);
1106
- return offscreenCanvas.toDataURL(this._getDownsampleMimeType(sourceDataUrl), quality);
1107
- }
1108
- _getDataUrlMimeType(dataUrl) {
1109
- const match = String(dataUrl || "").match(/^data:([^;,]+)[;,]/i);
1110
- return match ? match[1].toLowerCase() : "";
1111
- }
1112
- _getDownsampleMimeType(sourceDataUrl) {
1113
- if (this.options.downsampleMimeType) {
1114
- const requestedFormat = this._normalizeImageFormat(this.options.downsampleMimeType);
1115
- return `image/${requestedFormat}`;
1116
- }
1117
- const sourceMimeType = this._getDataUrlMimeType(sourceDataUrl);
1118
- if (this.options.preserveSourceFormat !== false && (sourceMimeType === "image/png" || sourceMimeType === "image/webp")) {
1119
- return sourceMimeType;
1120
- }
1121
- return "image/jpeg";
1122
- }
1123
- _captureCanvasStateOrThrow(context) {
1124
- const snapshot = this._serializeCanvasState();
1125
- if (!snapshot) throw new Error(`${context}: canvas state is unavailable`);
1126
- return snapshot;
1127
- }
1128
- /**
1129
- * Sets canvas size to integer width and height values to prevent scrollbars due to sub-pixel rendering.
1130
- * Also updates the corresponding style attributes.
1131
- *
1132
- * @param {number} width - Canvas width in pixels.
1133
- * @param {number} height - Canvas height in pixels.
1134
- * @private
1135
- */
1136
- _setCanvasSizeInt(width, height) {
1137
- if (!this.canvas) return;
1138
- const integerWidth = Math.max(1, Math.round(Number(width) || 1));
1139
- const integerHeight = Math.max(1, Math.round(Number(height) || 1));
1140
- this.canvas.setWidth(integerWidth);
1141
- this.canvas.setHeight(integerHeight);
1142
- if (typeof this.canvas.calcOffset === "function") this.canvas.calcOffset();
1143
- if (this.canvasElement) {
1144
- this.canvasElement.style.width = integerWidth + "px";
1145
- this.canvasElement.style.height = integerHeight + "px";
1146
- }
1147
- }
1148
- _ceilCanvasDimension(value) {
1149
- const numericValue = Number(value) || 0;
1150
- const roundedValue = Math.round(numericValue);
1151
- if (Math.abs(numericValue - roundedValue) < 0.01) return roundedValue;
1152
- return Math.ceil(numericValue);
1153
- }
1154
- _getContainerViewportSize() {
1155
- if (!this.containerElement) {
1156
- return {
1157
- width: Math.max(1, Math.floor(this.options.canvasWidth || 1)),
1158
- height: Math.max(1, Math.floor(this.options.canvasHeight || 1))
1159
- };
1160
- }
1161
- const measuredWidth = Math.floor(this.containerElement.clientWidth || 0);
1162
- const measuredHeight = Math.floor(this.containerElement.clientHeight || 0);
1163
- let width = Math.max(1, measuredWidth || this._lastContainerViewportSize?.width || this.options.canvasWidth || 1);
1164
- let height = Math.max(1, measuredHeight || this._lastContainerViewportSize?.height || this.options.canvasHeight || 1);
1165
- if (measuredWidth > 0 && measuredHeight > 0) {
1166
- this._lastContainerViewportSize = { width: measuredWidth, height: measuredHeight };
1167
- }
1168
- if (this._hasFixedContainerScrollbars()) {
1169
- return { width, height };
1170
- }
1171
- const overflow = this._getContainerOverflowValues();
1172
- const canScrollX = overflow.x.some((value) => value === "auto" || value === "scroll");
1173
- const canScrollY = overflow.y.some((value) => value === "auto" || value === "scroll");
1174
- const hasHorizontalScrollbar = canScrollX && this.containerElement.scrollWidth > this.containerElement.clientWidth;
1175
- const hasVerticalScrollbar = canScrollY && this.containerElement.scrollHeight > this.containerElement.clientHeight;
1176
- if (hasHorizontalScrollbar || hasVerticalScrollbar) {
1177
- const scrollbar = this._getScrollbarSize();
1178
- if (hasVerticalScrollbar) width += scrollbar.width;
1179
- if (hasHorizontalScrollbar) height += scrollbar.height;
1180
- }
1181
- return { width, height };
1182
- }
1183
- /**
1184
- * Reads inline and computed overflow values for both scroll axes.
1185
- *
1186
- * @returns {{x:string[], y:string[]}} Overflow values grouped by axis.
1187
- * @private
1188
- */
1189
- _getContainerOverflowValues() {
1190
- if (!this.containerElement) return { x: [], y: [] };
1191
- const inlineOverflow = this.containerElement.style.overflow;
1192
- const inlineOverflowX = this.containerElement.style.overflowX;
1193
- const inlineOverflowY = this.containerElement.style.overflowY;
1194
- let computedOverflow = "";
1195
- let computedOverflowX = "";
1196
- let computedOverflowY = "";
1197
- if (typeof window !== "undefined" && typeof window.getComputedStyle === "function") {
1198
- const style = window.getComputedStyle(this.containerElement);
1199
- computedOverflow = style.overflow;
1200
- computedOverflowX = style.overflowX;
1201
- computedOverflowY = style.overflowY;
1202
- }
1203
- return {
1204
- x: [inlineOverflow, inlineOverflowX, computedOverflow, computedOverflowX],
1205
- y: [inlineOverflow, inlineOverflowY, computedOverflow, computedOverflowY]
1206
- };
1207
- }
1208
- _hasFixedContainerScrollbars() {
1209
- if (!this.containerElement) return false;
1210
- const overflow = this._getContainerOverflowValues();
1211
- return [...overflow.x, ...overflow.y].some((value) => value === "scroll");
1212
- }
1213
- _getScrollbarSize() {
1214
- if (this._scrollbarSizeCache) {
1215
- return { ...this._scrollbarSizeCache };
1216
- }
1217
- if (typeof document === "undefined" || !document.createElement || !document.body) {
1218
- return { width: 0, height: 0 };
1219
- }
1220
- const probe = document.createElement("div");
1221
- probe.style.position = "absolute";
1222
- probe.style.visibility = "hidden";
1223
- probe.style.overflow = "scroll";
1224
- probe.style.width = "100px";
1225
- probe.style.height = "100px";
1226
- probe.style.top = "-9999px";
1227
- document.body.appendChild(probe);
1228
- const width = Math.max(0, probe.offsetWidth - probe.clientWidth);
1229
- const height = Math.max(0, probe.offsetHeight - probe.clientHeight);
1230
- document.body.removeChild(probe);
1231
- this._scrollbarSizeCache = { width, height };
1232
- return { ...this._scrollbarSizeCache };
1233
- }
1234
- _getScrollSafetyMargin() {
1235
- return 2;
1236
- }
1237
- _getScrollableCanvasSize(contentWidth, contentHeight, viewport = this._getContainerViewportSize()) {
1238
- if (this._hasFixedContainerScrollbars()) {
1239
- const safetyMargin2 = this._getScrollSafetyMargin();
1240
- const safeWidth = Math.max(1, viewport.width - safetyMargin2);
1241
- const safeHeight = Math.max(1, viewport.height - safetyMargin2);
1242
- return {
1243
- width: contentWidth > viewport.width + 0.5 ? this._ceilCanvasDimension(contentWidth) : safeWidth,
1244
- height: contentHeight > viewport.height + 0.5 ? this._ceilCanvasDimension(contentHeight) : safeHeight,
1245
- viewportWidth: viewport.width,
1246
- viewportHeight: viewport.height,
1247
- hasHorizontal: true,
1248
- hasVertical: true
1249
- };
1250
- }
1251
- const scrollbar = this._getScrollbarSize();
1252
- let hasVertical = false;
1253
- let hasHorizontal = false;
1254
- let effectiveWidth;
1255
- let effectiveHeight;
1256
- for (let i = 0; i < 4; i += 1) {
1257
- effectiveWidth = Math.max(1, viewport.width - (hasVertical ? scrollbar.width : 0));
1258
- effectiveHeight = Math.max(1, viewport.height - (hasHorizontal ? scrollbar.height : 0));
1259
- const nextHasVertical = contentHeight > effectiveHeight + 0.5;
1260
- const nextHasHorizontal = contentWidth > effectiveWidth + 0.5;
1261
- if (nextHasVertical === hasVertical && nextHasHorizontal === hasHorizontal) break;
1262
- hasVertical = nextHasVertical;
1263
- hasHorizontal = nextHasHorizontal;
1264
- }
1265
- effectiveWidth = Math.max(1, viewport.width - (hasVertical ? scrollbar.width : 0));
1266
- effectiveHeight = Math.max(1, viewport.height - (hasHorizontal ? scrollbar.height : 0));
1267
- const safetyMargin = this._getScrollSafetyMargin();
1268
- const layoutMode = this._getImageLayoutMode();
1269
- const shouldReserveNoScrollbarMargin = layoutMode === "fit" || layoutMode === "cover";
1270
- const getNonOverflowAxisSize = (contentSize, effectiveSize, hasOppositeScrollbar) => {
1271
- const margin = hasOppositeScrollbar ? safetyMargin : shouldReserveNoScrollbarMargin ? 1 : 0;
1272
- const safeEffectiveSize = Math.max(1, effectiveSize - margin);
1273
- return contentSize <= safeEffectiveSize + 0.5 ? safeEffectiveSize : effectiveSize;
1274
- };
1275
- return {
1276
- width: hasHorizontal ? this._ceilCanvasDimension(contentWidth) : getNonOverflowAxisSize(contentWidth, effectiveWidth, hasVertical),
1277
- height: hasVertical ? this._ceilCanvasDimension(contentHeight) : getNonOverflowAxisSize(contentHeight, effectiveHeight, hasHorizontal),
1278
- viewportWidth: effectiveWidth,
1279
- viewportHeight: effectiveHeight,
1280
- hasHorizontal,
1281
- hasVertical
1282
- };
1283
- }
1284
- _calculateCoverCanvasLayout(imageWidth, imageHeight) {
1285
- const viewport = this._getContainerViewportSize();
1286
- if (this._hasFixedContainerScrollbars()) {
1287
- const safetyMargin = this._getScrollSafetyMargin();
1288
- const targetWidth = Math.max(1, viewport.width - safetyMargin);
1289
- const targetHeight = Math.max(1, viewport.height - safetyMargin);
1290
- const scale2 = Math.min(1, Math.max(targetWidth / imageWidth, targetHeight / imageHeight));
1291
- const contentWidth2 = imageWidth * scale2;
1292
- const contentHeight2 = imageHeight * scale2;
1293
- const canvasSize2 = this._getScrollableCanvasSize(contentWidth2, contentHeight2, viewport);
1294
- return {
1295
- scale: scale2,
1296
- canvasWidth: canvasSize2.width,
1297
- canvasHeight: canvasSize2.height
1298
- };
1299
- }
1300
- const scrollbar = this._getScrollbarSize();
1301
- let hasVertical = false;
1302
- let hasHorizontal = false;
1303
- let scale = 1;
1304
- let contentWidth = imageWidth;
1305
- let contentHeight = imageHeight;
1306
- let effectiveWidth;
1307
- let effectiveHeight;
1308
- for (let i = 0; i < 4; i += 1) {
1309
- effectiveWidth = Math.max(1, viewport.width - (hasVertical ? scrollbar.width : 0));
1310
- effectiveHeight = Math.max(1, viewport.height - (hasHorizontal ? scrollbar.height : 0));
1311
- scale = Math.min(1, Math.max(effectiveWidth / imageWidth, effectiveHeight / imageHeight));
1312
- contentWidth = imageWidth * scale;
1313
- contentHeight = imageHeight * scale;
1314
- const nextHasVertical = contentHeight > effectiveHeight + 0.5;
1315
- const nextHasHorizontal = contentWidth > effectiveWidth + 0.5;
1316
- if (nextHasVertical === hasVertical && nextHasHorizontal === hasHorizontal) break;
1317
- hasVertical = nextHasVertical;
1318
- hasHorizontal = nextHasHorizontal;
1319
- }
1320
- const canvasSize = this._getScrollableCanvasSize(contentWidth, contentHeight, viewport);
1321
- return {
1322
- scale,
1323
- canvasWidth: canvasSize.width,
1324
- canvasHeight: canvasSize.height
1325
- };
1326
- }
1327
- _getStateProperties() {
1328
- return [
1329
- "maskId",
1330
- "maskName",
1331
- "maskLabel",
1332
- "isCropRect",
1333
- "originalAlpha",
1334
- "originalStroke",
1335
- "originalStrokeWidth",
1336
- "selectable",
1337
- "evented",
1338
- "hasControls",
1339
- "lockRotation",
1340
- "borderColor",
1341
- "cornerColor",
1342
- "cornerSize",
1343
- "transparentCorners",
1344
- "strokeUniform",
1345
- "strokeDashArray"
1346
- ];
1347
- }
1348
- _getMaskNormalStyle(mask) {
1349
- const strokeWidth = Number(mask && mask.originalStrokeWidth);
1350
- const opacity = Number(mask && mask.originalAlpha);
1351
- const style = {
1352
- stroke: mask && mask.originalStroke || "#ccc",
1353
- strokeWidth: Number.isFinite(strokeWidth) ? strokeWidth : 1
1354
- };
1355
- if (Number.isFinite(opacity)) style.opacity = opacity;
1356
- return style;
1357
- }
1358
- _withNormalizedMaskStyles(callback) {
1359
- if (!this.canvas) return callback();
1360
- const masks = this.canvas.getObjects().filter((object) => object.maskId);
1361
- const maskStyleBackups = [];
1362
- try {
1363
- masks.forEach((mask) => {
1364
- const normalStyle = this._getMaskNormalStyle(mask);
1365
- const stylePatch = {};
1366
- Object.keys(normalStyle).forEach((property) => {
1367
- if (mask[property] !== normalStyle[property]) {
1368
- stylePatch[property] = normalStyle[property];
1369
- }
1370
- });
1371
- const changedProperties = Object.keys(stylePatch);
1372
- if (!changedProperties.length) return;
1373
- const backup = { object: mask };
1374
- changedProperties.forEach((property) => {
1375
- backup[property] = mask[property];
1376
- });
1377
- maskStyleBackups.push(backup);
1378
- mask.set(stylePatch);
1379
- });
1380
- const result = callback();
1381
- if (result && typeof result.then === "function") {
1382
- throw new Error("_withNormalizedMaskStyles callback must be synchronous");
1383
- }
1384
- return result;
1385
- } finally {
1386
- maskStyleBackups.forEach((backup) => {
1387
- try {
1388
- const restorePatch = {};
1389
- Object.keys(backup).forEach((property) => {
1390
- if (property !== "object") restorePatch[property] = backup[property];
1391
- });
1392
- backup.object.set(restorePatch);
1393
- } catch (error) {
1394
- void error;
1395
- }
1396
- });
1397
- }
1398
- }
1399
- _getSerializableStateObjects() {
1400
- if (!this.canvas) return [];
1401
- return this.canvas.getObjects().filter((object) => !object.isCropRect && !object.maskLabel);
1402
- }
1403
- _restoreHighPrecisionSerializedGeometry(serializedObjects) {
1404
- if (!Array.isArray(serializedObjects)) return;
1405
- const fabricObjects = this._getSerializableStateObjects();
1406
- const numericProperties = [
1407
- "left",
1408
- "top",
1409
- "width",
1410
- "height",
1411
- "scaleX",
1412
- "scaleY",
1413
- "angle",
1414
- "skewX",
1415
- "skewY",
1416
- "cropX",
1417
- "cropY",
1418
- "radius",
1419
- "rx",
1420
- "ry",
1421
- "strokeWidth"
1422
- ];
1423
- serializedObjects.forEach((serializedObject, index) => {
1424
- const fabricObject = fabricObjects[index];
1425
- if (!serializedObject || !fabricObject) return;
1426
- numericProperties.forEach((property) => {
1427
- const numericValue = Number(fabricObject[property]);
1428
- if (Number.isFinite(numericValue)) serializedObject[property] = numericValue;
1429
- });
1430
- if (Array.isArray(serializedObject.points) && Array.isArray(fabricObject.points)) {
1431
- serializedObject.points = fabricObject.points.map((point) => ({
1432
- x: Number.isFinite(Number(point && point.x)) ? Number(point.x) : 0,
1433
- y: Number.isFinite(Number(point && point.y)) ? Number(point.y) : 0
1434
- }));
1435
- }
1436
- });
1437
- }
1438
- _restoreMaskControls(mask) {
1439
- if (!mask) return;
1440
- const cornerSize = Number(mask.cornerSize);
1441
- mask.set({
1442
- selectable: mask.selectable !== false,
1443
- evented: mask.evented !== false,
1444
- hasControls: mask.hasControls !== false,
1445
- lockRotation: typeof mask.lockRotation === "boolean" ? mask.lockRotation : !this.options.maskRotatable,
1446
- borderColor: mask.borderColor || "red",
1447
- cornerColor: mask.cornerColor || "black",
1448
- cornerSize: Number.isFinite(cornerSize) ? cornerSize : 8,
1449
- transparentCorners: mask.transparentCorners === true,
1450
- strokeUniform: mask.strokeUniform !== false
1451
- });
1452
- if (typeof mask.setCoords === "function") mask.setCoords();
1453
- }
1454
- /**
1455
- * Captures editor-owned runtime state that Fabric does not include in canvas JSON.
1456
- *
1457
- * @returns {{version:number, baseImageScale:number, currentScale:number, currentRotation:number, maskCounter:number, canvasWidth:number, canvasHeight:number}} Serializable editor metadata.
1458
- * @private
1459
- */
1460
- _serializeEditorMetadata() {
1461
- const baseImageScale = Number(this.baseImageScale);
1462
- const currentScale = Number(this.currentScale);
1463
- const currentRotation = Number(this.currentRotation);
1464
- const maskCounter = Number(this.maskCounter);
1465
- const canvasWidth = this.canvas ? Number(this.canvas.getWidth()) : NaN;
1466
- const canvasHeight = this.canvas ? Number(this.canvas.getHeight()) : NaN;
1467
- return {
1468
- version: 1,
1469
- baseImageScale: Number.isFinite(baseImageScale) && baseImageScale > 0 ? baseImageScale : 1,
1470
- currentScale: Number.isFinite(currentScale) && currentScale > 0 ? currentScale : 1,
1471
- currentRotation: Number.isFinite(currentRotation) ? currentRotation : 0,
1472
- maskCounter: Number.isFinite(maskCounter) && maskCounter > 0 ? Math.floor(maskCounter) : 0,
1473
- canvasWidth: Number.isFinite(canvasWidth) && canvasWidth > 0 ? Math.round(canvasWidth) : 1,
1474
- canvasHeight: Number.isFinite(canvasHeight) && canvasHeight > 0 ? Math.round(canvasHeight) : 1
1475
- };
1476
- }
1477
- _serializeCanvasState() {
1478
- if (!this.canvas) return null;
1479
- return this._withNormalizedMaskStyles(() => {
1480
- const jsonObject = this.canvas.toJSON(this._getStateProperties());
1481
- if (Array.isArray(jsonObject.objects)) {
1482
- jsonObject.objects = jsonObject.objects.filter((object) => !object.isCropRect && !object.maskLabel);
1483
- this._restoreHighPrecisionSerializedGeometry(jsonObject.objects);
1484
- }
1485
- jsonObject.imageEditorMetadata = this._serializeEditorMetadata();
1486
- return JSON.stringify(jsonObject);
1487
- });
1488
- }
1489
- /**
1490
- * Normalizes a lossy image quality value to Fabric/canvas's 0..1 range.
1491
- *
1492
- * @param {number} quality - Requested image quality.
1493
- * @returns {number} A finite quality value between 0 and 1.
1494
- * @private
1495
- */
1496
- _normalizeQuality(quality, fallback = void 0) {
1497
- const fallbackQuality = fallback == null ? this.options.downsampleQuality : fallback;
1498
- const numericFallback = fallbackQuality == null ? NaN : Number(fallbackQuality);
1499
- const safeFallback = Number.isFinite(numericFallback) ? Math.max(0, Math.min(1, numericFallback)) : 0.92;
1500
- if (quality == null) return safeFallback;
1501
- const numericQuality = Number(quality);
1502
- if (!Number.isFinite(numericQuality)) return safeFallback;
1503
- return Math.max(0, Math.min(1, numericQuality));
1504
- }
1505
- /**
1506
- * Normalizes public image format aliases to canvas export format names.
1507
- *
1508
- * @param {string} format - Requested image format or MIME type.
1509
- * @returns {'jpeg'|'png'|'webp'} Canvas-compatible image format.
1510
- * @private
1511
- */
1512
- _normalizeImageFormat(format) {
1513
- const typeMapping = {
1514
- "jpeg": "jpeg",
1515
- "jpg": "jpeg",
1516
- "image/jpeg": "jpeg",
1517
- "png": "png",
1518
- "image/png": "png",
1519
- "webp": "webp",
1520
- "image/webp": "webp"
1521
- };
1522
- return typeMapping[String(format || "jpeg").toLowerCase()] || "jpeg";
1523
- }
1524
- /**
1525
- * Converts a bounding rectangle into a canvas-safe integer source region.
1526
- *
1527
- * @param {{left:number, top:number, width:number, height:number}} bounds - Bounds in canvas coordinates.
1528
- * @param {Object} [options={}] - Region rounding options.
1529
- * @param {boolean} [options.includePartialPixels=true] - If false, excludes partially covered trailing pixels.
1530
- * @returns {{sourceX:number, sourceY:number, sourceWidth:number, sourceHeight:number}} Clamped source region.
1531
- * @private
1532
- */
1533
- _getClampedCanvasRegion(bounds, options = {}) {
1534
- const canvasWidth = Math.max(1, Math.round(this.canvas.getWidth()));
1535
- const canvasHeight = Math.max(1, Math.round(this.canvas.getHeight()));
1536
- const left = Number(bounds.left) || 0;
1537
- const top = Number(bounds.top) || 0;
1538
- const width = Math.max(0, Number(bounds.width) || 0);
1539
- const height = Math.max(0, Number(bounds.height) || 0);
1540
- const includePartialPixels = options.includePartialPixels !== false;
1541
- const roundEnd = includePartialPixels ? Math.ceil : Math.floor;
1542
- const sourceX = Math.min(canvasWidth - 1, Math.max(0, Math.floor(left)));
1543
- const sourceY = Math.min(canvasHeight - 1, Math.max(0, Math.floor(top)));
1544
- const endX = Math.min(canvasWidth, Math.max(sourceX + 1, roundEnd(left + width)));
1545
- const endY = Math.min(canvasHeight, Math.max(sourceY + 1, roundEnd(top + height)));
1546
- return {
1547
- sourceX,
1548
- sourceY,
1549
- sourceWidth: Math.max(1, endX - sourceX),
1550
- sourceHeight: Math.max(1, endY - sourceY)
1551
- };
1552
- }
1553
- _hasFractionalCanvasEdge(value) {
1554
- const numericValue = Number(value);
1555
- if (!Number.isFinite(numericValue)) return false;
1556
- return Math.abs(numericValue - Math.round(numericValue)) > 0.01;
1557
- }
1558
- _hasScaledImageEdge(axis) {
1559
- if (!this.originalImage) return false;
1560
- const scale = Number(axis === "y" ? this.originalImage.scaleY : this.originalImage.scaleX);
1561
- if (!Number.isFinite(scale)) return false;
1562
- return Math.abs(scale - 1) > 0.01;
1563
- }
1564
- _getPartialExportEdges(bounds) {
1565
- if (!bounds) return null;
1566
- const angle = Math.abs((Number(this.originalImage && this.originalImage.angle) || 0) % 90);
1567
- const isAxisAligned = angle < 0.01 || Math.abs(angle - 90) < 0.01;
1568
- if (!isAxisAligned) return null;
1569
- return {
1570
- left: this._hasFractionalCanvasEdge(bounds.left),
1571
- top: this._hasFractionalCanvasEdge(bounds.top),
1572
- right: this._hasFractionalCanvasEdge((Number(bounds.left) || 0) + (Number(bounds.width) || 0)) || this._hasScaledImageEdge("x"),
1573
- bottom: this._hasFractionalCanvasEdge((Number(bounds.top) || 0) + (Number(bounds.height) || 0)) || this._hasScaledImageEdge("y")
1574
- };
1575
- }
1576
- async _sealPartialTransparentEdges(dataUrl, edges) {
1577
- if (!edges || !Object.values(edges).some(Boolean)) return dataUrl;
1578
- const imageElement = await this._createImageElement(dataUrl);
1579
- const width = Math.max(1, imageElement.naturalWidth || imageElement.width || 1);
1580
- const height = Math.max(1, imageElement.naturalHeight || imageElement.height || 1);
1581
- const offscreenCanvas = document.createElement("canvas");
1582
- offscreenCanvas.width = width;
1583
- offscreenCanvas.height = height;
1584
- const context = offscreenCanvas.getContext("2d");
1585
- if (!context) throw new Error("2D canvas context is unavailable");
1586
- context.drawImage(imageElement, 0, 0, width, height);
1587
- const imageData = context.getImageData(0, 0, width, height);
1588
- const pixels = imageData.data;
1589
- const sealPixel = (x, y, fallbackX, fallbackY) => {
1590
- const index = (y * width + x) * 4;
1591
- const fallbackIndex = (fallbackY * width + fallbackX) * 4;
1592
- if (pixels[index + 3] === 0 && pixels[fallbackIndex + 3] > 0) {
1593
- pixels[index] = pixels[fallbackIndex];
1594
- pixels[index + 1] = pixels[fallbackIndex + 1];
1595
- pixels[index + 2] = pixels[fallbackIndex + 2];
1596
- pixels[index + 3] = pixels[fallbackIndex + 3];
1597
- }
1598
- if (pixels[index + 3] > 0 && pixels[index + 3] < 255) {
1599
- pixels[index + 3] = 255;
1600
- }
1601
- };
1602
- if (edges.left && width > 1) {
1603
- for (let y = 0; y < height; y += 1) sealPixel(0, y, 1, y);
1604
- }
1605
- if (edges.right && width > 1) {
1606
- for (let y = 0; y < height; y += 1) sealPixel(width - 1, y, width - 2, y);
1607
- }
1608
- if (edges.top && height > 1) {
1609
- for (let x = 0; x < width; x += 1) sealPixel(x, 0, x, 1);
1610
- }
1611
- if (edges.bottom && height > 1) {
1612
- for (let x = 0; x < width; x += 1) sealPixel(x, height - 1, x, height - 2);
1613
- }
1614
- context.putImageData(imageData, 0, 0);
1615
- return offscreenCanvas.toDataURL("image/png");
1616
- }
1617
- /**
1618
- * Exports a source region directly through Fabric's region export options.
1619
- *
1620
- * @param {Object} region - Canvas source region and export options.
1621
- * @param {number} region.sourceX - Source region x coordinate.
1622
- * @param {number} region.sourceY - Source region y coordinate.
1623
- * @param {number} region.sourceWidth - Source region width.
1624
- * @param {number} region.sourceHeight - Source region height.
1625
- * @param {number} [region.multiplier=1] - Export multiplier.
1626
- * @param {number} [region.quality=0.92] - Output image quality for lossy formats.
1627
- * @param {'jpeg'|'png'|'webp'} [region.format='jpeg'] - Output image format.
1628
- * @param {Object|null} [region.sealPartialEdges=null] - Fractional canvas edges whose alpha should be sealed.
1629
- * @returns {Promise<string>} Resolves with an image data URL for the cropped region.
1630
- * @private
1631
- */
1632
- async _exportCanvasRegionToDataURL({ sourceX, sourceY, sourceWidth, sourceHeight, multiplier = 1, quality = 0.92, format = "jpeg", sealPartialEdges = null }) {
1633
- const safeMultiplier = this._getSafeExportMultiplier(multiplier);
1634
- this._assertExportPixelBudget(sourceWidth, sourceHeight, safeMultiplier);
1635
- const safeFormat = this._normalizeImageFormat(format);
1636
- const exportFormat = safeFormat === "jpeg" ? "png" : safeFormat;
1637
- let regionDataUrl = this.canvas.toDataURL({
1638
- format: exportFormat,
1639
- quality,
1640
- multiplier: safeMultiplier,
1641
- left: sourceX,
1642
- top: sourceY,
1643
- width: sourceWidth,
1644
- height: sourceHeight
1645
- });
1646
- regionDataUrl = await this._sealPartialTransparentEdges(regionDataUrl, sealPartialEdges);
1647
- if (safeFormat !== "jpeg") return regionDataUrl;
1648
- return this._convertDataUrlToOpaqueJpeg(regionDataUrl, quality);
1649
- }
1650
- _getSafeExportMultiplier(multiplier) {
1651
- const numericMultiplier = Number(multiplier);
1652
- if (!Number.isFinite(numericMultiplier) || numericMultiplier <= 0) {
1653
- throw new Error("Export multiplier must be a finite positive number");
1654
- }
1655
- return Math.max(1, numericMultiplier);
1656
- }
1657
- _assertExportPixelBudget(sourceWidth, sourceHeight, safeMultiplier) {
1658
- const width = Math.max(1, Math.ceil(Number(sourceWidth) || 1));
1659
- const height = Math.max(1, Math.ceil(Number(sourceHeight) || 1));
1660
- const outputWidth = Math.ceil(width * safeMultiplier);
1661
- const outputHeight = Math.ceil(height * safeMultiplier);
1662
- const outputPixels = outputWidth * outputHeight;
1663
- const configuredMaxPixels = Number(this.options.maxExportPixels);
1664
- const maxPixels = Number.isFinite(configuredMaxPixels) && configuredMaxPixels > 0 ? Math.floor(configuredMaxPixels) : 5e7;
1665
- if (outputPixels > maxPixels) {
1666
- throw new Error(`Export would create ${outputPixels} pixels, exceeding the configured maxExportPixels limit of ${maxPixels}`);
1667
- }
1668
- }
1669
- async _convertDataUrlToOpaqueJpeg(dataUrl, quality = 0.92) {
1670
- const imageElement = await this._createImageElement(dataUrl);
1671
- const width = Math.max(1, imageElement.naturalWidth || imageElement.width || 1);
1672
- const height = Math.max(1, imageElement.naturalHeight || imageElement.height || 1);
1673
- const offscreenCanvas = document.createElement("canvas");
1674
- offscreenCanvas.width = width;
1675
- offscreenCanvas.height = height;
1676
- const context = offscreenCanvas.getContext("2d");
1677
- if (!context) throw new Error("2D canvas context is unavailable");
1678
- context.fillStyle = this._getJpegBackgroundColor();
1679
- context.fillRect(0, 0, width, height);
1680
- context.drawImage(imageElement, 0, 0, width, height);
1681
- return offscreenCanvas.toDataURL("image/jpeg", this._normalizeQuality(quality));
1682
- }
1683
- _getJpegBackgroundColor() {
1684
- const backgroundColor = String(this.options.backgroundColor || "").trim();
1685
- if (!backgroundColor || this._isTransparentCssColor(backgroundColor)) return "#ffffff";
1686
- return this._isValidCanvasFillStyle(backgroundColor) ? backgroundColor : "#ffffff";
1687
- }
1688
- _isValidCanvasFillStyle(color) {
1689
- try {
1690
- if (typeof document === "undefined" || !document.createElement) return false;
1691
- const validationCanvas = document.createElement("canvas");
1692
- const context = validationCanvas.getContext && validationCanvas.getContext("2d");
1693
- if (!context) return false;
1694
- context.fillStyle = "#010203";
1695
- context.fillStyle = color;
1696
- if (context.fillStyle !== "#010203") return true;
1697
- context.fillStyle = "#040506";
1698
- context.fillStyle = color;
1699
- return context.fillStyle !== "#040506";
1700
- } catch {
1701
- return false;
1702
- }
1703
- }
1704
- _isTransparentCssColor(color) {
1705
- const normalizedColor = String(color || "").trim().toLowerCase();
1706
- if (!normalizedColor || normalizedColor === "transparent") return true;
1707
- const hexAlphaMatch = normalizedColor.match(/^#(?:[0-9a-f]{3}([0-9a-f])|[0-9a-f]{6}([0-9a-f]{2}))$/i);
1708
- if (hexAlphaMatch) {
1709
- const alpha = hexAlphaMatch[1] || hexAlphaMatch[2];
1710
- return alpha === "0" || alpha === "00";
1711
- }
1712
- const slashAlphaMatch = normalizedColor.match(/^(?:rgba?|hsla?)\([^)]*\/\s*([^)]+)\)$/i);
1713
- if (slashAlphaMatch) return this._isZeroCssAlpha(slashAlphaMatch[1]);
1714
- const commaAlphaMatch = normalizedColor.match(/^(?:rgba|hsla)\((.*)\)$/i);
1715
- if (commaAlphaMatch) {
1716
- const parts = commaAlphaMatch[1].split(",");
1717
- if (parts.length >= 4) return this._isZeroCssAlpha(parts[parts.length - 1]);
1718
- }
1719
- return false;
1720
- }
1721
- _isZeroCssAlpha(alphaValue) {
1722
- const normalizedAlpha = String(alphaValue || "").trim();
1723
- if (!normalizedAlpha) return false;
1724
- if (normalizedAlpha.endsWith("%")) return Number.parseFloat(normalizedAlpha) === 0;
1725
- return Number(normalizedAlpha) === 0;
1726
- }
1727
- _decodeBase64Payload(base64Payload) {
1728
- const payload = String(base64Payload || "");
1729
- if (!payload) throw new Error("Data URL base64 payload is empty");
1730
- if (typeof atob === "function") {
1731
- return Uint8Array.from(atob(payload), (char) => char.charCodeAt(0));
1732
- }
1733
- if (typeof Buffer !== "undefined" && typeof Buffer.from === "function") {
1734
- return new Uint8Array(Buffer.from(payload, "base64"));
1735
- }
1736
- throw new Error("Base64 decoding is unavailable");
1737
- }
1738
- _decodeDataUrlPayload(dataUrl) {
1739
- const match = String(dataUrl || "").match(/^data:([^;,]+);base64,([A-Za-z0-9+/=]+)$/i);
1740
- if (!match || !match[2]) {
1741
- throw new Error("Export produced an invalid or empty base64 data URL");
1742
- }
1743
- return this._decodeBase64Payload(match[2]);
1744
- }
1745
- /**
1746
- * Gets the top-left corner coordinates of the given object.
1747
- * Used for geometry calculations (e.g., scale, rotate).
1748
- *
1749
- * @param {Object} fabricObject - The object for which to get the top-left coordinates. Should support setCoords and getCoords/getBoundingRect methods.
1750
- * @returns {{x: number, y: number}} The top-left corner point as an object with x and y properties.
1751
- * @private
1752
- */
1753
- _getObjectTopLeftPoint(fabricObject) {
1754
- if (!fabricObject) return { x: 0, y: 0 };
1755
- fabricObject.setCoords();
1756
- const boundingRect = fabricObject.getBoundingRect(true, true);
1757
- return { x: boundingRect.left, y: boundingRect.top };
1758
- }
1759
- _getObjectCoordinateTopLeftPoint(fabricObject) {
1760
- if (!fabricObject) return { x: 0, y: 0 };
1761
- fabricObject.setCoords();
1762
- const coords = typeof fabricObject.getCoords === "function" ? fabricObject.getCoords() : null;
1763
- if (coords && coords.length) return coords[0];
1764
- return this._getObjectTopLeftPoint(fabricObject);
1765
- }
1766
- _getObjectOriginPoint(fabricObject, originX, originY) {
1767
- if (!fabricObject) return { x: 0, y: 0 };
1768
- if (typeof fabricObject.getPointByOrigin === "function") {
1769
- return fabricObject.getPointByOrigin(originX, originY);
1770
- }
1771
- return this._getObjectTopLeftPoint(fabricObject);
1772
- }
1773
- _translateObjectByCanvasOffset(fabricObject, deltaX, deltaY) {
1774
- if (!fabricObject) return;
1775
- if (typeof fabricObject.getCenterPoint === "function" && typeof fabricObject.setPositionByOrigin === "function") {
1776
- const center = fabricObject.getCenterPoint();
1777
- const nextCenter = new fabric.Point(center.x + deltaX, center.y + deltaY);
1778
- fabricObject.setPositionByOrigin(nextCenter, "center", "center");
1779
- } else {
1780
- fabricObject.set({
1781
- left: (fabricObject.left || 0) + deltaX,
1782
- top: (fabricObject.top || 0) + deltaY
1783
- });
1784
- }
1785
- fabricObject.setCoords();
1786
- }
1787
- /**
1788
- * Sets the object's origin at the specified origin point, keeping a reference point fixed in position.
1789
- *
1790
- * @param {Object} fabricObject - The object to modify. Should support set, setPositionByOrigin, and setCoords.
1791
- * @param {string} originX - The new originX ("left", "center", "right", etc.).
1792
- * @param {string} originY - The new originY ("top", "center", "bottom", etc.).
1793
- * @param {{x: number, y: number}} refPoint - The point to keep fixed while setting the new origins.
1794
- * @private
1795
- */
1796
- _setObjectOriginKeepingPosition(fabricObject, originX, originY, refPoint) {
1797
- if (!fabricObject || !refPoint || !fabricObject.setPositionByOrigin) return;
1798
- fabricObject.set({ originX, originY });
1799
- fabricObject.setPositionByOrigin(refPoint, originX, originY);
1800
- fabricObject.setCoords();
1801
- }
1802
- /**
1803
- * Moves the object so its bounding box aligns with the canvas's top-left corner (0, 0).
1804
- *
1805
- * @param {Object} fabricObject - The object to align.
1806
- * @private
1807
- */
1808
- _alignObjectBoundingBoxToCanvasTopLeft(fabricObject) {
1809
- if (!fabricObject) return;
1810
- fabricObject.setCoords();
1811
- const boundingRect = fabricObject.getBoundingRect(true, true);
1812
- const deltaX = boundingRect.left;
1813
- const deltaY = boundingRect.top;
1814
- fabricObject.set({ left: (fabricObject.left || 0) - deltaX, top: (fabricObject.top || 0) - deltaY });
1815
- fabricObject.setCoords();
1816
- this.canvas.renderAll();
1817
- }
1818
- /**
1819
- * Updates the canvas size to match the bounding box of the original image,
1820
- * ensuring that the canvas is always at least as large as its container.
1821
- * @private
1822
- */
1823
- _updateCanvasSizeToImageBounds() {
1824
- if (!this.originalImage) return;
1825
- this.originalImage.setCoords();
1826
- const imageBounds = this.originalImage.getBoundingRect(true, true);
1827
- const size = this._getScrollableCanvasSize(imageBounds.width, imageBounds.height);
1828
- this._setCanvasSizeInt(size.width, size.height);
1829
- }
1830
- /**
1831
- * Whether post-load edits should resize the canvas to keep transformed content visible.
1832
- *
1833
- * @returns {boolean} True when canvas bounds should follow edited image or mask bounds.
1834
- * @private
1835
- */
1836
- _shouldResizeCanvasToContentBounds() {
1837
- return !!(this.options.expandCanvasToImage || this.options.coverImageToCanvas || this.options.fitImageToCanvas);
1838
- }
1839
- /**
1840
- * Expands the canvas once so all provided objects remain visible after an edit.
1841
- *
1842
- * @param {Array<fabric.Object>} fabricObjects - Objects whose bounds should fit inside the canvas.
1843
- * @param {number} [padding=10] - Extra canvas space after the farthest object edge.
1844
- * @returns {void}
1845
- * @private
1846
- */
1847
- _expandCanvasToFitObjects(fabricObjects, padding = 10) {
1848
- if (!this.canvas || !Array.isArray(fabricObjects) || !fabricObjects.length || !this._shouldResizeCanvasToContentBounds()) return;
1849
- try {
1850
- const currentWidth = this.canvas.getWidth();
1851
- const currentHeight = this.canvas.getHeight();
1852
- let requiredWidth = currentWidth;
1853
- let requiredHeight = currentHeight;
1854
- const layoutMode = this._getImageLayoutMode();
1855
- const usesScrollableFitBounds = layoutMode === "fit" || layoutMode === "cover";
1856
- let contentWidth = 0;
1857
- let contentHeight = 0;
1858
- const includeObjectBounds = (fabricObject, objectPadding = 0) => {
1859
- if (!fabricObject) return;
1860
- if (typeof fabricObject.setCoords === "function") fabricObject.setCoords();
1861
- const boundingRect = fabricObject.getBoundingRect(true, true);
1862
- const right = Math.ceil(boundingRect.left + boundingRect.width + objectPadding);
1863
- const bottom = Math.ceil(boundingRect.top + boundingRect.height + objectPadding);
1864
- contentWidth = Math.max(contentWidth, right);
1865
- contentHeight = Math.max(contentHeight, bottom);
1866
- return { right, bottom };
1867
- };
1868
- fabricObjects.forEach((fabricObject) => {
1869
- const bounds = includeObjectBounds(fabricObject, padding);
1870
- if (!bounds) return;
1871
- requiredWidth = Math.max(requiredWidth, bounds.right);
1872
- requiredHeight = Math.max(requiredHeight, bounds.bottom);
1873
- });
1874
- if (usesScrollableFitBounds) {
1875
- if (this.originalImage) includeObjectBounds(this.originalImage, 0);
1876
- this.canvas.getObjects().forEach((object) => {
1877
- if (object && object.maskId) includeObjectBounds(object, padding);
1878
- });
1879
- const contentSize = this._getScrollableCanvasSize(
1880
- Math.max(1, contentWidth),
1881
- Math.max(1, contentHeight)
1882
- );
1883
- const newWidth2 = contentSize.hasHorizontal ? Math.max(currentWidth, contentSize.width) : contentSize.width;
1884
- const newHeight2 = contentSize.hasVertical ? Math.max(currentHeight, contentSize.height) : contentSize.height;
1885
- if (newWidth2 !== currentWidth || newHeight2 !== currentHeight) {
1886
- this._setCanvasSizeInt(newWidth2, newHeight2);
1887
- }
1888
- return;
1889
- }
1890
- let minWidth = 0;
1891
- let minHeight = 0;
1892
- if (this.containerElement) {
1893
- const viewport = this._getContainerViewportSize();
1894
- const safetyMargin = this._getScrollSafetyMargin();
1895
- minWidth = Math.max(1, viewport.width - safetyMargin);
1896
- minHeight = Math.max(1, viewport.height - safetyMargin);
1897
- }
1898
- const newWidth = Math.max(currentWidth, minWidth, requiredWidth);
1899
- const newHeight = Math.max(currentHeight, minHeight, requiredHeight);
1900
- if (newWidth !== currentWidth || newHeight !== currentHeight) {
1901
- this._setCanvasSizeInt(newWidth, newHeight);
1902
- }
1903
- } catch (error) {
1904
- this._reportWarning("expandCanvasToFitObjects: failed to expand canvas", error);
1905
- }
1906
- }
1907
- _captureImageDisplayBounds() {
1908
- if (!this.originalImage || !this.canvas) return null;
1909
- this.originalImage.setCoords();
1910
- const bounds = this.originalImage.getBoundingRect(true, true);
1911
- const width = Number(bounds && bounds.width);
1912
- const height = Number(bounds && bounds.height);
1913
- if (!Number.isFinite(width) || width <= 0 || !Number.isFinite(height) || height <= 0) return null;
1914
- return {
1915
- left: Number.isFinite(Number(bounds.left)) ? Number(bounds.left) : 0,
1916
- top: Number.isFinite(Number(bounds.top)) ? Number(bounds.top) : 0,
1917
- width,
1918
- height
1919
- };
1920
- }
1921
- _restoreImageDisplayBounds(displayBounds) {
1922
- if (!displayBounds || !this.originalImage || !this.canvas) return;
1923
- const imageWidth = Number(this.originalImage.width);
1924
- const imageHeight = Number(this.originalImage.height);
1925
- if (!Number.isFinite(imageWidth) || imageWidth <= 0 || !Number.isFinite(imageHeight) || imageHeight <= 0) return;
1926
- const scaleX = Number(displayBounds.width) / imageWidth;
1927
- const scaleY = Number(displayBounds.height) / imageHeight;
1928
- if (!Number.isFinite(scaleX) || scaleX <= 0 || !Number.isFinite(scaleY) || scaleY <= 0) return;
1929
- const left = Number(displayBounds.left) || 0;
1930
- const top = Number(displayBounds.top) || 0;
1931
- const requiredCanvasWidth = Math.max(1, Math.ceil(left + Number(displayBounds.width)));
1932
- const requiredCanvasHeight = Math.max(1, Math.ceil(top + Number(displayBounds.height)));
1933
- const currentCanvasWidth = Math.max(1, Math.round(Number(this.canvas.getWidth()) || 1));
1934
- const currentCanvasHeight = Math.max(1, Math.round(Number(this.canvas.getHeight()) || 1));
1935
- const layoutMode = this._getImageLayoutMode();
1936
- if (layoutMode === "fit" || layoutMode === "cover") {
1937
- const contentSize = this._getScrollableCanvasSize(requiredCanvasWidth, requiredCanvasHeight);
1938
- if (contentSize.width !== currentCanvasWidth || contentSize.height !== currentCanvasHeight) {
1939
- this._setCanvasSizeInt(contentSize.width, contentSize.height);
1940
- }
1941
- } else if (requiredCanvasWidth > currentCanvasWidth || requiredCanvasHeight > currentCanvasHeight) {
1942
- this._setCanvasSizeInt(
1943
- Math.max(currentCanvasWidth, requiredCanvasWidth),
1944
- Math.max(currentCanvasHeight, requiredCanvasHeight)
1945
- );
1946
- }
1947
- this.originalImage.set({
1948
- originX: "left",
1949
- originY: "top",
1950
- left,
1951
- top,
1952
- scaleX,
1953
- scaleY
1954
- });
1955
- this.originalImage.setCoords();
1956
- this.baseImageScale = scaleX;
1957
- this.currentScale = 1;
1958
- this.currentRotation = Number(this.originalImage.angle) || 0;
1959
- this._updateInputs();
1960
- this.canvas.renderAll();
1961
- }
1962
- /**
1963
- * Scales the original image by a given factor, with animation.
1964
- * Returns a promise that resolves when the scale animation is complete.
1965
- * @param {number} factor - The scaling factor (will be clamped between `options.minScale` and `options.maxScale`).
1966
- * @returns {Promise<void>} Promise that resolves once the scaling animation finishes.
1967
- * @public
1968
- */
1969
- scaleImage(factor, options = {}) {
1970
- try {
1971
- this._assertCanQueueAnimation("scaleImage", options);
1972
- } catch (error) {
1973
- return Promise.reject(error);
1974
- }
1975
- return this.animationQueue.add(async () => {
1976
- const operationToken = this._beginBusyOperation("scaleImage");
1977
- try {
1978
- await this._scaleImageImpl(factor, this._withInternalOperationOptions(operationToken, options));
1979
- } finally {
1980
- this._endBusyOperation(operationToken);
1981
- }
1982
- }).finally(() => {
1983
- if (!this._disposed && this.canvas) this._updateUI();
1984
- });
1985
- }
1986
- _getInternalOperationToken(options) {
1987
- return options && options[INTERNAL_OPERATION_TOKEN];
1988
- }
1989
- _isOwnInternalOperation(options) {
1990
- const token = this._getInternalOperationToken(options);
1991
- return !!token && token === this._activeOperationToken;
1992
- }
1993
- _beginBusyOperation(operationName) {
1994
- const token = Symbol(operationName);
1995
- this._activeOperationName = operationName;
1996
- this._activeOperationToken = token;
1997
- this._updateUI();
1998
- return token;
1999
- }
2000
- _endBusyOperation(token) {
2001
- if (token && token === this._activeOperationToken) {
2002
- this._activeOperationName = null;
2003
- this._activeOperationToken = null;
2004
- this._updateUI();
2005
- }
2006
- }
2007
- _withInternalOperationOptions(token, options = {}) {
2008
- return {
2009
- ...options,
2010
- [INTERNAL_OPERATION_TOKEN]: token
2011
- };
2012
- }
2013
- _assertEditorAvailable(operationName) {
2014
- if (this._disposed || !this.canvas) throw new Error(`${operationName} cannot run after the editor has been disposed`);
2015
- }
2016
- _isCropModeAllowedOperation(operationName) {
2017
- return operationName === "applyCrop" || operationName === "cancelCrop";
2018
- }
2019
- _assertIdleForOperation(operationName, options = {}) {
2020
- this._assertEditorAvailable(operationName);
2021
- const isOwnInternalOperation = this._isOwnInternalOperation(options);
2022
- if (this._cropMode && !this._isCropModeAllowedOperation(operationName) && !isOwnInternalOperation) {
2023
- throw new Error(`${operationName} cannot run while crop mode is active`);
2024
- }
2025
- if ((this.isAnimating || this.animationQueue && this.animationQueue.isBusy()) && !isOwnInternalOperation) {
2026
- throw new Error(`${operationName} cannot run while an animation is running`);
2027
- }
2028
- if (this._isLoading && !isOwnInternalOperation) {
2029
- throw new Error(`${operationName} cannot run while an image is loading`);
2030
- }
2031
- if (this._activeOperationToken && !isOwnInternalOperation) {
2032
- throw new Error(`${operationName} cannot run while ${this._activeOperationName || "another operation"} is running`);
2033
- }
2034
- }
2035
- _assertCanQueueAnimation(operationName, options = {}) {
2036
- this._assertEditorAvailable(operationName);
2037
- const isOwnInternalOperation = this._isOwnInternalOperation(options);
2038
- if (this._cropMode && !this._isCropModeAllowedOperation(operationName) && !isOwnInternalOperation) {
2039
- throw new Error(`${operationName} cannot run while crop mode is active`);
2040
- }
2041
- if (this._isLoading && !isOwnInternalOperation) {
2042
- throw new Error(`${operationName} cannot run while an image is loading`);
2043
- }
2044
- if (this._activeOperationToken && !isOwnInternalOperation) {
2045
- throw new Error(`${operationName} cannot run while ${this._activeOperationName || "another operation"} is running`);
2046
- }
2047
- }
2048
- _canMutateNow(operationName, options = {}) {
2049
- try {
2050
- this._assertIdleForOperation(operationName, options);
2051
- return true;
2052
- } catch (error) {
2053
- this._reportError(`${operationName} blocked`, error);
2054
- return false;
2055
- }
2056
- }
2057
- _rejectActiveAnimations(reason) {
2058
- const error = reason instanceof Error ? reason : new Error(String(reason || "Animation cancelled"));
2059
- this._activeAnimationRejectors.forEach((reject) => {
2060
- try {
2061
- reject(error);
2062
- } catch (rejectError) {
2063
- void rejectError;
2064
- }
2065
- });
2066
- this._activeAnimationRejectors.clear();
2067
- }
2068
- _animateFabricProperty(fabricObject, property, value) {
2069
- return new Promise((resolve, reject) => {
2070
- if (this._disposed || !this.canvas || !fabricObject) {
2071
- reject(new Error("Animation cannot start after editor disposal"));
2072
- return;
2073
- }
2074
- let isSettled = false;
2075
- const duration = Math.max(0, Number(this.options.animationDuration) || 0);
2076
- const timeoutMs = Math.max(1e3, duration + 1e3);
2077
- let timerId;
2078
- const settle = (callback) => {
2079
- if (isSettled) return;
2080
- isSettled = true;
2081
- clearTimeout(timerId);
2082
- this._activeAnimationRejectors.delete(reject);
2083
- callback();
2084
- };
2085
- this._activeAnimationRejectors.add(reject);
2086
- timerId = setTimeout(() => {
2087
- settle(() => reject(new Error(`Animation timed out while changing ${property}`)));
2088
- }, timeoutMs);
2089
- try {
2090
- fabricObject.animate(property, value, {
2091
- duration,
2092
- onChange: () => {
2093
- if (!this._disposed && this.canvas) this.canvas.renderAll();
2094
- },
2095
- onComplete: () => settle(resolve)
2096
- });
2097
- } catch (error) {
2098
- settle(() => reject(error));
2099
- }
2100
- });
2101
- }
2102
- /**
2103
- * Scales the original image by a given factor, with animation.
2104
- * Returns a promise that resolves when the scale animation is complete.
2105
- * @param {number} factor - The scaling factor (will be clamped between `options.minScale` and `options.maxScale`).
2106
- * @returns {Promise<void>} Promise that resolves once the scaling animation finishes.
2107
- * @private
2108
- */
2109
- async _scaleImageImpl(factor, options = {}) {
2110
- if (!this.originalImage || this._disposed) return;
2111
- if (this.isAnimating) return;
2112
- const numericFactor = Number(factor);
2113
- if (!Number.isFinite(numericFactor)) return;
2114
- const saveHistory = options.saveHistory !== false;
2115
- let didStartAnimation = false;
2116
- try {
2117
- factor = Math.max(this.options.minScale, Math.min(this.options.maxScale, numericFactor));
2118
- this.currentScale = factor;
2119
- this.isAnimating = true;
2120
- didStartAnimation = true;
2121
- this._updateUI();
2122
- const targetScale = this.baseImageScale * factor;
2123
- const topLeft = this._getObjectTopLeftPoint(this.originalImage);
2124
- this._setObjectOriginKeepingPosition(this.originalImage, "left", "top", topLeft);
2125
- await Promise.all([
2126
- this._animateFabricProperty(this.originalImage, "scaleX", targetScale),
2127
- this._animateFabricProperty(this.originalImage, "scaleY", targetScale)
2128
- ]);
2129
- if (this._disposed || !this.canvas || !this.originalImage) throw new Error("Editor was disposed during scale animation");
2130
- this.originalImage.set({ scaleX: targetScale, scaleY: targetScale });
2131
- this.originalImage.setCoords();
2132
- if (this._shouldResizeCanvasToContentBounds()) {
2133
- this._updateCanvasSizeToImageBounds();
2134
- }
2135
- this._alignObjectBoundingBoxToCanvasTopLeft(this.originalImage);
2136
- this.canvas.getObjects().forEach((object) => {
2137
- if (object.maskId) this._syncMaskLabel(object);
2138
- });
2139
- this._updateInputs();
2140
- if (saveHistory) this.saveState(options);
2141
- } finally {
2142
- if (didStartAnimation) {
2143
- this.isAnimating = false;
2144
- this._updateInputs();
2145
- this._updateUI();
2146
- }
2147
- }
2148
- }
2149
- /**
2150
- * Rotates the original image by a given number of degrees, with animation.
2151
- * Returns a promise that resolves when the rotation animation is complete.
2152
- * @param {number} degrees - The angle in degrees to rotate the image.
2153
- * @returns {Promise<void>} Promise that resolves once the rotation animation finishes.
2154
- * @public
2155
- */
2156
- rotateImage(degrees, options = {}) {
2157
- try {
2158
- this._assertCanQueueAnimation("rotateImage", options);
2159
- } catch (error) {
2160
- return Promise.reject(error);
2161
- }
2162
- return this.animationQueue.add(async () => {
2163
- const operationToken = this._beginBusyOperation("rotateImage");
2164
- try {
2165
- await this._rotateImageImpl(degrees, this._withInternalOperationOptions(operationToken, options));
2166
- } finally {
2167
- this._endBusyOperation(operationToken);
2168
- }
2169
- }).finally(() => {
2170
- if (!this._disposed && this.canvas) this._updateUI();
2171
- });
2172
- }
2173
- /**
2174
- * Rotates the original image by a given number of degrees, with animation.
2175
- * Returns a promise that resolves when the rotation animation is complete.
2176
- * @param {number} degrees - The angle in degrees to rotate the image.
2177
- * @returns {Promise<void>} Promise that resolves once the rotation animation finishes.
2178
- * @private
2179
- */
2180
- async _rotateImageImpl(degrees, options = {}) {
2181
- if (!this.originalImage || this._disposed) return;
2182
- if (this.isAnimating) return;
2183
- const numericDegrees = Number(degrees);
2184
- if (!Number.isFinite(numericDegrees)) return;
2185
- const saveHistory = options.saveHistory !== false;
2186
- const image = this.originalImage;
2187
- const previousOriginX = image.originX || "left";
2188
- const previousOriginY = image.originY || "top";
2189
- const previousOriginPoint = this._getObjectOriginPoint(image, previousOriginX, previousOriginY);
2190
- let didStartAnimation = false;
2191
- let didCompleteRotation = false;
2192
- try {
2193
- degrees = numericDegrees;
2194
- this.currentRotation = degrees;
2195
- this.isAnimating = true;
2196
- didStartAnimation = true;
2197
- this._updateUI();
2198
- const center = image.getCenterPoint();
2199
- this._setObjectOriginKeepingPosition(image, "center", "center", center);
2200
- await this._animateFabricProperty(image, "angle", degrees);
2201
- if (this._disposed || !this.canvas || !this.originalImage) throw new Error("Editor was disposed during rotation animation");
2202
- this.originalImage.set("angle", degrees);
2203
- this.originalImage.setCoords();
2204
- if (this._shouldResizeCanvasToContentBounds()) {
2205
- this._updateCanvasSizeToImageBounds();
2206
- }
2207
- this._alignObjectBoundingBoxToCanvasTopLeft(this.originalImage);
2208
- const newTopLeft = this._getObjectCoordinateTopLeftPoint(this.originalImage);
2209
- this._setObjectOriginKeepingPosition(this.originalImage, "left", "top", newTopLeft);
2210
- this.canvas.getObjects().forEach((object) => {
2211
- if (object.maskId) this._syncMaskLabel(object);
2212
- });
2213
- this._updateInputs();
2214
- if (saveHistory) this.saveState(options);
2215
- didCompleteRotation = true;
2216
- } finally {
2217
- if (!didCompleteRotation && !this._disposed && image) {
2218
- this._setObjectOriginKeepingPosition(image, previousOriginX, previousOriginY, previousOriginPoint);
2219
- }
2220
- if (didStartAnimation) {
2221
- this.isAnimating = false;
2222
- this._updateInputs();
2223
- this._updateUI();
2224
- }
2225
- }
2226
- }
2227
- /**
2228
- * Resets the image transform: scales to 1 and rotates to 0 degrees.
2229
- *
2230
- * @returns {Promise<void>} Resolves when the reset history transition has been recorded.
2231
- * @public
2232
- */
2233
- resetImageTransform() {
2234
- if (!this.originalImage) return Promise.resolve();
2235
- try {
2236
- this._assertCanQueueAnimation("resetImageTransform");
2237
- } catch (error) {
2238
- return Promise.reject(error);
2239
- }
2240
- return this.animationQueue.add(async () => {
2241
- const operationToken = this._beginBusyOperation("resetImageTransform");
2242
- const before = this._lastSnapshot || this._captureCanvasStateOrThrow("resetImageTransform");
2243
- try {
2244
- await this._scaleImageImpl(1, this._withInternalOperationOptions(operationToken, { saveHistory: false }));
2245
- await this._rotateImageImpl(0, this._withInternalOperationOptions(operationToken, { saveHistory: false }));
2246
- const after = this._captureCanvasStateOrThrow("resetImageTransform");
2247
- this._pushStateTransition(before, after);
2248
- } catch (error) {
2249
- try {
2250
- await this.loadFromState(before, this._withInternalOperationOptions(operationToken));
2251
- } catch (restoreError) {
2252
- this._reportError("resetImageTransform rollback failed", restoreError);
2253
- }
2254
- throw error;
2255
- } finally {
2256
- this._endBusyOperation(operationToken);
2257
- }
2258
- }).finally(() => {
2259
- if (!this._disposed && this.canvas) this._updateUI();
2260
- }).catch((error) => {
2261
- this._reportError("resetImageTransform() failed", error);
2262
- throw error;
2263
- });
2264
- }
2265
- /**
2266
- * Backward-compatible alias for {@link ImageEditor#resetImageTransform}.
2267
- *
2268
- * @deprecated Use resetImageTransform() instead. This alias will be removed in v2.0.0.
2269
- * @returns {Promise<void>} Resolves when the image transform reset is complete.
2270
- */
2271
- reset() {
2272
- return this.resetImageTransform();
2273
- }
2274
- /**
2275
- * Restores a serialized canvas state and rebinds editor-specific mask/image metadata.
2276
- *
2277
- * @param {string|Object} serializedState - State returned by `_serializeCanvasState()` as a JSON string or object.
2278
- * @returns {Promise<void>} Resolves after Fabric has loaded the state and UI state has been refreshed.
2279
- * @public
2280
- */
2281
- loadFromState(serializedState, options = {}) {
2282
- if (!serializedState || !this.canvas || this._disposed) return Promise.resolve();
2283
- try {
2284
- this._assertIdleForOperation("loadFromState", options);
2285
- } catch (error) {
2286
- return Promise.reject(error);
2287
- }
2288
- if (this._cropMode || this._cropRect) {
2289
- this._removeCropRect();
2290
- this._restoreCropObjectState();
2291
- this._cropMode = false;
2292
- if (this._prevSelectionSetting !== void 0 && this.canvas) {
2293
- this.canvas.selection = !!this._prevSelectionSetting;
2294
- }
2295
- this._prevSelectionSetting = void 0;
2296
- }
2297
- return new Promise((resolve, reject) => {
2298
- try {
2299
- const state = typeof serializedState === "string" ? JSON.parse(serializedState) : serializedState;
2300
- const editorMetadata = state && state.imageEditorMetadata ? state.imageEditorMetadata : null;
2301
- const restoredCanvasWidth = Number(editorMetadata && editorMetadata.canvasWidth);
2302
- const restoredCanvasHeight = Number(editorMetadata && editorMetadata.canvasHeight);
2303
- const hasRestoredCanvasSize = Number.isFinite(restoredCanvasWidth) && restoredCanvasWidth > 0 && Number.isFinite(restoredCanvasHeight) && restoredCanvasHeight > 0;
2304
- if (editorMetadata && Object.prototype.hasOwnProperty.call(editorMetadata, "version") && Number(editorMetadata.version) !== 1) {
2305
- this._reportWarning(`loadFromState: unsupported editor metadata version ${editorMetadata.version}`);
2306
- }
2307
- const finishLoad = async () => {
2308
- try {
2309
- if (this._disposed || !this.canvas) {
2310
- reject(new Error("Editor was disposed while loading state"));
2311
- return;
2312
- }
2313
- await this._waitForFabricImagesReady(this.canvas.getObjects());
2314
- if (this._disposed || !this.canvas) {
2315
- reject(new Error("Editor was disposed while loading state"));
2316
- return;
2317
- }
2318
- this._hideAllMaskLabels();
2319
- const canvasObjects = this.canvas.getObjects();
2320
- this.originalImage = canvasObjects.find((object) => object.type === "image" && !object.maskId) || null;
2321
- if (this.originalImage) {
2322
- this.originalImage.set({ originX: "left", originY: "top", selectable: false, evented: false, hasControls: false, hoverCursor: "default" });
2323
- this.canvas.sendToBack(this.originalImage);
2324
- const restoredBaseScale = Number(editorMetadata && editorMetadata.baseImageScale);
2325
- const restoredCurrentScale = Number(editorMetadata && editorMetadata.currentScale);
2326
- const restoredCurrentRotation = Number(editorMetadata && editorMetadata.currentRotation);
2327
- if (Number.isFinite(restoredBaseScale) && restoredBaseScale > 0) {
2328
- this.baseImageScale = restoredBaseScale;
2329
- }
2330
- if (Number.isFinite(restoredCurrentScale) && restoredCurrentScale > 0) {
2331
- this.currentScale = restoredCurrentScale;
2332
- } else {
2333
- const baseScale = Number(this.baseImageScale) || 1;
2334
- const imageScale = Number(this.originalImage.scaleX) || baseScale;
2335
- this.currentScale = imageScale / baseScale;
2336
- }
2337
- this.currentRotation = Number.isFinite(restoredCurrentRotation) ? restoredCurrentRotation : Number(this.originalImage.angle) || 0;
2338
- } else {
2339
- this.baseImageScale = 1;
2340
- this.currentScale = 1;
2341
- this.currentRotation = 0;
2342
- }
2343
- if (hasRestoredCanvasSize) {
2344
- this._setCanvasSizeInt(restoredCanvasWidth, restoredCanvasHeight);
2345
- } else if (this.originalImage && this._shouldResizeCanvasToContentBounds()) {
2346
- this._updateCanvasSizeToImageBounds();
2347
- }
2348
- const masks = canvasObjects.filter((object) => object.maskId);
2349
- masks.forEach((mask) => {
2350
- this._restoreMaskControls(mask);
2351
- this._rebindMaskEvents(mask);
2352
- mask.set(this._getMaskNormalStyle(mask));
2353
- });
2354
- const restoredMaskCounter = Number(editorMetadata && editorMetadata.maskCounter);
2355
- const maxMaskId = masks.reduce((max, mask) => Math.max(max, mask.maskId), 0);
2356
- this.maskCounter = Number.isFinite(restoredMaskCounter) && restoredMaskCounter >= maxMaskId ? Math.floor(restoredMaskCounter) : maxMaskId;
2357
- this._lastMask = masks.length ? masks[masks.length - 1] : null;
2358
- if (!this._lastMask) {
2359
- this._lastMaskInitialLeft = null;
2360
- this._lastMaskInitialTop = null;
2361
- this._lastMaskInitialWidth = null;
2362
- }
2363
- this.isImageLoadedToCanvas = !!this.originalImage;
2364
- this.canvas.renderAll();
2365
- this._updateInputs();
2366
- this._updateMaskList();
2367
- this._updatePlaceholderStatus();
2368
- this._lastSnapshot = this._serializeCanvasState();
2369
- this._updateUI();
2370
- resolve();
2371
- } catch (callbackError) {
2372
- this._reportError("loadFromState() failed", callbackError);
2373
- reject(callbackError);
2374
- }
2375
- };
2376
- this.canvas.loadFromJSON(state, () => {
2377
- void finishLoad();
2378
- });
2379
- } catch (error) {
2380
- this._reportError("loadFromState() failed", error);
2381
- reject(error);
2382
- }
2383
- });
2384
- }
2385
- async _waitForFabricImagesReady(canvasObjects) {
2386
- const imageObjects = (canvasObjects || []).filter((object) => object && object.type === "image");
2387
- await Promise.all(imageObjects.map((object) => this._waitForImageElementReady(
2388
- typeof object.getElement === "function" ? object.getElement() : object._element
2389
- )));
2390
- }
2391
- _waitForImageElementReady(imageElement) {
2392
- if (!imageElement) return Promise.resolve();
2393
- const hasLoadedDimensions = (Number(imageElement.naturalWidth) > 0 || Number(imageElement.width) > 0) && (Number(imageElement.naturalHeight) > 0 || Number(imageElement.height) > 0);
2394
- if (hasLoadedDimensions) return Promise.resolve();
2395
- if (imageElement.complete) return Promise.reject(new Error("Image could not be loaded while restoring state"));
2396
- return new Promise((resolve, reject) => {
2397
- let isSettled = false;
2398
- let timerId;
2399
- const settle = (callback) => {
2400
- if (isSettled) return;
2401
- isSettled = true;
2402
- clearTimeout(timerId);
2403
- if (typeof imageElement.removeEventListener === "function") {
2404
- imageElement.removeEventListener("load", handleLoad);
2405
- imageElement.removeEventListener("error", handleError);
2406
- } else {
2407
- imageElement.onload = null;
2408
- imageElement.onerror = null;
2409
- }
2410
- callback();
2411
- };
2412
- const handleLoad = () => {
2413
- const didLoad = (Number(imageElement.naturalWidth) > 0 || Number(imageElement.width) > 0) && (Number(imageElement.naturalHeight) > 0 || Number(imageElement.height) > 0);
2414
- settle(() => {
2415
- if (didLoad) {
2416
- resolve();
2417
- } else {
2418
- reject(new Error("Image could not be loaded while restoring state"));
2419
- }
2420
- });
2421
- };
2422
- const handleError = (error) => settle(() => reject(error instanceof Error ? error : new Error("Image could not be loaded while restoring state")));
2423
- timerId = setTimeout(() => {
2424
- settle(() => reject(new Error("Image load timed out while restoring state")));
2425
- }, this._getSafeTimeoutMs(this.options.imageLoadTimeoutMs));
2426
- if (typeof imageElement.addEventListener === "function") {
2427
- imageElement.addEventListener("load", handleLoad, { once: true });
2428
- imageElement.addEventListener("error", handleError, { once: true });
2429
- } else {
2430
- imageElement.onload = handleLoad;
2431
- imageElement.onerror = handleError;
2432
- }
2433
- });
2434
- }
2435
- /**
2436
- * Saves the current editable canvas state as an undoable history transition.
2437
- *
2438
- * Labels are hidden before serialization because labels are UI overlays, while mask metadata is kept on
2439
- * mask objects and restored by `loadFromState()`.
2440
- *
2441
- * @returns {void}
2442
- * @public
2443
- */
2444
- saveState(options = {}) {
2445
- if (!this.canvas) return;
2446
- try {
2447
- this._assertIdleForOperation("saveState", options);
2448
- } catch (error) {
2449
- this._reportError("saveState blocked", error);
2450
- this._updateUI();
2451
- return;
2452
- }
2453
- try {
2454
- const after = this._captureCanvasStateOrThrow("saveState");
2455
- const before = this._lastSnapshot || after;
2456
- if (after === before) return;
2457
- let executedOnce = false;
2458
- const command = new Command(
2459
- (commandOptions = {}) => {
2460
- if (executedOnce) {
2461
- return this.loadFromState(after, commandOptions);
2462
- }
2463
- executedOnce = true;
2464
- return void 0;
2465
- },
2466
- (commandOptions = {}) => this.loadFromState(before, commandOptions)
2467
- );
2468
- this.historyManager.execute(command);
2469
- this._lastSnapshot = after;
2470
- } catch (error) {
2471
- this._reportWarning("saveState: failed to save canvas snapshot", error);
2472
- } finally {
2473
- this._updateUI();
2474
- }
2475
- }
2476
- /**
2477
- * Pushes a precomputed before/after state transition into history.
2478
- *
2479
- * Use this for operations such as crop and merge that build their snapshots around asynchronous image
2480
- * loading, where the "after" state is already applied before the history command is recorded.
2481
- *
2482
- * @param {string} before - Serialized state before the operation.
2483
- * @param {string} after - Serialized state after the operation.
2484
- * @returns {void}
2485
- * @private
2486
- */
2487
- _pushStateTransition(before, after) {
2488
- if (!before || !after) {
2489
- this._reportWarning("History transition skipped because a canvas snapshot is unavailable");
2490
- return;
2491
- }
2492
- if (before === after) return;
2493
- if (!this.historyManager) this.historyManager = new HistoryManager(this.maxHistorySize || 50);
2494
- const command = new Command(
2495
- (commandOptions = {}) => this.loadFromState(after, commandOptions),
2496
- (commandOptions = {}) => this.loadFromState(before, commandOptions)
2497
- );
2498
- this.historyManager.push(command);
2499
- this._lastSnapshot = after;
2500
- this._updateUI();
2501
- }
2502
- /**
2503
- * Undo the last state change, if possible.
2504
- *
2505
- * @returns {Promise<void>} Resolves after the history manager finishes the queued undo.
2506
- * @public
2507
- */
2508
- undo() {
2509
- try {
2510
- this._assertIdleForOperation("undo");
2511
- } catch (error) {
2512
- return Promise.reject(error);
2513
- }
2514
- const operationToken = this._beginBusyOperation("undo");
2515
- return this.historyManager.undo(this._withInternalOperationOptions(operationToken)).then(() => {
2516
- this._updateUI();
2517
- }).finally(() => {
2518
- this._endBusyOperation(operationToken);
2519
- }).catch((error) => {
2520
- this._reportError("undo failed", error);
2521
- throw error;
2522
- });
2523
- }
2524
- /**
2525
- * Redo the next state change, if possible.
2526
- *
2527
- * @returns {Promise<void>} Resolves after the history manager finishes the queued redo.
2528
- * @public
2529
- */
2530
- redo() {
2531
- try {
2532
- this._assertIdleForOperation("redo");
2533
- } catch (error) {
2534
- return Promise.reject(error);
2535
- }
2536
- const operationToken = this._beginBusyOperation("redo");
2537
- return this.historyManager.redo(this._withInternalOperationOptions(operationToken)).then(() => {
2538
- this._updateUI();
2539
- }).finally(() => {
2540
- this._endBusyOperation(operationToken);
2541
- }).catch((error) => {
2542
- this._reportError("redo failed", error);
2543
- throw error;
2544
- });
2545
- }
2546
- _rebindMaskEvents(mask) {
2547
- if (!mask) return;
2548
- this._cleanupMaskEvents(mask);
2549
- const metadata = {};
2550
- if (!Number.isFinite(Number(mask.originalAlpha))) {
2551
- metadata.originalAlpha = Number.isFinite(Number(mask.opacity)) ? Number(mask.opacity) : 0.5;
2552
- }
2553
- if (!mask.originalStroke) metadata.originalStroke = mask.stroke || "#ccc";
2554
- if (!Number.isFinite(Number(mask.originalStrokeWidth))) {
2555
- metadata.originalStrokeWidth = Number.isFinite(Number(mask.strokeWidth)) ? Number(mask.strokeWidth) : 1;
2556
- }
2557
- if (Object.keys(metadata).length) mask.set(metadata);
2558
- const mouseover = () => {
2559
- const opacity = Number(mask.originalAlpha);
2560
- mask.set({
2561
- stroke: "#ff5500",
2562
- strokeWidth: 2,
2563
- opacity: Math.min((Number.isFinite(opacity) ? opacity : 0.5) + 0.2, 1)
2564
- });
2565
- if (mask.canvas) mask.canvas.requestRenderAll();
2566
- };
2567
- const mouseout = () => {
2568
- mask.set(this._getMaskNormalStyle(mask));
2569
- if (mask.canvas) mask.canvas.requestRenderAll();
2570
- };
2571
- mask.on("mouseover", mouseover);
2572
- mask.on("mouseout", mouseout);
2573
- mask.__imageEditorMaskHandlers = { mouseover, mouseout };
2574
- }
2575
- _cleanupMaskEvents(mask) {
2576
- if (!mask || !mask.__imageEditorMaskHandlers) return;
2577
- try {
2578
- if (typeof mask.off === "function") {
2579
- mask.off("mouseover", mask.__imageEditorMaskHandlers.mouseover);
2580
- mask.off("mouseout", mask.__imageEditorMaskHandlers.mouseout);
2581
- }
2582
- } catch (error) {
2583
- this._reportWarning("Mask event cleanup failed", error);
2584
- }
2585
- try {
2586
- delete mask.__imageEditorMaskHandlers;
2587
- } catch (error) {
2588
- this._reportWarning("Mask event metadata cleanup failed", error);
2589
- }
2590
- }
2591
- /**
2592
- * Creates a mask and adds it to the canvas.
2593
- *
2594
- * Placement is based on explicit `left`/`top` values when provided; otherwise each new mask is placed
2595
- * after the previously created mask. Fabric object properties are applied through `set()` and `setCoords()`
2596
- * so controls and hit testing stay in sync with Fabric 5.x behavior.
2597
- *
2598
- * @param {Object} [config={}] - Optional mask configuration overrides.
2599
- * @param {string} [config.shape='rect'] - Mask shape: `rect`, `circle`, `ellipse`, `polygon`, or a custom shape handled by `fabricGenerator`.
2600
- * @param {Array<{x:number,y:number}>|Array<Array<number>>} [config.points] - Polygon points.
2601
- * @param {number|string|MaskValueResolver} [config.width] - Width in pixels, percentage string, or resolver callback.
2602
- * @param {number|string|MaskValueResolver} [config.height] - Height in pixels, percentage string, or resolver callback.
2603
- * @param {number|string|MaskValueResolver} [config.radius] - Circle radius in pixels, percentage string, or resolver callback.
2604
- * @param {number|string|MaskValueResolver} [config.rx] - Ellipse horizontal radius or rectangle corner radius.
2605
- * @param {number|string|MaskValueResolver} [config.ry] - Ellipse vertical radius or rectangle corner radius.
2606
- * @param {number|string|MaskValueResolver} [config.left] - Left position in pixels, percentage string, or resolver callback.
2607
- * @param {number|string|MaskValueResolver} [config.top] - Top position in pixels, percentage string, or resolver callback.
2608
- * @param {number} [config.angle=0] - Rotation angle in degrees.
2609
- * @param {string} [config.color='rgba(0,0,0,0.5)'] - Fill color.
2610
- * @param {number} [config.alpha=0.5] - Opacity from 0 to 1.
2611
- * @param {boolean} [config.selectable=true] - Whether the mask can be selected.
2612
- * @param {boolean} [config.hasControls=true] - Whether Fabric transform controls are shown.
2613
- * @param {Object} [config.styles] - Additional Fabric style properties, such as `stroke` or `strokeDashArray`.
2614
- * @param {MaskFabricGenerator} [config.fabricGenerator] - Factory callback that returns a custom Fabric object.
2615
- * @param {MaskCreateCallback} [config.onCreate] - Callback invoked after the mask is added to the canvas.
2616
- * @returns {fabric.Object|null} The created mask object, or null if the canvas is not initialized.
2617
- * @public
2618
- */
2619
- createMask(config = {}) {
2620
- if (!this.canvas) return null;
2621
- if (!this._canMutateNow("createMask")) return null;
2622
- const shapeType = config.shape || "rect";
2623
- const maskConfig = {
2624
- shape: shapeType,
2625
- width: this.options.defaultMaskWidth,
2626
- height: this.options.defaultMaskHeight,
2627
- color: "rgba(0,0,0,0.5)",
2628
- alpha: 0.5,
2629
- gap: 5,
2630
- left: void 0,
2631
- top: void 0,
2632
- angle: 0,
2633
- selectable: true,
2634
- ...config
2635
- };
2636
- const firstOffset = 10;
2637
- let left;
2638
- let top;
2639
- const getCanvasBasis = (axis) => {
2640
- const canvasWidth = this.canvas ? this.canvas.getWidth() : 0;
2641
- const canvasHeight = this.canvas ? this.canvas.getHeight() : 0;
2642
- if (axis === "height") return canvasHeight;
2643
- if (axis === "min") return Math.min(canvasWidth, canvasHeight);
2644
- return canvasWidth;
2645
- };
2646
- const resolveValue = (value, fallback, axis = "width") => {
2647
- if (typeof value === "function")
2648
- return value(this.canvas, this.options);
2649
- if (typeof value === "string" && value.endsWith("%")) {
2650
- const percent = Number.parseFloat(value) / 100;
2651
- if (!Number.isFinite(percent)) return fallback;
2652
- return Math.floor(getCanvasBasis(axis) * percent);
2653
- }
2654
- return value != null ? value : fallback;
2655
- };
2656
- const rejectInvalidMask = (message, error = null) => {
2657
- this._reportWarning(`createMask: ${message}`, error);
2658
- return null;
2659
- };
2660
- const resolveNumber = (value, fallback, axis, fieldName, constraints = {}) => {
2661
- const resolvedValue = resolveValue(value, fallback, axis);
2662
- const numericValue = Number(resolvedValue);
2663
- if (!Number.isFinite(numericValue)) {
2664
- throw new Error(`${fieldName} must be a finite number`);
2665
- }
2666
- if (constraints.positive && numericValue <= 0) {
2667
- throw new Error(`${fieldName} must be greater than 0`);
2668
- }
2669
- if (constraints.nonNegative && numericValue < 0) {
2670
- throw new Error(`${fieldName} must be 0 or greater`);
2671
- }
2672
- return numericValue;
2673
- };
2674
- try {
2675
- maskConfig.gap = resolveNumber(maskConfig.gap, 5, "width", "gap", { nonNegative: true });
2676
- maskConfig.width = resolveNumber(maskConfig.width, this.options.defaultMaskWidth, "width", "width", { positive: true });
2677
- maskConfig.height = resolveNumber(maskConfig.height, this.options.defaultMaskHeight, "height", "height", { positive: true });
2678
- maskConfig.angle = resolveNumber(maskConfig.angle, 0, "width", "angle");
2679
- maskConfig.alpha = Math.max(0, Math.min(1, resolveNumber(maskConfig.alpha, 0.5, "width", "alpha")));
2680
- if (maskConfig.left === void 0 && this._lastMask) {
2681
- const previousMask = this._lastMask;
2682
- if (typeof previousMask.setCoords === "function") previousMask.setCoords();
2683
- const previousBounds = typeof previousMask.getBoundingRect === "function" ? previousMask.getBoundingRect(true, true) : { left: previousMask.left || firstOffset, top: previousMask.top || firstOffset, width: previousMask.width || 0 };
2684
- left = Math.round(previousBounds.left + previousBounds.width + maskConfig.gap);
2685
- top = Math.round(previousBounds.top ?? firstOffset);
2686
- } else {
2687
- left = resolveNumber(maskConfig.left, firstOffset, "width", "left");
2688
- top = resolveNumber(maskConfig.top, firstOffset, "height", "top");
2689
- }
2690
- } catch (error) {
2691
- return rejectInvalidMask("invalid numeric configuration", error);
2692
- }
2693
- maskConfig.left = left;
2694
- maskConfig.top = top;
2695
- let mask;
2696
- if (typeof maskConfig.fabricGenerator === "function") {
2697
- try {
2698
- mask = maskConfig.fabricGenerator(maskConfig, this.canvas, this.options);
2699
- } catch (error) {
2700
- return rejectInvalidMask("fabricGenerator failed", error);
2701
- }
2702
- } else {
2703
- switch (shapeType) {
2704
- case "circle":
2705
- try {
2706
- maskConfig.radius = resolveNumber(maskConfig.radius, Math.min(maskConfig.width, maskConfig.height) / 2, "min", "radius", { positive: true });
2707
- } catch (error) {
2708
- return rejectInvalidMask("invalid circle radius", error);
2709
- }
2710
- mask = new fabric.Circle({
2711
- left,
2712
- top,
2713
- radius: maskConfig.radius,
2714
- fill: maskConfig.color,
2715
- opacity: maskConfig.alpha,
2716
- angle: maskConfig.angle,
2717
- ...maskConfig.styles
2718
- });
2719
- break;
2720
- case "ellipse":
2721
- try {
2722
- maskConfig.rx = resolveNumber(maskConfig.rx, maskConfig.width / 2, "width", "rx", { positive: true });
2723
- maskConfig.ry = resolveNumber(maskConfig.ry, maskConfig.height / 2, "height", "ry", { positive: true });
2724
- } catch (error) {
2725
- return rejectInvalidMask("invalid ellipse radius", error);
2726
- }
2727
- mask = new fabric.Ellipse({
2728
- left,
2729
- top,
2730
- rx: maskConfig.rx,
2731
- ry: maskConfig.ry,
2732
- fill: maskConfig.color,
2733
- opacity: maskConfig.alpha,
2734
- angle: maskConfig.angle,
2735
- ...maskConfig.styles
2736
- });
2737
- break;
2738
- case "polygon": {
2739
- let polygonPoints = maskConfig.points || [];
2740
- if (!Array.isArray(polygonPoints) || polygonPoints.length < 3) {
2741
- return rejectInvalidMask("polygon masks require at least three points");
2742
- }
2743
- try {
2744
- polygonPoints = polygonPoints.map((point) => {
2745
- const x = Number(Array.isArray(point) ? point[0] : point.x);
2746
- const y = Number(Array.isArray(point) ? point[1] : point.y);
2747
- if (!Number.isFinite(x) || !Number.isFinite(y)) {
2748
- throw new Error("polygon point coordinates must be finite numbers");
2749
- }
2750
- return { x, y };
2751
- });
2752
- } catch (error) {
2753
- return rejectInvalidMask("invalid polygon points", error);
2754
- }
2755
- const uniquePointKeys = new Set(polygonPoints.map((point) => `${point.x}:${point.y}`));
2756
- if (uniquePointKeys.size !== polygonPoints.length) {
2757
- return rejectInvalidMask("polygon points must not contain duplicates");
2758
- }
2759
- const doubleArea = polygonPoints.reduce((area, point, index) => {
2760
- const nextPoint = polygonPoints[(index + 1) % polygonPoints.length];
2761
- return area + point.x * nextPoint.y - nextPoint.x * point.y;
2762
- }, 0);
2763
- if (Math.abs(doubleArea) < 1e-6) {
2764
- return rejectInvalidMask("polygon masks must have a non-zero area");
2765
- }
2766
- mask = new fabric.Polygon(polygonPoints, {
2767
- left,
2768
- top,
2769
- fill: maskConfig.color,
2770
- opacity: maskConfig.alpha,
2771
- angle: maskConfig.angle,
2772
- ...maskConfig.styles
2773
- });
2774
- break;
2775
- }
2776
- case "rect":
2777
- default:
2778
- try {
2779
- if (maskConfig.rx != null) maskConfig.rx = resolveNumber(maskConfig.rx, 0, "width", "rx", { nonNegative: true });
2780
- if (maskConfig.ry != null) maskConfig.ry = resolveNumber(maskConfig.ry, 0, "height", "ry", { nonNegative: true });
2781
- } catch (error) {
2782
- return rejectInvalidMask("invalid rectangle corner radius", error);
2783
- }
2784
- mask = new fabric.Rect({
2785
- left,
2786
- top,
2787
- width: maskConfig.width,
2788
- height: maskConfig.height,
2789
- fill: maskConfig.color,
2790
- opacity: maskConfig.alpha,
2791
- angle: maskConfig.angle,
2792
- rx: maskConfig.rx,
2793
- ry: maskConfig.ry,
2794
- ...maskConfig.styles
2795
- });
2796
- }
2797
- }
2798
- if (!mask || typeof mask.set !== "function" || typeof mask.setCoords !== "function") {
2799
- this._reportWarning("fabricGenerator returned an invalid Fabric object");
2800
- return null;
2801
- }
2802
- const styles = maskConfig.styles || {};
2803
- const hasStyle = (property) => Object.prototype.hasOwnProperty.call(styles, property);
2804
- const maskSettings = {
2805
- selectable: maskConfig.selectable !== false,
2806
- hasControls: "hasControls" in maskConfig ? maskConfig.hasControls : true,
2807
- lockRotation: !this.options.maskRotatable,
2808
- borderColor: "borderColor" in maskConfig ? maskConfig.borderColor : "red",
2809
- cornerColor: "cornerColor" in maskConfig ? maskConfig.cornerColor : "black",
2810
- cornerSize: "cornerSize" in maskConfig ? maskConfig.cornerSize : 8,
2811
- transparentCorners: "transparentCorners" in maskConfig ? maskConfig.transparentCorners : false,
2812
- stroke: hasStyle("stroke") ? styles.stroke : "#ccc",
2813
- strokeWidth: hasStyle("strokeWidth") ? styles.strokeWidth : 1,
2814
- opacity: hasStyle("opacity") ? styles.opacity : maskConfig.alpha,
2815
- strokeUniform: "strokeUniform" in maskConfig ? maskConfig.strokeUniform : hasStyle("strokeUniform") ? styles.strokeUniform : true
2816
- };
2817
- if (hasStyle("strokeDashArray")) maskSettings.strokeDashArray = styles.strokeDashArray;
2818
- mask.set(maskSettings);
2819
- mask.setCoords();
2820
- mask.set({
2821
- originalAlpha: Number.isFinite(Number(mask.opacity)) ? Number(mask.opacity) : maskConfig.alpha,
2822
- originalStroke: mask.stroke || "#ccc",
2823
- originalStrokeWidth: Number.isFinite(Number(mask.strokeWidth)) ? Number(mask.strokeWidth) : 1
2824
- });
2825
- this._rebindMaskEvents(mask);
2826
- this._expandCanvasToFitObjects([mask]);
2827
- this._lastMaskInitialLeft = left;
2828
- this._lastMaskInitialTop = top;
2829
- this._lastMaskInitialWidth = maskConfig.width;
2830
- const maskId = ++this.maskCounter;
2831
- mask.set({
2832
- maskId,
2833
- maskName: `${this.options.maskName}${maskId}`
2834
- });
2835
- this._lastMask = mask;
2836
- this.canvas.add(mask);
2837
- this.canvas.bringToFront(mask);
2838
- if (maskConfig.selectable) this.canvas.setActiveObject(mask);
2839
- this._handleSelectionChanged([mask]);
2840
- this._updateMaskList();
2841
- this._updateUI();
2842
- this.canvas.renderAll();
2843
- this.saveState();
2844
- if (typeof maskConfig.onCreate === "function") {
2845
- this._emitSafeCallback(
2846
- () => maskConfig.onCreate(mask, this.canvas),
2847
- "createMask onCreate callback failed"
2848
- );
2849
- }
2850
- return mask;
2851
- }
2852
- /**
2853
- * Backward-compatible alias for {@link ImageEditor#createMask}.
2854
- *
2855
- * @deprecated Use createMask() instead. This alias will be removed in v2.0.0.
2856
- * @param {Object} [config={}] - Mask configuration passed to createMask().
2857
- * @returns {fabric.Object|null} The created mask object, or null if the canvas is not initialized.
2858
- */
2859
- addMask(config = {}) {
2860
- return this.createMask(config);
2861
- }
2862
- /**
2863
- * Removes the currently selected mask from the canvas, if any.
2864
- * The associated label is also removed. UI and mask list are updated.
2865
- */
2866
- removeSelectedMask() {
2867
- if (!this.canvas) return;
2868
- if (!this._canMutateNow("removeSelectedMask")) return;
2869
- const activeObject = this.canvas.getActiveObject();
2870
- const selectedMasks = this._getModifiedMasks(activeObject);
2871
- if (!selectedMasks.length) return;
2872
- this.canvas.discardActiveObject();
2873
- selectedMasks.forEach((mask) => {
2874
- this._removeLabelForMask(mask);
2875
- this._cleanupMaskEvents(mask);
2876
- this.canvas.remove(mask);
2877
- });
2878
- const masks = this.canvas.getObjects().filter((object) => object.maskId);
2879
- this._lastMask = masks.length ? masks[masks.length - 1] : null;
2880
- if (!this._lastMask) {
2881
- this._lastMaskInitialLeft = null;
2882
- this._lastMaskInitialTop = null;
2883
- this._lastMaskInitialWidth = null;
2884
- }
2885
- this._updateMaskList();
2886
- this._updateUI();
2887
- this.canvas.renderAll();
2888
- this.saveState();
2889
- }
2890
- /**
2891
- * Removes all masks from the canvas, including their labels.
2892
- * UI and internal mask placement memory are reset.
2893
- */
2894
- removeAllMasks(options = {}) {
2895
- if (!this.canvas) return;
2896
- if (!this._canMutateNow("removeAllMasks", options)) return;
2897
- const saveHistory = options.saveHistory !== false;
2898
- const masks = this.canvas.getObjects().filter((object) => object.maskId);
2899
- masks.forEach((mask) => this._removeLabelForMask(mask));
2900
- masks.forEach((mask) => {
2901
- this._cleanupMaskEvents(mask);
2902
- this.canvas.remove(mask);
2903
- });
2904
- this.canvas.discardActiveObject();
2905
- this._lastMask = null;
2906
- this._lastMaskInitialLeft = null;
2907
- this._lastMaskInitialTop = null;
2908
- this._lastMaskInitialWidth = null;
2909
- this._updateMaskList();
2910
- this._updateUI();
2911
- this.canvas.renderAll();
2912
- if (saveHistory) this.saveState();
2913
- }
2914
- /**
2915
- * Removes the label associated with the specified mask object, if it exists.
2916
- *
2917
- * @param {fabric.Object} mask - The mask object whose label should be removed.
2918
- * @private
2919
- */
2920
- _removeLabelForMask(mask) {
2921
- if (!mask || !this.canvas) return;
2922
- if (mask.__label) {
2923
- try {
2924
- const canvasObjects = this.canvas.getObjects();
2925
- if (canvasObjects.includes(mask.__label)) {
2926
- this.canvas.remove(mask.__label);
2927
- }
2928
- } catch (error) {
2929
- void error;
2930
- }
2931
- try {
2932
- delete mask.__label;
2933
- } catch (error) {
2934
- void error;
2935
- }
2936
- }
2937
- }
2938
- _captureMaskLabelBackups(masks) {
2939
- if (!this.canvas) return [];
2940
- const canvasObjects = new Set(this.canvas.getObjects());
2941
- return (masks || []).map((mask) => {
2942
- const label = mask && mask.__label ? mask.__label : null;
2943
- return {
2944
- mask,
2945
- label,
2946
- hadLabel: !!label,
2947
- labelInCanvas: !!label && canvasObjects.has(label),
2948
- visible: label ? label.visible : void 0
2949
- };
2950
- });
2951
- }
2952
- _restoreMaskLabelBackups(labelBackups) {
2953
- if (!this.canvas || !Array.isArray(labelBackups)) return;
2954
- const canvasObjects = new Set(this.canvas.getObjects());
2955
- labelBackups.forEach((backup) => {
2956
- if (!backup || !backup.mask) return;
2957
- try {
2958
- if (!backup.hadLabel) {
2959
- if (backup.mask.__label) this._removeLabelForMask(backup.mask);
2960
- return;
2961
- }
2962
- backup.mask.__label = backup.label;
2963
- if (!backup.label) return;
2964
- if (backup.labelInCanvas && !canvasObjects.has(backup.label)) {
2965
- this.canvas.add(backup.label);
2966
- canvasObjects.add(backup.label);
2967
- }
2968
- if (backup.visible !== void 0) backup.label.set({ visible: backup.visible });
2969
- if (backup.labelInCanvas) this.canvas.bringToFront(backup.label);
2970
- this._syncMaskLabel(backup.mask);
2971
- } catch (error) {
2972
- this._reportWarning("restoreMaskLabelBackups: failed to restore mask label", error);
2973
- }
2974
- });
2975
- }
2976
- _captureActiveObjectBackup() {
2977
- if (!this.canvas) return null;
2978
- const activeObject = this.canvas.getActiveObject();
2979
- if (!activeObject) return null;
2980
- const selectedObjects = typeof activeObject.getObjects === "function" ? activeObject.getObjects() : [activeObject];
2981
- return { activeObject, selectedObjects };
2982
- }
2983
- _restoreActiveObjectBackup(activeObjectBackup) {
2984
- if (!this.canvas || !activeObjectBackup || !activeObjectBackup.activeObject) return;
2985
- const canvasObjects = this.canvas.getObjects();
2986
- const selectedObjects = Array.isArray(activeObjectBackup.selectedObjects) ? activeObjectBackup.selectedObjects : [];
2987
- const canRestore = selectedObjects.length ? selectedObjects.every((object) => canvasObjects.includes(object)) : canvasObjects.includes(activeObjectBackup.activeObject);
2988
- if (!canRestore) return;
2989
- try {
2990
- this.canvas.setActiveObject(activeObjectBackup.activeObject);
2991
- } catch (error) {
2992
- void error;
2993
- }
2994
- }
2995
- _captureMaskExportBackups(masks) {
2996
- return (masks || []).map((mask) => ({
2997
- object: mask,
2998
- visible: mask.visible,
2999
- opacity: mask.opacity,
3000
- fill: mask.fill,
3001
- strokeWidth: mask.strokeWidth,
3002
- stroke: mask.stroke,
3003
- selectable: mask.selectable,
3004
- lockRotation: mask.lockRotation
3005
- }));
3006
- }
3007
- _restoreMaskExportBackups(maskBackups) {
3008
- (maskBackups || []).forEach((backup) => {
3009
- try {
3010
- backup.object.set({
3011
- visible: backup.visible,
3012
- opacity: backup.opacity,
3013
- fill: backup.fill,
3014
- strokeWidth: backup.strokeWidth,
3015
- stroke: backup.stroke,
3016
- selectable: backup.selectable,
3017
- lockRotation: backup.lockRotation
3018
- });
3019
- backup.object.setCoords();
3020
- } catch (error) {
3021
- void error;
3022
- }
3023
- });
3024
- }
3025
- /**
3026
- * Returns a stable zero-based creation index for label callbacks.
3027
- *
3028
- * Mask ids are one-based and are not renumbered after deletion, so this value remains stable for the
3029
- * lifetime of a mask.
3030
- *
3031
- * @param {fabric.Object} mask - Mask object.
3032
- * @returns {number} Stable zero-based creation index.
3033
- * @private
3034
- */
3035
- _getMaskCreationIndex(mask) {
3036
- const maskId = Number(mask && mask.maskId);
3037
- if (Number.isFinite(maskId) && maskId > 0) return Math.floor(maskId) - 1;
3038
- const masks = this.canvas ? this.canvas.getObjects().filter((object) => object.maskId) : [];
3039
- return Math.max(0, masks.indexOf(mask));
3040
- }
3041
- /**
3042
- * Creates and adds a custom label (fabric.Text or fabric.IText) for the mask.
3043
- * The label is default bound to the top-left of the mask and managed as a non-interactive overlay.
3044
- *
3045
- * @param {fabric.Object} mask - The mask to create a label for.
3046
- * @private
3047
- */
3048
- _createLabelForMask(mask) {
3049
- if (!mask || !this.options.maskLabelOnSelect) return;
3050
- this._removeLabelForMask(mask);
3051
- let textObject = null;
3052
- if (this.options.label && typeof this.options.label.create === "function") {
3053
- let didLabelCreateThrow = false;
3054
- try {
3055
- textObject = this.options.label.create(mask, fabric);
3056
- } catch (error) {
3057
- didLabelCreateThrow = true;
3058
- this._reportWarning("label.create() failed; using the default label", error);
3059
- textObject = null;
3060
- }
3061
- if (!didLabelCreateThrow && (!textObject || typeof textObject.set !== "function")) {
3062
- this._reportWarning("label.create() returned an invalid Fabric object; using the default label");
3063
- textObject = null;
3064
- }
3065
- }
3066
- if (!textObject) {
3067
- let labelText = mask.maskName;
3068
- let textOptions = {
3069
- left: 0,
3070
- top: 0,
3071
- fontSize: 12,
3072
- fill: "#fff",
3073
- backgroundColor: "rgba(0,0,0,0.7)",
3074
- selectable: false,
3075
- evented: false,
3076
- padding: 2,
3077
- originX: "left",
3078
- originY: "top"
3079
- };
3080
- if (this.options.label) {
3081
- if (typeof this.options.label.getText === "function") {
3082
- try {
3083
- labelText = this.options.label.getText(mask, this._getMaskCreationIndex(mask));
3084
- } catch (error) {
3085
- this._reportWarning("label.getText() failed; using the mask name", error);
3086
- labelText = mask.maskName;
3087
- }
3088
- }
3089
- if (this.options.label.textOptions) {
3090
- Object.assign(textOptions, this.options.label.textOptions);
3091
- }
3092
- }
3093
- textObject = new fabric.Text(labelText, textOptions);
3094
- }
3095
- textObject.maskLabel = true;
3096
- mask.__label = textObject;
3097
- this.canvas.add(textObject);
3098
- this.canvas.bringToFront(textObject);
3099
- this._syncMaskLabel(mask);
3100
- }
3101
- /**
3102
- * Hides (removes) all mask labels from the canvas.
3103
- * Internal label references on mask objects are also deleted.
3104
- * @private
3105
- */
3106
- _hideAllMaskLabels() {
3107
- if (!this.canvas) return;
3108
- const canvasObjects = this.canvas.getObjects();
3109
- const canvasObjectSet = new Set(canvasObjects);
3110
- const labels = canvasObjects.filter((object) => object.maskLabel);
3111
- labels.forEach((label) => {
3112
- try {
3113
- if (canvasObjectSet.has(label)) {
3114
- this.canvas.remove(label);
3115
- }
3116
- } catch (error) {
3117
- void error;
3118
- }
3119
- });
3120
- canvasObjects.forEach((object) => {
3121
- if (object.maskId && object.__label) {
3122
- try {
3123
- delete object.__label;
3124
- } catch (error) {
3125
- void error;
3126
- }
3127
- }
3128
- });
3129
- }
3130
- /**
3131
- * Synchronizes the position, angle, and visibility of the mask's label so that it appears properly above the mask.
3132
- *
3133
- * @param {fabric.Object} mask - The mask whose label should be repositioned.
3134
- * @private
3135
- */
3136
- _syncMaskLabel(mask) {
3137
- if (!mask) return;
3138
- if (!this.options.maskLabelOnSelect) return;
3139
- if (!mask.__label) return;
3140
- if (typeof mask.setCoords === "function") mask.setCoords();
3141
- const bounds = mask.getBoundingRect ? mask.getBoundingRect(true, true) : null;
3142
- if (!bounds) return;
3143
- const tl = { x: bounds.left, y: bounds.top };
3144
- const center = mask.getCenterPoint();
3145
- const vx = center.x - tl.x;
3146
- const vy = center.y - tl.y;
3147
- const dist = Math.sqrt(vx * vx + vy * vy) || 1;
3148
- const ux = vx / dist;
3149
- const uy = vy / dist;
3150
- const offset = Math.max(0, this.options.maskLabelOffset ?? 3);
3151
- const px = tl.x + ux * offset;
3152
- const py = tl.y + uy * offset;
3153
- mask.__label.set({
3154
- left: Math.round(px),
3155
- top: Math.round(py),
3156
- angle: mask.angle || 0,
3157
- originX: "left",
3158
- originY: "top",
3159
- visible: true
3160
- });
3161
- mask.__label.setCoords();
3162
- if (typeof this.canvas.requestRenderAll === "function") {
3163
- this.canvas.requestRenderAll();
3164
- } else {
3165
- this.canvas.renderAll();
3166
- }
3167
- }
3168
- /**
3169
- * Shows the label for the given mask, creating it if necessary and synchronizing its position.
3170
- *
3171
- * @param {fabric.Object} mask - The mask whose label should be shown.
3172
- * @private
3173
- */
3174
- _showLabelForMask(mask) {
3175
- if (!mask) return;
3176
- if (!this.options.maskLabelOnSelect) return;
3177
- if (!mask.__label) this._createLabelForMask(mask);
3178
- mask.__label.set({ visible: true });
3179
- this._syncMaskLabel(mask);
3180
- }
3181
- /**
3182
- * Handles changes to the selection of canvas objects (masks),
3183
- * updates mask stroke and label display, and syncs mask list selection.
3184
- *
3185
- * @param {Array<Object>} selected - The currently selected objects (e.g. [mask] or []).
3186
- * @private
3187
- */
3188
- _handleSelectionChanged(selected) {
3189
- const selectedMask = (selected || []).find((object) => object.maskId);
3190
- const masks = this.canvas.getObjects().filter((object) => object.maskId);
3191
- masks.forEach((mask) => {
3192
- if (mask !== selectedMask) {
3193
- if (mask.__label) {
3194
- try {
3195
- this.canvas.remove(mask.__label);
3196
- } catch (error) {
3197
- void error;
3198
- }
3199
- delete mask.__label;
3200
- }
3201
- const originalStrokeWidth = Number(mask.originalStrokeWidth);
3202
- mask.set({
3203
- stroke: mask.originalStroke || "#ccc",
3204
- strokeWidth: Number.isFinite(originalStrokeWidth) ? originalStrokeWidth : 1
3205
- });
3206
- } else {
3207
- mask.set({ stroke: "#ff0000", strokeWidth: 1 });
3208
- }
3209
- });
3210
- if (selectedMask) this._showLabelForMask(selectedMask);
3211
- this._updateMaskListSelection(selectedMask);
3212
- this.canvas.renderAll();
3213
- this._updateUI();
3214
- }
3215
- /**
3216
- * Updates the mask list in the DOM to reflect the current masks on the canvas.
3217
- * Each list entry becomes a clickable element for mask selection.
3218
- * @private
3219
- */
3220
- _updateMaskList() {
3221
- const maskListElement = this._getElement("maskList");
3222
- if (!maskListElement) return;
3223
- maskListElement.innerHTML = "";
3224
- const masks = this.canvas.getObjects().filter((object) => object.maskId);
3225
- masks.forEach((mask) => {
3226
- const listItemElement = document.createElement("li");
3227
- listItemElement.className = "list-group-item mask-item";
3228
- listItemElement.textContent = mask.maskName;
3229
- listItemElement.dataset.maskId = String(mask.maskId);
3230
- maskListElement.appendChild(listItemElement);
3231
- });
3232
- }
3233
- _handleMaskListClick(event) {
3234
- if (!this.canvas) return;
3235
- const itemElement = event.target && event.target.closest ? event.target.closest(".mask-item") : null;
3236
- if (!itemElement || !itemElement.dataset) return;
3237
- const maskId = Number(itemElement.dataset.maskId);
3238
- const mask = this.canvas.getObjects().find((object) => Number(object.maskId) === maskId);
3239
- if (!mask) return;
3240
- this.canvas.setActiveObject(mask);
3241
- this._handleSelectionChanged([mask]);
3242
- }
3243
- /**
3244
- * Updates the visual selection (CSS 'active') state for the mask list in the DOM.
3245
- *
3246
- * @param {Object|null} selectedMask - The currently selected mask, or null if none selected.
3247
- * @private
3248
- */
3249
- _updateMaskListSelection(selectedMask) {
3250
- const maskListElement = this._getElement("maskList");
3251
- if (!maskListElement) return;
3252
- const maskItems = maskListElement.querySelectorAll(".mask-item");
3253
- maskItems.forEach((item) => {
3254
- const isSelected = !!selectedMask && Number(item.dataset.maskId) === Number(selectedMask.maskId);
3255
- item.classList.toggle("active", isSelected);
3256
- item.classList.toggle("selected", isSelected);
3257
- });
3258
- }
3259
- /**
3260
- * Flattens the current masks into the base image and reloads the flattened image.
3261
- *
3262
- * This removes editable mask objects after export and records the operation as one undoable history transition.
3263
- * It does nothing when no base image or no masks exist.
3264
- *
3265
- * @async
3266
- * @returns {Promise<void>} Resolves when the flattened image has been loaded.
3267
- * @public
3268
- */
3269
- async mergeMasks() {
3270
- if (!this.originalImage) return;
3271
- this._assertIdleForOperation("mergeMasks");
3272
- const masks = this.canvas.getObjects().filter((object) => object.maskId);
3273
- if (!masks.length) return;
3274
- const beforeImageDisplayBounds = this._captureImageDisplayBounds();
3275
- const beforeJson = this._serializeCanvasState();
3276
- const operationToken = this._beginBusyOperation("mergeMasks");
3277
- this.canvas.discardActiveObject();
3278
- this.canvas.renderAll();
3279
- try {
3280
- const merged = await this.exportImageBase64(this._withInternalOperationOptions(operationToken, {
3281
- exportImageArea: true,
3282
- multiplier: this.options.exportMultiplier,
3283
- fileType: "png"
3284
- }));
3285
- this.removeAllMasks(this._withInternalOperationOptions(operationToken, { saveHistory: false }));
3286
- if (this.canvas.getObjects().some((object) => object.maskId)) {
3287
- throw new Error("Masks could not be removed during merge");
3288
- }
3289
- await this.loadImage(merged, this._withInternalOperationOptions(operationToken, {
3290
- preserveScroll: true,
3291
- resetMaskCounter: false
3292
- }));
3293
- this._restoreImageDisplayBounds(beforeImageDisplayBounds);
3294
- const afterJson = this._serializeCanvasState();
3295
- this._pushStateTransition(beforeJson, afterJson);
3296
- } catch (error) {
3297
- this._reportError("merge error", error);
3298
- try {
3299
- await this.loadFromState(beforeJson, this._withInternalOperationOptions(operationToken));
3300
- } catch (restoreError) {
3301
- this._reportError("mergeMasks rollback failed", restoreError);
3302
- }
3303
- throw error;
3304
- } finally {
3305
- this._endBusyOperation(operationToken);
3306
- }
3307
- }
3308
- /**
3309
- * Backward-compatible alias for {@link ImageEditor#mergeMasks}.
3310
- *
3311
- * @deprecated Use mergeMasks() instead. This alias will be removed in v2.0.0.
3312
- * @returns {Promise<void>} Resolves when mask flattening is complete.
3313
- */
3314
- async merge() {
3315
- return this.mergeMasks();
3316
- }
3317
- /**
3318
- * Triggers a JPEG image download of the current canvas.
3319
- *
3320
- * The image area and multiplier are controlled by options.
3321
- * @param {string} [fileName=this.options.defaultDownloadFileName] - Desired download file name.
3322
- * @returns {void}
3323
- * @public
3324
- */
3325
- downloadImage(fileName = this.options.defaultDownloadFileName) {
3326
- if (!this.originalImage) return;
3327
- if (!this._canMutateNow("downloadImage")) return;
3328
- const exportImageArea = this.options.exportImageAreaByDefault;
3329
- this.exportImageBase64({ exportImageArea, multiplier: this.options.exportMultiplier }).then((imageBase64) => {
3330
- const link = document.createElement("a");
3331
- link.download = fileName;
3332
- link.href = imageBase64;
3333
- document.body.appendChild(link);
3334
- link.click();
3335
- document.body.removeChild(link);
3336
- }).catch((error) => this._reportError("download error", error));
3337
- }
3338
- /**
3339
- * Exports the current image as a Base64-encoded data URL.
3340
- *
3341
- * When `exportImageArea` is false, the export omits masks and labels. When it is true, masks are
3342
- * temporarily rendered as opaque export shapes and then restored, so editable mask state is not mutated.
3343
- *
3344
- * @async
3345
- * @param {Object} [options={}] - Export options.
3346
- * @param {boolean} [options.exportImageArea] - If true, exports only the image bounding area with masks cropped and blended.
3347
- * @param {number} [options.multiplier=1] - Scaling multiplier for output (resolution).
3348
- * @param {number} [options.quality=0.92] - Image quality between 0 and 1 for lossy formats.
3349
- * @param {string} [options.fileType='jpeg'] - Output file type ('jpeg' | 'png' | 'webp').
3350
- * @returns {Promise<string>} Resolves with an image data URL.
3351
- * @throws {Error} If there is no image loaded.
3352
- * @public
3353
- */
3354
- async exportImageBase64(options = {}) {
3355
- if (!this.originalImage) throw new Error("No image loaded");
3356
- options = options || {};
3357
- this._assertIdleForOperation("exportImageBase64", options);
3358
- const isNestedOperation = this._isOwnInternalOperation(options);
3359
- const operationToken = isNestedOperation ? this._getInternalOperationToken(options) : this._beginBusyOperation("exportImageBase64");
3360
- const exportImageArea = typeof options.exportImageArea === "boolean" ? options.exportImageArea : this.options.exportImageAreaByDefault;
3361
- const multiplier = options.multiplier || this.options.exportMultiplier || 1;
3362
- const quality = this._normalizeQuality(options.quality ?? this.options.downsampleQuality);
3363
- const format = this._normalizeImageFormat(options.fileType || options.format);
3364
- try {
3365
- if (!exportImageArea) {
3366
- const masks2 = this.canvas.getObjects().filter((object) => object.maskId || object.maskLabel);
3367
- const editableMasks = this.canvas.getObjects().filter((object) => object.maskId);
3368
- const maskVisibilityBackups = masks2.map((mask) => ({ object: mask, visible: mask.visible }));
3369
- const maskStyleBackups2 = this._captureMaskExportBackups(editableMasks);
3370
- const labelBackups2 = this._captureMaskLabelBackups(editableMasks);
3371
- const activeObjectBackup2 = this._captureActiveObjectBackup();
3372
- try {
3373
- masks2.forEach((mask) => {
3374
- mask.set({ visible: false });
3375
- });
3376
- this.canvas.discardActiveObject();
3377
- this.canvas.renderAll();
3378
- this.originalImage.setCoords();
3379
- const imageBounds = this.originalImage.getBoundingRect(true, true);
3380
- const exportRegion = this._getClampedCanvasRegion(imageBounds);
3381
- return await this._exportCanvasRegionToDataURL({
3382
- ...exportRegion,
3383
- multiplier,
3384
- quality,
3385
- format,
3386
- sealPartialEdges: this._getPartialExportEdges(imageBounds)
3387
- });
3388
- } finally {
3389
- maskVisibilityBackups.forEach((backup) => {
3390
- try {
3391
- backup.object.set({ visible: backup.visible });
3392
- } catch (error) {
3393
- void error;
3394
- }
3395
- });
3396
- this._restoreMaskExportBackups(maskStyleBackups2);
3397
- this._restoreMaskLabelBackups(labelBackups2);
3398
- this._restoreActiveObjectBackup(activeObjectBackup2);
3399
- this.canvas.renderAll();
3400
- }
3401
- }
3402
- const masks = this.canvas.getObjects().filter((object) => object.maskId);
3403
- const maskStyleBackups = this._captureMaskExportBackups(masks);
3404
- const labelBackups = this._captureMaskLabelBackups(masks);
3405
- const activeObjectBackup = this._captureActiveObjectBackup();
3406
- try {
3407
- masks.forEach((mask) => this._removeLabelForMask(mask));
3408
- this.canvas.discardActiveObject();
3409
- this.canvas.renderAll();
3410
- masks.forEach((mask) => {
3411
- mask.set({ opacity: 1, fill: "#000000", strokeWidth: 0, stroke: null, selectable: false });
3412
- mask.setCoords();
3413
- });
3414
- this.canvas.renderAll();
3415
- this.originalImage.setCoords();
3416
- const imageBounds = this.originalImage.getBoundingRect(true, true);
3417
- const exportRegion = this._getClampedCanvasRegion(imageBounds);
3418
- return await this._exportCanvasRegionToDataURL({
3419
- ...exportRegion,
3420
- multiplier,
3421
- quality,
3422
- format,
3423
- sealPartialEdges: this._getPartialExportEdges(imageBounds)
3424
- });
3425
- } finally {
3426
- this._restoreMaskExportBackups(maskStyleBackups);
3427
- this._restoreMaskLabelBackups(labelBackups);
3428
- this._restoreActiveObjectBackup(activeObjectBackup);
3429
- this.canvas.renderAll();
3430
- }
3431
- } finally {
3432
- if (!isNestedOperation) this._endBusyOperation(operationToken);
3433
- }
3434
- }
3435
- /**
3436
- * Backward-compatible alias for {@link ImageEditor#exportImageBase64}.
3437
- *
3438
- * @deprecated Use exportImageBase64() instead. This alias will be removed in v2.0.0.
3439
- * @param {Object} [options={}] - Export options passed to exportImageBase64().
3440
- * @returns {Promise<string>} Resolves with an image data URL.
3441
- */
3442
- async getImageBase64(options = {}) {
3443
- return this.exportImageBase64(options);
3444
- }
3445
- /**
3446
- * Exports the current image as a File object.
3447
- *
3448
- * The export can include flattened masks (`mergeMask: true`) or only the plain base image (`mergeMask: false`).
3449
- * Supported output formats are JPEG, PNG, and WebP.
3450
- *
3451
- * @async
3452
- * @param {Object} [options={}] - Export options.
3453
- * @param {boolean} [options.mergeMask=true] - If true, export image area with masks merged; if false, export the plain image without masks.
3454
- * @param {string} [options.fileType='jpeg'] - Output file type ('jpeg' | 'png' | 'webp'). Defaults to 'jpeg' on invalid input.
3455
- * @param {number} [options.quality=0.92] - Image quality for lossy types (0-1, default based on options.downsampleQuality).
3456
- * @param {number} [options.multiplier=1] - Output resolution multiplier.
3457
- * @param {string} [options.fileName] - Optional file name (only used for download).
3458
- * @returns {Promise<File>} Resolves with the exported image as a File object.
3459
- *
3460
- * @example
3461
- * const file = await this.exportImageFile({ mergeMask: false, fileType: 'png' });
3462
- */
3463
- async exportImageFile(options = {}) {
3464
- if (!this.originalImage) throw new Error("No image loaded");
3465
- options = options || {};
3466
- this._assertIdleForOperation("exportImageFile", options);
3467
- const isNestedOperation = this._isOwnInternalOperation(options);
3468
- const operationToken = isNestedOperation ? this._getInternalOperationToken(options) : this._beginBusyOperation("exportImageFile");
3469
- const {
3470
- mergeMask = true,
3471
- fileType = "jpeg",
3472
- quality = this.options.downsampleQuality ?? 0.92,
3473
- multiplier = this.options.exportMultiplier ?? 1,
3474
- fileName = this.options.defaultDownloadFileName ?? "exported_image.jpg"
3475
- } = options;
3476
- const safeFileType = this._normalizeImageFormat(fileType);
3477
- const normalizedQuality = this._normalizeQuality(quality);
3478
- try {
3479
- let imageBase64;
3480
- if (mergeMask) {
3481
- imageBase64 = await this.exportImageBase64(this._withInternalOperationOptions(operationToken, {
3482
- exportImageArea: true,
3483
- multiplier,
3484
- quality: normalizedQuality,
3485
- fileType: safeFileType
3486
- }));
3487
- } else {
3488
- imageBase64 = await this.exportImageBase64(this._withInternalOperationOptions(operationToken, {
3489
- exportImageArea: false,
3490
- multiplier,
3491
- quality: normalizedQuality,
3492
- fileType: safeFileType
3493
- }));
3494
- }
3495
- let imageDataUrl = imageBase64;
3496
- if (!imageDataUrl.startsWith(`data:image/${safeFileType}`)) {
3497
- imageDataUrl = await new Promise((resolve, reject) => {
3498
- const imageElement = new window.Image();
3499
- imageElement.crossOrigin = "Anonymous";
3500
- imageElement.onload = () => {
3501
- try {
3502
- const offscreenCanvas = document.createElement("canvas");
3503
- offscreenCanvas.width = imageElement.width;
3504
- offscreenCanvas.height = imageElement.height;
3505
- const context = offscreenCanvas.getContext("2d");
3506
- if (!context) throw new Error("Unable to create 2D canvas context for export conversion");
3507
- context.drawImage(imageElement, 0, 0);
3508
- const convertedDataUrl = offscreenCanvas.toDataURL(`image/${safeFileType}`, normalizedQuality);
3509
- resolve(convertedDataUrl);
3510
- } catch (error) {
3511
- reject(error);
3512
- }
3513
- };
3514
- imageElement.onerror = reject;
3515
- imageElement.src = imageBase64;
3516
- });
3517
- }
3518
- const bytes = this._decodeDataUrlPayload(imageDataUrl);
3519
- const mime = `image/${safeFileType}`;
3520
- return new File([bytes], fileName, { type: mime });
3521
- } finally {
3522
- if (!isNestedOperation) this._endBusyOperation(operationToken);
3523
- }
3524
- }
3525
- _clearMaskPlacementMemory() {
3526
- this._lastMask = null;
3527
- this._lastMaskInitialLeft = null;
3528
- this._lastMaskInitialTop = null;
3529
- this._lastMaskInitialWidth = null;
3530
- }
3531
- async _restoreStateAfterCropFailure(beforeJson, message, error, options = {}) {
3532
- this._reportError(message, error);
3533
- if (this._cropRect && this.canvas) this._removeCropRect();
3534
- this._cropRect = null;
3535
- this._cropMode = false;
3536
- if (this.canvas && this._prevSelectionSetting !== void 0) {
3537
- this.canvas.selection = !!this._prevSelectionSetting;
3538
- }
3539
- this._prevSelectionSetting = void 0;
3540
- if (beforeJson) {
3541
- try {
3542
- await this.loadFromState(beforeJson, options);
3543
- } catch (restoreError) {
3544
- this._reportError("applyCrop: rollback failed", restoreError);
3545
- }
3546
- }
3547
- this._updateUI();
3548
- if (this.canvas) this.canvas.renderAll();
3549
- }
3550
- _restoreCropObjectState() {
3551
- if (Array.isArray(this._cropPrevEvented)) {
3552
- this._cropPrevEvented.forEach((state) => {
3553
- try {
3554
- state.object.set({
3555
- evented: state.evented,
3556
- selectable: state.selectable,
3557
- visible: state.visible
3558
- });
3559
- } catch (error) {
3560
- void error;
3561
- }
3562
- });
3563
- }
3564
- this._cropPrevEvented = null;
3565
- }
3566
- _removeCropRect() {
3567
- if (this._cropHandlers && this._cropHandlers.length) {
3568
- this._cropHandlers.forEach((targetHandlers) => {
3569
- (targetHandlers.handlers || []).forEach((handlerRecord) => {
3570
- try {
3571
- if (targetHandlers.target && typeof targetHandlers.target.off === "function") {
3572
- targetHandlers.target.off(handlerRecord.eventName, handlerRecord.handler);
3573
- }
3574
- } catch (error) {
3575
- this._reportWarning("Crop handler cleanup failed", error);
3576
- }
3577
- });
3578
- });
3579
- }
3580
- try {
3581
- if (this.canvas && this._cropRect) this.canvas.remove(this._cropRect);
3582
- } catch (error) {
3583
- void error;
3584
- }
3585
- this._cropRect = null;
3586
- this._cropHandlers = [];
3587
- }
3588
- _getCropRectContentBounds(cropRect) {
3589
- if (!cropRect) return { left: 0, top: 0, width: 1, height: 1 };
3590
- const width = Math.max(1, (Number(cropRect.width) || 1) * Math.abs(Number(cropRect.scaleX) || 1));
3591
- const height = Math.max(1, (Number(cropRect.height) || 1) * Math.abs(Number(cropRect.scaleY) || 1));
3592
- return {
3593
- left: Number(cropRect.left) || 0,
3594
- top: Number(cropRect.top) || 0,
3595
- width,
3596
- height
3597
- };
3598
- }
3599
- _getCropRectRawBounds(cropRect) {
3600
- if (!cropRect) return { left: NaN, top: NaN, width: NaN, height: NaN };
3601
- return {
3602
- left: Number(cropRect.left),
3603
- top: Number(cropRect.top),
3604
- width: Number(cropRect.width) * Math.abs(Number(cropRect.scaleX)),
3605
- height: Number(cropRect.height) * Math.abs(Number(cropRect.scaleY))
3606
- };
3607
- }
3608
- _isValidCropRegion(cropBounds, imageBounds) {
3609
- if (!cropBounds || !imageBounds) return false;
3610
- const left = Number(cropBounds.left);
3611
- const top = Number(cropBounds.top);
3612
- const width = Number(cropBounds.width);
3613
- const height = Number(cropBounds.height);
3614
- const imageLeft = Number(imageBounds.left);
3615
- const imageTop = Number(imageBounds.top);
3616
- const imageWidth = Number(imageBounds.width);
3617
- const imageHeight = Number(imageBounds.height);
3618
- if (![left, top, width, height, imageLeft, imageTop, imageWidth, imageHeight].every(Number.isFinite)) return false;
3619
- if (width <= 0 || height <= 0 || imageWidth <= 0 || imageHeight <= 0) return false;
3620
- const right = left + width;
3621
- const bottom = top + height;
3622
- const imageRight = imageLeft + imageWidth;
3623
- const imageBottom = imageTop + imageHeight;
3624
- const overlapsImage = left < imageRight && right > imageLeft && top < imageBottom && bottom > imageTop;
3625
- if (!overlapsImage) return false;
3626
- const canvasWidth = this.canvas ? Number(this.canvas.getWidth()) : NaN;
3627
- const canvasHeight = this.canvas ? Number(this.canvas.getHeight()) : NaN;
3628
- if (!Number.isFinite(canvasWidth) || !Number.isFinite(canvasHeight) || canvasWidth <= 0 || canvasHeight <= 0) return false;
3629
- return left < canvasWidth && right > 0 && top < canvasHeight && bottom > 0;
3630
- }
3631
- /**
3632
- * Enters crop mode by creating a resizable crop rectangle above the base image.
3633
- *
3634
- * Other canvas objects are made non-interactive while crop mode is active. Masks can be hidden during
3635
- * cropping when `crop.hideMasksDuringCrop` is enabled.
3636
- *
3637
- * @returns {void}
3638
- * @public
3639
- */
3640
- enterCropMode() {
3641
- if (!this.canvas || !this.originalImage || this._cropMode) return;
3642
- if (this._isApplyingCrop) {
3643
- this._reportWarning("enterCropMode ignored because a crop is already being applied");
3644
- return;
3645
- }
3646
- if (!this._canMutateNow("enterCropMode")) return;
3647
- if (!this.isImageLoaded()) return;
3648
- this._removeCropRect();
3649
- this._cropMode = true;
3650
- this._prevSelectionSetting = this.canvas.selection;
3651
- this.canvas.selection = false;
3652
- this.canvas.discardActiveObject();
3653
- this.originalImage.setCoords();
3654
- const imageBounds = this.originalImage.getBoundingRect(true, true);
3655
- const padding = this.options.crop && this.options.crop.padding ? this.options.crop.padding : 10;
3656
- const left = Math.max(0, Math.floor(imageBounds.left + padding));
3657
- const top = Math.max(0, Math.floor(imageBounds.top + padding));
3658
- const maxCropWidth = Math.max(1, Math.floor(imageBounds.width));
3659
- const maxCropHeight = Math.max(1, Math.floor(imageBounds.height));
3660
- const configuredMinWidth = Math.max(1, Number(this.options.crop.minWidth) || 50);
3661
- const configuredMinHeight = Math.max(1, Number(this.options.crop.minHeight) || 50);
3662
- const minCropWidth = Math.min(configuredMinWidth, maxCropWidth);
3663
- const minCropHeight = Math.min(configuredMinHeight, maxCropHeight);
3664
- const width = minCropWidth;
3665
- const height = minCropHeight;
3666
- const requestedCropRotation = !!(this.options.crop && this.options.crop.allowRotationOfCropRect);
3667
- if (requestedCropRotation && !this._cropRotationWarningEmitted) {
3668
- this._cropRotationWarningEmitted = true;
3669
- this._reportWarning("crop.allowRotationOfCropRect is disabled in v1.x because rotated crop export is not supported");
3670
- }
3671
- const cropRect = new fabric.Rect({
3672
- left,
3673
- top,
3674
- width,
3675
- height,
3676
- fill: "rgba(0,0,0,0.12)",
3677
- stroke: "#00aaff",
3678
- strokeDashArray: [6, 4],
3679
- strokeWidth: 1,
3680
- strokeUniform: true,
3681
- selectable: true,
3682
- hasRotatingPoint: false,
3683
- lockRotation: true,
3684
- cornerSize: 8,
3685
- objectCaching: false,
3686
- originX: "left",
3687
- originY: "top",
3688
- lockScalingFlip: true
3689
- });
3690
- this.canvas.add(cropRect);
3691
- cropRect.isCropRect = true;
3692
- this.canvas.bringToFront(cropRect);
3693
- this.canvas.setActiveObject(cropRect);
3694
- this._cropRect = cropRect;
3695
- this._cropPrevEvented = [];
3696
- const shouldHideMasks = !!(this.options.crop && this.options.crop.hideMasksDuringCrop);
3697
- this.canvas.getObjects().forEach((object) => {
3698
- if (object !== cropRect) {
3699
- this._cropPrevEvented.push({ object, evented: object.evented, selectable: object.selectable, visible: object.visible });
3700
- try {
3701
- const updates = {
3702
- evented: false,
3703
- selectable: false
3704
- };
3705
- if (shouldHideMasks && (object.maskId || object.maskLabel)) updates.visible = false;
3706
- object.set(updates);
3707
- } catch (error) {
3708
- void error;
3709
- }
3710
- }
3711
- });
3712
- const handleCropRectModified = () => {
3713
- try {
3714
- const cropWidth = Math.max(1, Number(cropRect.width) || 1);
3715
- const cropHeight = Math.max(1, Number(cropRect.height) || 1);
3716
- const nextScaleX = Math.min(maxCropWidth / cropWidth, Math.max(minCropWidth / cropWidth, Number(cropRect.scaleX) || 1));
3717
- const nextScaleY = Math.min(maxCropHeight / cropHeight, Math.max(minCropHeight / cropHeight, Number(cropRect.scaleY) || 1));
3718
- cropRect.set({ scaleX: nextScaleX, scaleY: nextScaleY });
3719
- cropRect.setCoords();
3720
- const cropBounds = this._getCropRectContentBounds(cropRect);
3721
- const imageLeft = Number(imageBounds.left) || 0;
3722
- const imageTop = Number(imageBounds.top) || 0;
3723
- const imageRight = imageLeft + (Number(imageBounds.width) || 0);
3724
- const imageBottom = imageTop + (Number(imageBounds.height) || 0);
3725
- let deltaX = 0;
3726
- let deltaY = 0;
3727
- if (cropBounds.left < imageLeft) {
3728
- deltaX = imageLeft - cropBounds.left;
3729
- } else if (cropBounds.left + cropBounds.width > imageRight) {
3730
- deltaX = imageRight - (cropBounds.left + cropBounds.width);
3731
- }
3732
- if (cropBounds.top < imageTop) {
3733
- deltaY = imageTop - cropBounds.top;
3734
- } else if (cropBounds.top + cropBounds.height > imageBottom) {
3735
- deltaY = imageBottom - (cropBounds.top + cropBounds.height);
3736
- }
3737
- if (deltaX || deltaY) {
3738
- cropRect.set({
3739
- left: (Number(cropRect.left) || 0) + deltaX,
3740
- top: (Number(cropRect.top) || 0) + deltaY
3741
- });
3742
- cropRect.setCoords();
3743
- }
3744
- this.canvas.requestRenderAll();
3745
- } catch (error) {
3746
- void error;
3747
- }
3748
- };
3749
- cropRect.on("modified", handleCropRectModified);
3750
- cropRect.on("moving", handleCropRectModified);
3751
- cropRect.on("scaling", handleCropRectModified);
3752
- this._cropHandlers.push({
3753
- target: cropRect,
3754
- handlers: [
3755
- { eventName: "modified", handler: handleCropRectModified },
3756
- { eventName: "moving", handler: handleCropRectModified },
3757
- { eventName: "scaling", handler: handleCropRectModified }
3758
- ]
3759
- });
3760
- this._updateUI();
3761
- this.canvas.renderAll();
3762
- }
3763
- /**
3764
- * Cancels crop mode and removes the temporary crop rectangle.
3765
- *
3766
- * @returns {void}
3767
- * @public
3768
- */
3769
- cancelCrop() {
3770
- if (this._isApplyingCrop) {
3771
- this._reportWarning("cancelCrop ignored because a crop is already being applied");
3772
- return;
3773
- }
3774
- if (!this.canvas || !this._cropMode) return;
3775
- this._removeCropRect();
3776
- this._restoreCropObjectState();
3777
- this._cropMode = false;
3778
- this.canvas.selection = !!this._prevSelectionSetting;
3779
- this._prevSelectionSetting = void 0;
3780
- this.canvas.discardActiveObject();
3781
- this._updateUI();
3782
- this.canvas.renderAll();
3783
- }
3784
- /**
3785
- * Applies the current crop rectangle to the base image.
3786
- *
3787
- * Masks are removed by default. When `crop.preserveMasksAfterCrop` is true, masks that intersect the crop
3788
- * region are shifted into the cropped coordinate space and remain editable. The operation is recorded as a
3789
- * single undoable history transition.
3790
- *
3791
- * @async
3792
- * @returns {Promise<void>} Resolves after the cropped image has been loaded and history is updated.
3793
- * @public
3794
- */
3795
- async applyCrop() {
3796
- if (!this.canvas || !this._cropMode || !this._cropRect) return;
3797
- if (this._isApplyingCrop) {
3798
- this._reportWarning("applyCrop ignored because a crop is already being applied");
3799
- return;
3800
- }
3801
- this._assertIdleForOperation("applyCrop");
3802
- this._isApplyingCrop = true;
3803
- const operationToken = this._beginBusyOperation("applyCrop");
3804
- const internalOptions = this._withInternalOperationOptions(operationToken);
3805
- try {
3806
- this._cropRect.setCoords();
3807
- this.originalImage.setCoords();
3808
- const imageBounds = this.originalImage.getBoundingRect(true, true);
3809
- const rawCropBounds = this._getCropRectRawBounds(this._cropRect);
3810
- if (!this._isValidCropRegion(rawCropBounds, imageBounds)) {
3811
- this._reportWarning("applyCrop: crop region is invalid");
3812
- return;
3813
- }
3814
- const rectBounds = this._getCropRectContentBounds(this._cropRect);
3815
- const cropRegion = this._getClampedCanvasRegion(rectBounds, { includePartialPixels: false });
3816
- const shouldPreserveMasks = !!(this.options.crop && this.options.crop.preserveMasksAfterCrop);
3817
- this._restoreCropObjectState();
3818
- let beforeJson;
3819
- try {
3820
- beforeJson = this._serializeCanvasState();
3821
- } catch (error) {
3822
- this._reportError("applyCrop: failed to capture rollback state", error);
3823
- beforeJson = null;
3824
- }
3825
- if (!beforeJson) {
3826
- this._removeCropRect();
3827
- this._cropMode = false;
3828
- this.canvas.selection = !!this._prevSelectionSetting;
3829
- this._prevSelectionSetting = void 0;
3830
- this.canvas.discardActiveObject();
3831
- this._updateUI();
3832
- this.canvas.renderAll();
3833
- return;
3834
- }
3835
- const preservedMasks = [];
3836
- try {
3837
- const masks = this.canvas.getObjects().filter((object) => object.maskId);
3838
- if (masks && masks.length) {
3839
- masks.forEach((mask) => {
3840
- mask.setCoords();
3841
- const maskBounds = mask.getBoundingRect(true, true);
3842
- const intersectsCrop = maskBounds.left < cropRegion.sourceX + cropRegion.sourceWidth && maskBounds.left + maskBounds.width > cropRegion.sourceX && maskBounds.top < cropRegion.sourceY + cropRegion.sourceHeight && maskBounds.top + maskBounds.height > cropRegion.sourceY;
3843
- this._removeLabelForMask(mask);
3844
- this._cleanupMaskEvents(mask);
3845
- this.canvas.remove(mask);
3846
- if (shouldPreserveMasks && intersectsCrop) {
3847
- this._translateObjectByCanvasOffset(mask, -cropRegion.sourceX, -cropRegion.sourceY);
3848
- mask.set({ visible: true });
3849
- preservedMasks.push(mask);
3850
- }
3851
- });
3852
- this._clearMaskPlacementMemory();
3853
- this.canvas.discardActiveObject();
3854
- this.canvas.renderAll();
3855
- }
3856
- } catch (error) {
3857
- await this._restoreStateAfterCropFailure(beforeJson, "applyCrop: failed to prepare masks", error, internalOptions);
3858
- return;
3859
- }
3860
- this._removeCropRect();
3861
- this._cropMode = false;
3862
- this.canvas.selection = !!this._prevSelectionSetting;
3863
- this._prevSelectionSetting = void 0;
3864
- let croppedBase64;
3865
- try {
3866
- croppedBase64 = await this._exportCanvasRegionToDataURL({
3867
- ...cropRegion,
3868
- multiplier: 1,
3869
- quality: this._normalizeQuality(this.options.downsampleQuality),
3870
- format: "jpeg"
3871
- });
3872
- } catch (error) {
3873
- await this._restoreStateAfterCropFailure(beforeJson, "applyCrop: failed to create cropped image", error, internalOptions);
3874
- return;
3875
- }
3876
- try {
3877
- await this.loadImage(croppedBase64, this._withInternalOperationOptions(operationToken, { resetMaskCounter: false }));
3878
- if (preservedMasks.length) {
3879
- preservedMasks.forEach((mask) => {
3880
- this._rebindMaskEvents(mask);
3881
- this.canvas.add(mask);
3882
- this.canvas.bringToFront(mask);
3883
- });
3884
- this._lastMask = preservedMasks[preservedMasks.length - 1];
3885
- this.maskCounter = preservedMasks.reduce((max, mask) => Math.max(max, mask.maskId || 0), this.maskCounter);
3886
- this._updateMaskList();
3887
- this.canvas.renderAll();
3888
- }
3889
- } catch (error) {
3890
- await this._restoreStateAfterCropFailure(beforeJson, "applyCrop: loadImage(croppedBase64) failed", error, internalOptions);
3891
- return;
3892
- }
3893
- let afterJson;
3894
- try {
3895
- afterJson = preservedMasks.length ? this._serializeCanvasState() : this._lastSnapshot;
3896
- } catch (error) {
3897
- this._reportWarning("applyCrop: failed to serialize after state", error);
3898
- afterJson = null;
3899
- }
3900
- try {
3901
- this._pushStateTransition(beforeJson, afterJson);
3902
- } catch (error) {
3903
- this._reportWarning("applyCrop: failed to push history command", error);
3904
- }
3905
- this._updateUI();
3906
- this.canvas.renderAll();
3907
- } finally {
3908
- this._isApplyingCrop = false;
3909
- this._endBusyOperation(operationToken);
3910
- }
3911
- }
3912
- /* ---------- Misc / UI ---------- */
3913
- /**
3914
- * Updates the scale input field in the UI to reflect the current scale.
3915
- * Sets the value (as percentage) if the element is present.
3916
- * @private
3917
- */
3918
- _updateInputs() {
3919
- const scaleInputElement = this._getElement("scalePercentageInput");
3920
- if (scaleInputElement) scaleInputElement.value = Math.round(this.currentScale * 100);
3921
- }
3922
- /**
3923
- * Updates the enabled/disabled state of various UI controls (buttons)
3924
- * based on the current application state (image/mask presence, animation, etc).
3925
- * @private
3926
- */
3927
- _updateUI() {
3928
- if (!this.canvas) return;
3929
- const hasImage = !!this.originalImage;
3930
- const masks = hasImage ? this.canvas.getObjects().filter((object) => object.maskId) : [];
3931
- const hasMasks = masks.length > 0;
3932
- const activeObject = this.canvas.getActiveObject();
3933
- const hasSelectedMask = activeObject && activeObject.maskId;
3934
- const isDefaultTransform = this.currentScale === 1 && this.currentRotation === 0;
3935
- const canUndo = this.historyManager?.canUndo();
3936
- const canRedo = this.historyManager?.canRedo();
3937
- const isInCropMode = !!this._cropMode;
3938
- const isBusy = this.isBusy();
3939
- if (isInCropMode) {
3940
- const cropInteractionKeys = /* @__PURE__ */ new Set(["canvas", "canvasContainer", "imagePlaceholder", "imgPlaceholder"]);
3941
- for (const key of Object.keys(this.elements || {})) {
3942
- const element = this._getElement(key);
3943
- if (!element) continue;
3944
- if (cropInteractionKeys.has(key)) continue;
3945
- if (key === "applyCropButton" || key === "cancelCropButton" || key === "applyCropBtn" || key === "cancelCropBtn") {
3946
- this._setDisabled(key, false);
3947
- } else {
3948
- this._setDisabled(key, true);
3949
- }
3950
- }
3951
- return;
3952
- }
3953
- this._setDisabled("zoomInButton", !hasImage || isBusy || this.currentScale >= this.options.maxScale);
3954
- this._setDisabled("zoomOutButton", !hasImage || isBusy || this.currentScale <= this.options.minScale);
3955
- this._setDisabled("rotateLeftButton", !hasImage || isBusy);
3956
- this._setDisabled("rotateRightButton", !hasImage || isBusy);
3957
- this._setDisabled("createMaskButton", !hasImage || isBusy);
3958
- this._setDisabled("removeSelectedMaskButton", !hasSelectedMask || isBusy);
3959
- this._setDisabled("removeAllMasksButton", !hasMasks || isBusy);
3960
- this._setDisabled("mergeMasksButton", !hasImage || !hasMasks || isBusy);
3961
- this._setDisabled("downloadImageButton", !hasImage || isBusy);
3962
- this._setDisabled("resetImageTransformButton", !hasImage || isDefaultTransform || isBusy);
3963
- this._setDisabled("undoButton", !hasImage || isBusy || !canUndo);
3964
- this._setDisabled("redoButton", !hasImage || isBusy || !canRedo);
3965
- this._setDisabled("enterCropModeButton", !hasImage || isBusy);
3966
- this._setDisabled("applyCropButton", true);
3967
- this._setDisabled("cancelCropButton", true);
3968
- this._setDisabled("scalePercentageInput", !hasImage || isBusy);
3969
- this._setDisabled("rotateLeftDegreesInput", !hasImage || isBusy);
3970
- this._setDisabled("rotateRightDegreesInput", !hasImage || isBusy);
3971
- this._setDisabled("maskList", !hasImage || isBusy);
3972
- this._setDisabled("imageInput", isBusy);
3973
- this._setDisabled("uploadArea", isBusy);
3974
- }
3975
- /**
3976
- * Enables or disables a specific UI element (typically a button) by its key.
3977
- *
3978
- * @param {string} key - Key of the element in this.elements (e.g. 'zoomInButton').
3979
- * @param {boolean} disabled - If true, disables the element; otherwise enables.
3980
- * @private
3981
- */
3982
- _rememberElementDisabledState(key, element) {
3983
- if (!element) return;
3984
- if (!this._elementOriginalDisabledState) this._elementOriginalDisabledState = /* @__PURE__ */ new Map();
3985
- if (this._elementOriginalDisabledState.has(key)) return;
3986
- this._elementOriginalDisabledState.set(key, {
3987
- element,
3988
- hasDisabledProperty: "disabled" in element,
3989
- disabled: "disabled" in element ? !!element.disabled : void 0,
3990
- ariaDisabled: element.getAttribute ? element.getAttribute("aria-disabled") : null,
3991
- pointerEvents: element.style ? element.style.pointerEvents || "" : ""
3992
- });
3993
- }
3994
- _restoreElementDisabledStates() {
3995
- if (!this._elementOriginalDisabledState) return;
3996
- for (const state of this._elementOriginalDisabledState.values()) {
3997
- const element = state && state.element;
3998
- if (!element) continue;
3999
- try {
4000
- if (state.hasDisabledProperty && "disabled" in element) {
4001
- element.disabled = !!state.disabled;
4002
- }
4003
- if (element.getAttribute && element.setAttribute && element.removeAttribute) {
4004
- if (state.ariaDisabled === null) {
4005
- element.removeAttribute("aria-disabled");
4006
- } else {
4007
- element.setAttribute("aria-disabled", state.ariaDisabled);
4008
- }
4009
- }
4010
- if (element.style) element.style.pointerEvents = state.pointerEvents || "";
4011
- } catch (error) {
4012
- void error;
4013
- }
4014
- }
4015
- }
4016
- _setDisabled(key, disabled) {
4017
- const element = this._getElement(key);
4018
- if (!element) return;
4019
- this._rememberElementDisabledState(key, element);
4020
- if ("disabled" in element) {
4021
- element.disabled = !!disabled;
4022
- return;
4023
- }
4024
- if (!this._elementOriginalPointerEvents) this._elementOriginalPointerEvents = /* @__PURE__ */ new Map();
4025
- if (!this._elementOriginalPointerEvents.has(key)) {
4026
- this._elementOriginalPointerEvents.set(key, element.style.pointerEvents || "");
4027
- }
4028
- if (disabled) {
4029
- element.setAttribute("aria-disabled", "true");
4030
- element.style.pointerEvents = "none";
4031
- } else {
4032
- element.removeAttribute("aria-disabled");
4033
- element.style.pointerEvents = this._elementOriginalPointerEvents.get(key) ?? "";
4034
- }
4035
- }
4036
- _isElementDisabled(element) {
4037
- if (!element) return false;
4038
- if ("disabled" in element) return !!element.disabled;
4039
- return element.getAttribute("aria-disabled") === "true";
4040
- }
4041
- /**
4042
- * Updates placeholder and canvas container visibility based on whether an image is loaded.
4043
- * @private
4044
- */
4045
- _updatePlaceholderStatus() {
4046
- this._setPlaceholderVisible(!this.originalImage);
4047
- }
4048
- /**
4049
- * Shows or hides the placeholder and canvas container.
4050
- *
4051
- * @param {boolean} show - If true, displays the placeholder; otherwise displays the canvas container.
4052
- * @private
4053
- */
4054
- _setPlaceholderVisible(show) {
4055
- const shouldShowPlaceholder = !!show && this.options.showPlaceholder !== false;
4056
- if (this.placeholderElement) this._setElementVisible(this.placeholderElement, shouldShowPlaceholder);
4057
- const canvasVisibilityElement = this._getCanvasVisibilityElement();
4058
- if (canvasVisibilityElement && canvasVisibilityElement !== this.placeholderElement) {
4059
- this._setElementVisible(canvasVisibilityElement, !shouldShowPlaceholder);
4060
- }
4061
- }
4062
- _getCanvasVisibilityElement() {
4063
- const wrapperElement = this.canvas && this.canvas.wrapperEl ? this.canvas.wrapperEl : null;
4064
- if (this.containerElement && this.placeholderElement && (this.containerElement === this.placeholderElement || this.containerElement.contains(this.placeholderElement))) {
4065
- return wrapperElement || this.canvasElement;
4066
- }
4067
- return this.containerElement || wrapperElement || this.canvasElement;
4068
- }
4069
- /**
4070
- * Updates element visibility.
4071
- *
4072
- * @param {HTMLElement} element - Element whose visibility should be updated.
4073
- * @param {boolean} isVisible - If true, removes the hidden state.
4074
- * @returns {void}
4075
- * @private
4076
- */
4077
- _setElementVisible(element, isVisible) {
4078
- if (!element) return;
4079
- this._rememberElementVisibility(element);
4080
- element.hidden = !isVisible;
4081
- element.setAttribute("aria-hidden", isVisible ? "false" : "true");
4082
- if (element.classList) {
4083
- element.classList.toggle("d-none", !isVisible);
4084
- }
4085
- }
4086
- _rememberElementVisibility(element) {
4087
- if (!element || this._visibilityStateByElement.has(element)) return;
4088
- this._visibilityStateByElement.set(element, this._captureElementVisibility(element));
4089
- }
4090
- _captureElementVisibility(element) {
4091
- if (!element) return null;
4092
- return {
4093
- hidden: element.hidden,
4094
- ariaHidden: element.getAttribute("aria-hidden"),
4095
- className: element.className
4096
- };
4097
- }
4098
- _restoreElementVisibility(element, state) {
4099
- if (!element || !state) return;
4100
- element.hidden = !!state.hidden;
4101
- if (state.ariaHidden === null) {
4102
- element.removeAttribute("aria-hidden");
4103
- } else {
4104
- element.setAttribute("aria-hidden", state.ariaHidden);
4105
- }
4106
- element.className = state.className || "";
4107
- }
4108
- /**
4109
- * Cleans up and disposes of the canvas and related references.
4110
- * Call this method to free memory and remove canvas listeners when the editor is no longer needed.
4111
- * @public
4112
- */
4113
- dispose() {
4114
- this._disposed = true;
4115
- this._rejectActiveAnimations(new Error("Editor disposed during animation"));
4116
- if (this.animationQueue) {
4117
- this.animationQueue.cancelAll(new Error("Editor disposed"));
4118
- }
4119
- this._isLoading = false;
4120
- this._activeOperationName = null;
4121
- this._activeOperationToken = null;
4122
- try {
4123
- for (const [key, handlers] of Object.entries(this._handlersByElementKey || {})) {
4124
- const element = this._getElement(key);
4125
- if (!element) continue;
4126
- handlers.forEach((handlerRecord) => {
4127
- try {
4128
- element.removeEventListener(handlerRecord.eventName, handlerRecord.handler);
4129
- } catch (error) {
4130
- void error;
4131
- }
4132
- });
4133
- }
4134
- } catch (error) {
4135
- void error;
4136
- }
4137
- if (this._cropRect) this._removeCropRect();
4138
- this._isApplyingCrop = false;
4139
- try {
4140
- this._restoreElementDisabledStates();
4141
- } catch (error) {
4142
- void error;
4143
- }
4144
- if (this.containerElement && this._containerOriginalOverflow) {
4145
- try {
4146
- this._restoreContainerOverflowState();
4147
- } catch (error) {
4148
- void error;
4149
- }
4150
- }
4151
- if (this._visibilityStateByElement) {
4152
- try {
4153
- [this.placeholderElement, this._getCanvasVisibilityElement()].forEach((element) => {
4154
- const state = element ? this._visibilityStateByElement.get(element) : null;
4155
- if (state) this._restoreElementVisibility(element, state);
4156
- });
4157
- } catch (error) {
4158
- void error;
4159
- }
4160
- }
4161
- if (this.canvasElement && this._canvasElementOriginalStyle) {
4162
- try {
4163
- this.canvasElement.style.display = this._canvasElementOriginalStyle.display;
4164
- this.canvasElement.style.width = this._canvasElementOriginalStyle.width;
4165
- this.canvasElement.style.height = this._canvasElementOriginalStyle.height;
4166
- this.canvasElement.style.maxWidth = this._canvasElementOriginalStyle.maxWidth;
4167
- } catch (error) {
4168
- void error;
4169
- }
4170
- }
4171
- if (this.canvas) {
4172
- try {
4173
- this.canvas.getObjects().forEach((object) => {
4174
- if (object && object.maskId) this._cleanupMaskEvents(object);
4175
- });
4176
- } catch (error) {
4177
- void error;
4178
- }
4179
- try {
4180
- this.canvas.dispose();
4181
- } catch (error) {
4182
- void error;
4183
- }
4184
- this.canvas = null;
4185
- this.canvasElement = null;
4186
- this.isImageLoadedToCanvas = false;
4187
- }
4188
- this._handlersByElementKey = {};
4189
- this._elementCache = {};
4190
- this._elementOriginalPointerEvents = /* @__PURE__ */ new Map();
4191
- this._elementOriginalDisabledState = /* @__PURE__ */ new Map();
4192
- this._clearMaskPlacementMemory();
4193
- this.originalImage = null;
4194
- this.baseImageScale = 1;
4195
- this.currentScale = 1;
4196
- this.currentRotation = 0;
4197
- this.isAnimating = false;
4198
- this._isLoading = false;
4199
- this._cropMode = false;
4200
- this._isApplyingCrop = false;
4201
- this._cropRect = null;
4202
- this._cropHandlers = [];
4203
- this._cropPrevEvented = null;
4204
- this._prevSelectionSetting = void 0;
4205
- this._lastContainerViewportSize = null;
4206
- this._initialized = false;
4207
- }
4208
- };
4209
- var AnimationQueue = class {
4210
- /**
4211
- * Creates an empty animation queue.
4212
- */
4213
- constructor() {
4214
- this.animationTasks = [];
4215
- this.isRunning = false;
4216
- this.currentTask = null;
4217
- this._generation = 0;
4218
- }
4219
- /**
4220
- * Adds an animation function to the queue.
4221
- *
4222
- * @param {AnimationTaskCallback} animationFn - Function that returns a value, Promise, or awaitable animation result.
4223
- * @returns {Promise<unknown>} Resolves or rejects with the queued animation result.
4224
- */
4225
- async add(animationFn) {
4226
- return new Promise((resolve, reject) => {
4227
- this.animationTasks.push({ animationFn, resolve, reject, isSettled: false });
4228
- if (!this.isRunning) {
4229
- this._drainQueue();
4230
- }
4231
- });
4232
- }
4233
- isBusy() {
4234
- return this.isRunning || this.animationTasks.length > 0;
4235
- }
4236
- cancelAll(reason = new Error("Animation queue cancelled")) {
4237
- this._generation += 1;
4238
- const cancellationError = reason instanceof Error ? reason : new Error(String(reason));
4239
- const tasks = [
4240
- ...this.currentTask ? [this.currentTask] : [],
4241
- ...this.animationTasks.splice(0)
4242
- ];
4243
- tasks.forEach((task) => {
4244
- if (!task || task.isSettled) return;
4245
- task.isSettled = true;
4246
- task.reject(cancellationError);
4247
- });
4248
- this.isRunning = false;
4249
- this.currentTask = null;
4250
- }
4251
- /**
4252
- * Runs queued animation tasks sequentially until the queue is empty.
4253
- *
4254
- * @private
4255
- * @returns {Promise<void>}
4256
- */
4257
- async _drainQueue() {
4258
- if (this.isRunning) return;
4259
- const generation = this._generation;
4260
- this.isRunning = true;
4261
- try {
4262
- while (this.animationTasks.length > 0 && generation === this._generation) {
4263
- const task = this.animationTasks.shift();
4264
- this.currentTask = task;
4265
- try {
4266
- const result = await task.animationFn();
4267
- if (generation === this._generation && !task.isSettled) {
4268
- task.isSettled = true;
4269
- task.resolve(result);
4270
- }
4271
- } catch (error) {
4272
- if (generation === this._generation && !task.isSettled) {
4273
- task.isSettled = true;
4274
- task.reject(error);
4275
- }
4276
- } finally {
4277
- if (this.currentTask === task) this.currentTask = null;
4278
- }
4279
- }
4280
- } finally {
4281
- if (generation === this._generation) {
4282
- this.isRunning = false;
4283
- this.currentTask = null;
4284
- }
4285
- }
4286
- }
4287
- };
4288
- var Command = class {
4289
- /**
4290
- * @param {HistoryTaskCallback} execute - Function that performs the action.
4291
- * @param {HistoryTaskCallback} undo - Function that reverts the action.
4292
- */
4293
- constructor(execute, undo) {
4294
- this.execute = execute;
4295
- this.undo = undo;
4296
- }
4297
- };
4298
- var HistoryManager = class {
4299
- /**
4300
- * @param {number} [maxSize=50] - Maximum number of commands to keep in history.
4301
- */
4302
- constructor(maxSize = 50) {
4303
- const numericMaxSize = Number(maxSize);
4304
- this.history = [];
4305
- this.currentIndex = -1;
4306
- this.maxSize = Number.isFinite(numericMaxSize) && numericMaxSize > 0 ? Math.floor(numericMaxSize) : 50;
4307
- this.pending = Promise.resolve();
4308
- }
4309
- /**
4310
- * Queues a history task after the previously queued undo/redo task completes.
4311
- *
4312
- * @param {HistoryTaskCallback} task - Task to run after earlier history work settles.
4313
- * @returns {Promise<void>} Resolves or rejects with the queued task result.
4314
- * @private
4315
- */
4316
- enqueue(task) {
4317
- const nextTask = this.pending.then(() => Promise.resolve().then(task));
4318
- this.pending = nextTask.catch(() => void 0);
4319
- return nextTask;
4320
- }
4321
- /**
4322
- * Executes a new command and pushes it onto the history stack.
4323
- * Truncates any "future" history when branching.
4324
- *
4325
- * @param {Command} command The command to execute.
4326
- * @returns {void}
4327
- */
4328
- execute(command) {
4329
- const result = command.execute();
4330
- if (result && typeof result.then === "function") {
4331
- return this.enqueue(() => Promise.resolve(result).then(() => {
4332
- this.push(command);
4333
- }));
4334
- }
4335
- this.push(command);
4336
- return result;
4337
- }
4338
- /**
4339
- * Pushes an already-applied command onto the history stack.
4340
- * Truncates any "future" history when branching.
4341
- *
4342
- * @param {Command} command The command to push.
4343
- * @returns {void}
4344
- */
4345
- push(command) {
4346
- if (this.currentIndex < this.history.length - 1) {
4347
- this.history = this.history.slice(0, this.currentIndex + 1);
4348
- }
4349
- this.history.push(command);
4350
- if (this.history.length > this.maxSize) {
4351
- this.history.shift();
4352
- }
4353
- this.currentIndex = this.history.length - 1;
4354
- }
4355
- /**
4356
- * Checks whether an undo operation is possible.
4357
- *
4358
- * @returns {boolean} True if undo can be performed.
4359
- */
4360
- canUndo() {
4361
- return this.currentIndex >= 0;
4362
- }
4363
- /**
4364
- * Checks whether a redo operation is possible.
4365
- *
4366
- * @returns {boolean} True if redo can be performed.
4367
- */
4368
- canRedo() {
4369
- return this.currentIndex < this.history.length - 1;
4370
- }
4371
- /**
4372
- * Undoes the last executed command if possible.
4373
- *
4374
- * @returns {Promise<void>} Resolves after the undo task completes.
4375
- */
4376
- undo(options = {}) {
4377
- return this.enqueue(async () => {
4378
- if (this.currentIndex >= 0) {
4379
- const index = this.currentIndex;
4380
- await this.history[index].undo(options);
4381
- this.currentIndex = index - 1;
4382
- }
4383
- });
4384
- }
4385
- /**
4386
- * Redoes the next command in history if possible.
4387
- *
4388
- * @returns {Promise<void>} Resolves after the redo task completes.
4389
- */
4390
- redo(options = {}) {
4391
- return this.enqueue(async () => {
4392
- if (this.currentIndex < this.history.length - 1) {
4393
- const index = this.currentIndex + 1;
4394
- await this.history[index].execute(options);
4395
- this.currentIndex = index;
4396
- }
4397
- });
4398
- }
4399
- };
4400
- var image_editor_default = ImageEditor;
4401
-
4402
- // src/esm.js
4403
- var fabricInstance = import_fabric.default && (import_fabric.default.fabric || import_fabric.default.default || import_fabric.default);
4404
- setFabric(fabricInstance);
4405
- var esm_default = image_editor_default;
4406
- if (module.exports && module.exports.default) module.exports = Object.assign(module.exports.default, module.exports);
4407
- //# sourceMappingURL=image-editor.cjs.map