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