@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/README.md
CHANGED
|
@@ -1,28 +1,19 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @bensitu/image-editor
|
|
2
2
|
|
|
3
|
-
[](https://github.com/bensitu/image-editor)
|
|
3
|
+
[](https://github.com/bensitu/image-editor)
|
|
4
4
|
[](https://www.npmjs.com/package/@bensitu/image-editor)
|
|
5
5
|
[](https://www.jsdelivr.com/package/npm/@bensitu/image-editor)
|
|
6
6
|
|
|
7
|
-
A lightweight
|
|
7
|
+
A lightweight, TypeScript-first canvas image editor built on top of
|
|
8
|
+
[Fabric.js](https://fabricjs.com/) v7. `ImageEditor` wraps a Fabric canvas
|
|
9
|
+
with image loading, scale and rotation, mask creation, crop, history
|
|
10
|
+
(undo/redo), and base64/file export — exposed as a single canonical class
|
|
11
|
+
with a stable public surface.
|
|
8
12
|
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
- Image loading from base64 data URLs or file input
|
|
14
|
-
- Zoom in/out and reset transform helpers
|
|
15
|
-
- Rotation with custom degrees or step-based controls
|
|
16
|
-
- Crop mode with optional mask preservation
|
|
17
|
-
- Mask creation, selection, removal, and label support
|
|
18
|
-
- Undo/redo history helpers
|
|
19
|
-
- Merge, download, base64 export, and `File` export helpers
|
|
20
|
-
- Optional DOM/UI binding for common editor controls
|
|
21
|
-
- Large-image downsampling to reduce browser memory pressure
|
|
22
|
-
- Configurable history bounds for large image sessions
|
|
23
|
-
- Centralized error and warning callbacks
|
|
24
|
-
|
|
25
|
-
**Note:** This library uses **fabric.js v5.x**. Bundler and CommonJS entries load Fabric through the peer dependency. Browser global usage needs `window.fabric` available by the time `init()` runs; constructing the editor before Fabric is available is tolerated as long as Fabric is registered before initialization.
|
|
13
|
+
> **v2.0.0 is a behavior-preserving migration.** The v1 deprecated method
|
|
14
|
+
> and property aliases have been removed in favor of the canonical names
|
|
15
|
+
> documented below. See [`CHANGELOG.md`](./CHANGELOG.md) for the complete
|
|
16
|
+
> rename map.
|
|
26
17
|
|
|
27
18
|
## Demo
|
|
28
19
|
|
|
@@ -30,77 +21,109 @@ ImageEditor offers:
|
|
|
30
21
|
|
|
31
22
|
## Features
|
|
32
23
|
|
|
33
|
-
-
|
|
34
|
-
-
|
|
35
|
-
-
|
|
36
|
-
-
|
|
37
|
-
|
|
38
|
-
-
|
|
39
|
-
|
|
40
|
-
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
-
|
|
24
|
+
- TypeScript source with `.d.ts` declarations published alongside the runtime
|
|
25
|
+
- Single canonical class `ImageEditor` exported as both default and named
|
|
26
|
+
- Fabric.js v7 declared as a peer dependency (no bundled Fabric copy)
|
|
27
|
+
- Multi-format publish: ESM (`import`), CommonJS (`require`), UMD (`<script>`),
|
|
28
|
+
TypeScript declarations (`types`)
|
|
29
|
+
- Transactional `loadImage` with rollback on decode, Fabric, downsample, or
|
|
30
|
+
timeout failures
|
|
31
|
+
- Animation queue serializes `scaleImage`, `rotateImage`,
|
|
32
|
+
`resetImageTransform`, `undo`, and `redo` so concurrent clicks never
|
|
33
|
+
interleave
|
|
34
|
+
- Bounded history stack with idempotent dispose
|
|
35
|
+
- Crop session with mask preservation toggle and atomic apply/cancel
|
|
36
|
+
- Base64 and `File` exports with PNG/JPEG/WebP support, configurable
|
|
37
|
+
multiplier, and mask compositing
|
|
38
|
+
|
|
39
|
+
## Requirements
|
|
40
|
+
|
|
41
|
+
- **Node.js**: `>= 20` for development / building from source
|
|
42
|
+
- **Fabric.js**: peer dependency `^7.0.0` (must be installed by the consumer)
|
|
43
|
+
- **Browsers**: modern evergreen (Chrome, Firefox, Safari, Edge). The library
|
|
44
|
+
uses ES2022 features and the Fabric v7 promise-based API.
|
|
45
|
+
- **TypeScript**: strict consumers that compile dependencies with
|
|
46
|
+
`skipLibCheck: false` should include the ES2022 library in `tsconfig.json`.
|
|
47
|
+
Fabric v7.4 declarations also reference `jsdom` types, so install
|
|
48
|
+
`@types/jsdom` when your project type-checks Fabric's declaration files.
|
|
44
49
|
|
|
45
50
|
## Installation
|
|
46
51
|
|
|
47
|
-
### npm / pnpm / yarn
|
|
48
|
-
|
|
49
52
|
```bash
|
|
50
|
-
npm
|
|
53
|
+
npm install @bensitu/image-editor fabric
|
|
51
54
|
# or
|
|
52
55
|
pnpm add @bensitu/image-editor fabric
|
|
53
56
|
# or
|
|
54
57
|
yarn add @bensitu/image-editor fabric
|
|
55
58
|
```
|
|
56
59
|
|
|
57
|
-
|
|
60
|
+
`fabric@^7.0.0` is a peer dependency: install it explicitly so the editor
|
|
61
|
+
resolves the exact version your application uses.
|
|
58
62
|
|
|
59
|
-
|
|
60
|
-
import ImageEditor, {
|
|
61
|
-
ImageEditor as NamedImageEditor,
|
|
62
|
-
} from "@bensitu/image-editor";
|
|
63
|
-
```
|
|
63
|
+
## Module formats and entry points
|
|
64
64
|
|
|
65
|
-
|
|
65
|
+
The package ships a single public entry, resolved by tooling via the
|
|
66
|
+
`exports` map in `package.json`:
|
|
66
67
|
|
|
67
|
-
|
|
68
|
-
|
|
68
|
+
| Consumer | Resolves to |
|
|
69
|
+
| ------------------------------------- | ------------------------------ |
|
|
70
|
+
| ESM (`import`) | `dist/esm/index.js` |
|
|
71
|
+
| CommonJS (`require`) | `dist/cjs/index.cjs` |
|
|
72
|
+
| TypeScript (`types`) | `dist/types/index.d.ts` |
|
|
73
|
+
| UMD (`<script>`, `unpkg`, `jsdelivr`) | `dist/umd/image-editor.umd.js` |
|
|
74
|
+
| `default` fallback | `dist/esm/index.js` |
|
|
69
75
|
|
|
70
|
-
|
|
71
|
-
|
|
76
|
+
The UMD bundle exposes a global named `ImageEditor` and treats `fabric` as an
|
|
77
|
+
external global named `fabric`.
|
|
72
78
|
|
|
73
|
-
|
|
79
|
+
## Dual entry-point convention
|
|
74
80
|
|
|
75
|
-
|
|
81
|
+
`ImageEditor`'s constructor accepts the Fabric module either explicitly (ESM
|
|
82
|
+
consumers) or via `globalThis.fabric` (UMD consumers). The same source ships
|
|
83
|
+
in all four formats:
|
|
76
84
|
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
<script src="https://cdn.jsdelivr.net/npm/fabric@5.5.2/dist/fabric.min.js"></script>
|
|
85
|
+
- **Explicit module form** (recommended for bundled apps): pass the Fabric
|
|
86
|
+
module as the first argument.
|
|
80
87
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
88
|
+
```ts
|
|
89
|
+
import * as fabric from 'fabric';
|
|
90
|
+
import { ImageEditor } from '@bensitu/image-editor';
|
|
91
|
+
|
|
92
|
+
const editor = new ImageEditor(fabric, {
|
|
93
|
+
canvasWidth: 800,
|
|
94
|
+
canvasHeight: 600,
|
|
95
|
+
});
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
- **Global form** (UMD `<script>` consumers): omit the first argument; the
|
|
99
|
+
constructor reads `globalThis.fabric`.
|
|
100
|
+
|
|
101
|
+
```html
|
|
102
|
+
<script src="https://cdn.jsdelivr.net/npm/fabric@7/dist/index.min.js"></script>
|
|
103
|
+
<script src="https://cdn.jsdelivr.net/npm/@bensitu/image-editor/dist/umd/image-editor.umd.js"></script>
|
|
104
|
+
<script>
|
|
105
|
+
const editor = new ImageEditor({
|
|
106
|
+
canvasWidth: 800,
|
|
107
|
+
canvasHeight: 600,
|
|
108
|
+
});
|
|
109
|
+
</script>
|
|
110
|
+
```
|
|
86
111
|
|
|
87
|
-
|
|
112
|
+
If neither form yields a usable Fabric module, the constructor logs a single
|
|
113
|
+
descriptive `console.error` and `init()` and `loadImage()` become no-ops that
|
|
114
|
+
resolve to `undefined`.
|
|
88
115
|
|
|
89
|
-
## Quick
|
|
116
|
+
## Quick start
|
|
90
117
|
|
|
91
|
-
### HTML
|
|
118
|
+
### HTML
|
|
92
119
|
|
|
93
120
|
```html
|
|
94
|
-
|
|
95
|
-
<canvas id="fabricCanvas"></canvas>
|
|
121
|
+
<canvas id="canvas"></canvas>
|
|
96
122
|
|
|
97
|
-
<!-- Optional Controls -->
|
|
98
123
|
<button id="zoomInButton">Zoom In</button>
|
|
99
124
|
<button id="zoomOutButton">Zoom Out</button>
|
|
100
|
-
|
|
101
125
|
<button id="rotateLeftButton">Rotate Left</button>
|
|
102
126
|
<input id="rotateLeftDegreesInput" type="number" value="90" />
|
|
103
|
-
|
|
104
127
|
<button id="rotateRightButton">Rotate Right</button>
|
|
105
128
|
<input id="rotateRightDegreesInput" type="number" value="90" />
|
|
106
129
|
|
|
@@ -112,517 +135,343 @@ Use `dist/image-editor.js` or `dist/image-editor.min.js` for browser global scri
|
|
|
112
135
|
<button id="applyCropButton">Apply Crop</button>
|
|
113
136
|
<button id="cancelCropButton">Cancel Crop</button>
|
|
114
137
|
|
|
138
|
+
<button id="mergeMasksButton">Merge</button>
|
|
139
|
+
<button id="downloadImageButton">Download</button>
|
|
115
140
|
<button id="undoButton">Undo</button>
|
|
116
141
|
<button id="redoButton">Redo</button>
|
|
117
|
-
|
|
118
|
-
<button id="mergeMasksButton">Merge</button>
|
|
119
142
|
<button id="resetImageTransformButton">Reset</button>
|
|
120
|
-
<button id="downloadImageButton">Download</button>
|
|
121
143
|
|
|
122
144
|
<input id="imageInput" type="file" accept="image/*" />
|
|
145
|
+
<ul id="maskList"></ul>
|
|
123
146
|
```
|
|
124
147
|
|
|
125
|
-
###
|
|
148
|
+
### TypeScript / ESM
|
|
126
149
|
|
|
127
|
-
|
|
150
|
+
```ts
|
|
151
|
+
import * as fabric from 'fabric';
|
|
152
|
+
import { ImageEditor } from '@bensitu/image-editor';
|
|
153
|
+
import type { ImageEditorOptions, MaskConfig } from '@bensitu/image-editor';
|
|
128
154
|
|
|
129
|
-
|
|
130
|
-
|
|
155
|
+
const editor = new ImageEditor(fabric, {
|
|
156
|
+
canvasWidth: 800,
|
|
157
|
+
canvasHeight: 600,
|
|
158
|
+
backgroundColor: '#ffffff',
|
|
159
|
+
} satisfies ImageEditorOptions);
|
|
131
160
|
|
|
132
161
|
editor.init({
|
|
133
|
-
|
|
162
|
+
canvas: 'canvas',
|
|
163
|
+
zoomInButton: 'zoomInButton',
|
|
164
|
+
zoomOutButton: 'zoomOutButton',
|
|
165
|
+
rotateLeftButton: 'rotateLeftButton',
|
|
166
|
+
rotateLeftDegreesInput: 'rotateLeftDegreesInput',
|
|
167
|
+
rotateRightButton: 'rotateRightButton',
|
|
168
|
+
rotateRightDegreesInput: 'rotateRightDegreesInput',
|
|
169
|
+
createMaskButton: 'createMaskButton',
|
|
170
|
+
removeSelectedMaskButton: 'removeSelectedMaskButton',
|
|
171
|
+
removeAllMasksButton: 'removeAllMasksButton',
|
|
172
|
+
enterCropModeButton: 'enterCropModeButton',
|
|
173
|
+
applyCropButton: 'applyCropButton',
|
|
174
|
+
cancelCropButton: 'cancelCropButton',
|
|
175
|
+
mergeMasksButton: 'mergeMasksButton',
|
|
176
|
+
downloadImageButton: 'downloadImageButton',
|
|
177
|
+
undoButton: 'undoButton',
|
|
178
|
+
redoButton: 'redoButton',
|
|
179
|
+
resetImageTransformButton: 'resetImageTransformButton',
|
|
180
|
+
imageInput: 'imageInput',
|
|
181
|
+
maskList: 'maskList',
|
|
134
182
|
});
|
|
135
|
-
```
|
|
136
183
|
|
|
137
|
-
|
|
184
|
+
// Load an image programmatically (base64 data URL).
|
|
185
|
+
await editor.loadImage('data:image/jpeg;base64,...');
|
|
138
186
|
|
|
139
|
-
|
|
187
|
+
// Add a rectangular mask, then export the result as base64.
|
|
188
|
+
const mask: MaskConfig = { shape: 'rect', width: 120, height: 80, left: '25%', top: '25%' };
|
|
189
|
+
editor.createMask(mask);
|
|
140
190
|
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
```javascript
|
|
144
|
-
const editor = new ImageEditor({
|
|
145
|
-
canvasWidth: 800,
|
|
146
|
-
canvasHeight: 600,
|
|
147
|
-
backgroundColor: "#ffffff",
|
|
148
|
-
initialImageBase64: null
|
|
149
|
-
});
|
|
191
|
+
const dataUrl = await editor.exportImageBase64({ fileType: 'png' });
|
|
150
192
|
```
|
|
151
193
|
|
|
152
|
-
|
|
194
|
+
### CommonJS
|
|
153
195
|
|
|
154
|
-
|
|
196
|
+
```js
|
|
197
|
+
const fabric = require('fabric');
|
|
198
|
+
const { ImageEditor } = require('@bensitu/image-editor');
|
|
155
199
|
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
```javascript
|
|
159
|
-
const editor = new ImageEditor({
|
|
160
|
-
// Layout mode. Enable only one layout mode at a time.
|
|
161
|
-
expandCanvasToImage: false,
|
|
162
|
-
fitImageToCanvas: true,
|
|
163
|
-
coverImageToCanvas: false,
|
|
164
|
-
|
|
165
|
-
// Image loading / performance.
|
|
166
|
-
downsampleOnLoad: true,
|
|
167
|
-
initialImageBase64: null,
|
|
168
|
-
|
|
169
|
-
// Mask behavior.
|
|
170
|
-
maskRotatable: true,
|
|
171
|
-
maskLabelOnSelect: true,
|
|
172
|
-
maskLabelOffset: 5,
|
|
173
|
-
|
|
174
|
-
// UI behavior.
|
|
175
|
-
backgroundColor: "transparent",
|
|
176
|
-
showPlaceholder: true,
|
|
177
|
-
animationDuration: 100,
|
|
178
|
-
|
|
179
|
-
// Export behavior.
|
|
180
|
-
exportImageAreaByDefault: true
|
|
181
|
-
});
|
|
182
|
-
|
|
183
|
-
editor.init({
|
|
184
|
-
canvas: "fabricCanvas",
|
|
185
|
-
canvasContainer: null,
|
|
186
|
-
imagePlaceholder: "imagePlaceholder",
|
|
187
|
-
scalePercentageInput: "scalePercentageInput",
|
|
188
|
-
rotateLeftButton: "rotateLeftButton",
|
|
189
|
-
rotateRightButton: "rotateRightButton",
|
|
190
|
-
rotateLeftDegreesInput: "rotateLeftDegreesInput",
|
|
191
|
-
rotateRightDegreesInput: "rotateRightDegreesInput",
|
|
192
|
-
createMaskButton: null,
|
|
193
|
-
removeSelectedMaskButton: "removeSelectedMaskButton",
|
|
194
|
-
removeAllMasksButton: "removeAllMasksButton",
|
|
195
|
-
mergeMasksButton: "mergeMasksButton",
|
|
196
|
-
downloadImageButton: "downloadImageButton",
|
|
197
|
-
maskList: "maskList",
|
|
198
|
-
enterCropModeButton: "enterCropModeButton",
|
|
199
|
-
applyCropButton: "applyCropButton",
|
|
200
|
-
cancelCropButton: "cancelCropButton",
|
|
201
|
-
resetImageTransformButton: "resetImageTransformButton",
|
|
202
|
-
imageInput: null,
|
|
203
|
-
uploadArea: null
|
|
204
|
-
});
|
|
205
|
-
```
|
|
206
|
-
|
|
207
|
-
The demo binds `createMaskButton`, `imageInput`, and `uploadArea` itself, so it passes `null` for those built-in bindings. Regular integrations can omit those keys to use the default IDs, or pass `null` to disable any optional binding.
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
### Loading an Image Manually
|
|
211
|
-
|
|
212
|
-
```javascript
|
|
213
|
-
async function loadImageDataUrl(imageBase64) {
|
|
214
|
-
try {
|
|
215
|
-
await editor.loadImage(imageBase64);
|
|
216
|
-
} catch (error) {
|
|
217
|
-
console.error("Image could not be loaded:", error);
|
|
218
|
-
}
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
loadImageDataUrl("data:image/jpeg;base64,...");
|
|
200
|
+
const editor = new ImageEditor(fabric, { canvasWidth: 800, canvasHeight: 600 });
|
|
222
201
|
```
|
|
223
202
|
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
When creating the editor instance, pass an options object to override defaults.
|
|
229
|
-
|
|
230
|
-
| Option | Default | Description |
|
|
231
|
-
| ----------------------------- | ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
232
|
-
| `canvasWidth` | `800` | Initial canvas width in pixels. |
|
|
233
|
-
| `canvasHeight` | `600` | Initial canvas height in pixels. |
|
|
234
|
-
| `backgroundColor` | `transparent` | Canvas background color. |
|
|
235
|
-
| `animationDuration` | `300` | Animation duration for scale and rotation operations, in milliseconds. |
|
|
236
|
-
| `minScale` | `0.1` | Minimum image scale factor. |
|
|
237
|
-
| `maxScale` | `5.0` | Maximum image scale factor. |
|
|
238
|
-
| `scaleStep` | `0.05` | Scale increment/decrement used by zoom controls. |
|
|
239
|
-
| `rotationStep` | `90` | Default rotation step in degrees. |
|
|
240
|
-
| `expandCanvasToImage` | `true` | Expand the canvas to the loaded image size. |
|
|
241
|
-
| `fitImageToCanvas` | `false` | Fit the loaded image inside the visible canvas viewport. |
|
|
242
|
-
| `coverImageToCanvas` | `false` | Scale the image to cover the visible canvas viewport, allowing overflow when needed. |
|
|
243
|
-
| `downsampleOnLoad` | `true` | Downsample large images before rendering. |
|
|
244
|
-
| `downsampleMaxWidth` | `4000` | Maximum source image width before downsampling. |
|
|
245
|
-
| `downsampleMaxHeight` | `3000` | Maximum source image height before downsampling. |
|
|
246
|
-
| `downsampleQuality` | `0.92` | JPEG/WebP quality used when downsampling. `0` is valid and is preserved. |
|
|
247
|
-
| `preserveSourceFormat` | `true` | Preserve the source image format where possible during downsampling. |
|
|
248
|
-
| `downsampleMimeType` | `null` | Optional output MIME type for downsampled images. Supported values include `jpeg`, `jpg`, `png`, `webp`, `image/jpeg`, `image/png`, and `image/webp`. |
|
|
249
|
-
| `imageLoadTimeoutMs` | `30000` | Timeout for image decode/load operations. |
|
|
250
|
-
| `exportMultiplier` | `1` | Default scale multiplier for export. |
|
|
251
|
-
| `maxExportPixels` | `50000000` | Maximum output pixel count allowed per export after applying the multiplier. |
|
|
252
|
-
| `maxHistorySize` | `50` | Maximum undo/redo history entries to retain. Large base64 source images can make each history snapshot expensive. |
|
|
253
|
-
| `exportImageAreaByDefault` | `true` | Export only the image area by default instead of the full canvas. |
|
|
254
|
-
| `defaultMaskWidth` | `50` | Default mask width in pixels. |
|
|
255
|
-
| `defaultMaskHeight` | `80` | Default mask height in pixels. |
|
|
256
|
-
| `maskRotatable` | `false` | Whether masks can be rotated. |
|
|
257
|
-
| `maskLabelOnSelect` | `true` | Show the mask label when a mask is selected. |
|
|
258
|
-
| `maskLabelOffset` | `3` | Offset for mask labels from the mask's top-left corner. |
|
|
259
|
-
| `maskName` | `mask` | Prefix for mask names and labels. |
|
|
260
|
-
| `groupSelection` | `false` | Whether Fabric can select multiple masks as an active selection. |
|
|
261
|
-
| `label.getText` | `(mask) => mask.maskName` | Callback for custom label text. The second argument is the mask's stable zero-based creation index (`mask.maskId - 1`). |
|
|
262
|
-
| `label.create` | `undefined` | Optional callback that returns a custom Fabric label object for the selected mask. Invalid or throwing callbacks fall back to the default label. |
|
|
263
|
-
| `label.textOptions` | see defaults | Fabric text options merged into the default label when `label.create` is not used or falls back. |
|
|
264
|
-
| `showPlaceholder` | `true` | Show a placeholder when no image is loaded. When `false`, internal load, rollback, and status paths keep the placeholder hidden. |
|
|
265
|
-
| `initialImageBase64` | `null` | Base64 data URL to auto-load during initialization. |
|
|
266
|
-
| `defaultDownloadFileName` | `edited_image.jpg` | Default file name for downloads. |
|
|
267
|
-
| `crop.minWidth` | `100` | Minimum crop rectangle width, clamped to the current image bounds. |
|
|
268
|
-
| `crop.minHeight` | `100` | Minimum crop rectangle height, clamped to the current image bounds. |
|
|
269
|
-
| `crop.padding` | `10` | Initial inset from the image bounds when entering crop mode. |
|
|
270
|
-
| `crop.hideMasksDuringCrop` | `true` | Hide editable masks while crop mode is active. |
|
|
271
|
-
| `crop.preserveMasksAfterCrop` | `false` | Keep masks that intersect the crop area, shifted into the cropped canvas. Merge masks first if they should be baked into the image pixels. |
|
|
272
|
-
| `crop.allowRotationOfCropRect` | `false` | Reserved for future rotated crop support. In v1.x, crop rectangles stay axis-aligned; setting this to `true` reports a warning and rotation remains disabled. |
|
|
273
|
-
| `onImageLoaded` | `null` | Callback invoked after an image load is committed. Callback errors are reported as warnings and do not roll back the loaded image. |
|
|
274
|
-
| `onError` | `null` | Callback invoked for recoverable internal errors. |
|
|
275
|
-
| `onWarning` | `null` | Callback invoked for recoverable internal warnings. |
|
|
276
|
-
|
|
277
|
-
`expandCanvasToImage`, `fitImageToCanvas`, and `coverImageToCanvas` are mutually exclusive layout modes. If more than one is enabled, the editor reports a warning and uses this precedence: `fitImageToCanvas`, then `coverImageToCanvas`, then `expandCanvasToImage`.
|
|
278
|
-
|
|
279
|
-
Numeric runtime options are normalized during construction. Non-finite or invalid dimensions, scale limits, export limits, crop sizes, label offsets, and history sizes fall back to safe defaults. `animationDuration: 0` and `downsampleQuality: 0` remain valid.
|
|
280
|
-
|
|
281
|
-
## DOM Binding Keys
|
|
282
|
-
|
|
283
|
-
`init(idMap)` binds editor behavior to DOM elements by ID. All keys are optional when the default IDs are present. Optional bindings can also be set to `null` to disable the built-in listener for that element.
|
|
284
|
-
|
|
285
|
-
| Key | Description |
|
|
286
|
-
| --------------------------- | -------------------------------------------------------------- |
|
|
287
|
-
| `canvas` | Required canvas element ID. |
|
|
288
|
-
| `canvasContainer` | Optional scrollable viewport/container element ID. |
|
|
289
|
-
| `imagePlaceholder` | Optional placeholder element shown when no image is loaded. |
|
|
290
|
-
| `scalePercentageInput` | Optional element used to display the current scale percentage. |
|
|
291
|
-
| `rotateLeftDegreesInput` | Optional input used by the rotate-left button. |
|
|
292
|
-
| `rotateRightDegreesInput` | Optional input used by the rotate-right button. |
|
|
293
|
-
| `rotateLeftButton` | Rotate image left. |
|
|
294
|
-
| `rotateRightButton` | Rotate image right. |
|
|
295
|
-
| `createMaskButton` | Create a new mask. |
|
|
296
|
-
| `removeSelectedMaskButton` | Remove the currently selected mask. |
|
|
297
|
-
| `removeAllMasksButton` | Remove all masks. |
|
|
298
|
-
| `mergeMasksButton` | Merge masks into the base image. |
|
|
299
|
-
| `downloadImageButton` | Download the edited image. |
|
|
300
|
-
| `maskList` | Optional mask list container. |
|
|
301
|
-
| `zoomInButton` | Zoom in. |
|
|
302
|
-
| `zoomOutButton` | Zoom out. |
|
|
303
|
-
| `resetImageTransformButton` | Reset scale and rotation. |
|
|
304
|
-
| `undoButton` | Undo the last state change. |
|
|
305
|
-
| `redoButton` | Redo the next state change. |
|
|
306
|
-
| `imageInput` | File input used to load images. |
|
|
307
|
-
| `uploadArea` | Optional clickable upload area that triggers the file input. |
|
|
308
|
-
| `enterCropModeButton` | Enter crop mode. |
|
|
309
|
-
| `applyCropButton` | Apply the current crop rectangle. |
|
|
310
|
-
| `cancelCropButton` | Cancel crop mode. |
|
|
311
|
-
|
|
312
|
-
### Legacy DOM Binding Keys
|
|
313
|
-
|
|
314
|
-
The following DOM binding keys remain supported in `1.x` for compatibility, but are deprecated and will be removed in `v2.0.0`.
|
|
315
|
-
|
|
316
|
-
| Deprecated key | Use instead |
|
|
317
|
-
| -------------------- | --------------------------- |
|
|
318
|
-
| `imgPlaceholder` | `imagePlaceholder` |
|
|
319
|
-
| `scaleRate` | `scalePercentageInput` |
|
|
320
|
-
| `rotationLeftInput` | `rotateLeftDegreesInput` |
|
|
321
|
-
| `rotationRightInput` | `rotateRightDegreesInput` |
|
|
322
|
-
| `rotateLeftBtn` | `rotateLeftButton` |
|
|
323
|
-
| `rotateRightBtn` | `rotateRightButton` |
|
|
324
|
-
| `addMaskBtn` | `createMaskButton` |
|
|
325
|
-
| `removeMaskBtn` | `removeSelectedMaskButton` |
|
|
326
|
-
| `removeAllMasksBtn` | `removeAllMasksButton` |
|
|
327
|
-
| `mergeBtn` | `mergeMasksButton` |
|
|
328
|
-
| `downloadBtn` | `downloadImageButton` |
|
|
329
|
-
| `zoomInBtn` | `zoomInButton` |
|
|
330
|
-
| `zoomOutBtn` | `zoomOutButton` |
|
|
331
|
-
| `resetBtn` | `resetImageTransformButton` |
|
|
332
|
-
| `undoBtn` | `undoButton` |
|
|
333
|
-
| `redoBtn` | `redoButton` |
|
|
334
|
-
| `cropBtn` | `enterCropModeButton` |
|
|
335
|
-
| `applyCropBtn` | `applyCropButton` |
|
|
336
|
-
| `cancelCropBtn` | `cancelCropButton` |
|
|
337
|
-
|
|
338
|
-
## API Methods
|
|
339
|
-
|
|
340
|
-
| Method | Returns | Description |
|
|
341
|
-
| --------------------------------- | ----------------------- | --------------------------------------------------------------------------------------------------------------------- |
|
|
342
|
-
| `init(idMap)` | `void` | Bind the editor to DOM elements. Pass IDs in an object. |
|
|
343
|
-
| `dispose()` | `void` | Cleans up the canvas, listeners, crop state, animations, and captured DOM visibility/disabled/pointer-events state. |
|
|
344
|
-
| `loadImage(imageBase64, options)` | `Promise<void>` | Load an image from a base64 data URL. Resolves after the Fabric image is on the canvas. |
|
|
345
|
-
| `isImageLoaded()` | `boolean` | Return whether a valid image is loaded on the canvas. |
|
|
346
|
-
| `isBusy()` | `boolean` | Return whether the editor is loading, animating, cropping, applying crop, or running another compound operation. |
|
|
347
|
-
| `scaleImage(factor)` | `Promise<void>` | Scale the image to the given finite factor relative to the base scale. Non-finite values are ignored. |
|
|
348
|
-
| `rotateImage(degrees)` | `Promise<void>` | Rotate the image to the given finite angle in degrees. Non-finite values are ignored. |
|
|
349
|
-
| `resetImageTransform()` | `Promise<void>` | Reset scale to `1` and rotation to `0`. |
|
|
350
|
-
| `undo()` | `Promise<void>` | Undo the last state change. Resolves after the canvas state is restored. |
|
|
351
|
-
| `redo()` | `Promise<void>` | Redo the next state change. Resolves after the canvas state is restored. |
|
|
352
|
-
| `createMask(config)` | `fabric.Object \| null` | Create a mask on the canvas. Config can include shape, width, height, color, opacity, position, style, and callbacks. |
|
|
353
|
-
| `removeSelectedMask()` | `void` | Remove the currently selected mask or selected masks. |
|
|
354
|
-
| `removeAllMasks(options)` | `void` | Remove all masks from the canvas. |
|
|
355
|
-
| `enterCropMode()` | `void` | Create a resizable/movable selection rectangle on top of the image. |
|
|
356
|
-
| `cancelCrop()` | `void` | Cancel crop mode and remove the temporary selection rectangle. No-ops while `applyCrop()` is already running. |
|
|
357
|
-
| `applyCrop()` | `Promise<void>` | Apply the current valid crop rectangle to the canvas. Invalid crop regions warn and keep crop mode active. |
|
|
358
|
-
| `mergeMasks()` | `Promise<void>` | Merge masks into the base image on the canvas. |
|
|
359
|
-
| `downloadImage(fileName)` | `void` | Download the edited image as a file. |
|
|
360
|
-
| `exportImageBase64(options)` | `Promise<string>` | Export an image data URL. `fileType` can be `jpeg`, `jpg`, `png`, `webp`, or a supported image MIME type. |
|
|
361
|
-
| `exportImageFile(options)` | `Promise<File>` | Export the current canvas as a `File` object. |
|
|
362
|
-
| `saveState()` | `void` | Save the current editor state to history. Usually called internally after supported edits. |
|
|
363
|
-
| `loadFromState(serializedState)` | `Promise<void>` | Restore the editor from a serialized canvas/editor state. |
|
|
364
|
-
|
|
365
|
-
Deprecated method aliases are still available for compatibility and will be removed in `v2.0.0`.
|
|
366
|
-
|
|
367
|
-
| Deprecated method | Use instead |
|
|
368
|
-
| ------------------------- | ---------------------------- |
|
|
369
|
-
| `reset()` | `resetImageTransform()` |
|
|
370
|
-
| `addMask(config)` | `createMask(config)` |
|
|
371
|
-
| `merge()` | `mergeMasks()` |
|
|
372
|
-
| `getImageBase64(options)` | `exportImageBase64(options)` |
|
|
373
|
-
|
|
374
|
-
## Mask Configuration
|
|
375
|
-
|
|
376
|
-
`createMask(config)` accepts an optional configuration object.
|
|
377
|
-
|
|
378
|
-
Invalid mask configuration, such as non-finite numeric values, non-positive dimensions/radii, duplicate or zero-area polygon points, malformed polygon points, throwing custom generators, or custom generators that do not return a Fabric object, is rejected with a warning and returns `null` without mutating the canvas or history.
|
|
379
|
-
|
|
380
|
-
| Option | Description |
|
|
381
|
-
| ------------------ | ------------------------------------------------------------------------------------------ |
|
|
382
|
-
| `shape` | Mask shape. Built-in values include `rect`, `circle`, `ellipse`, and `polygon`. |
|
|
383
|
-
| `width` / `height` | Mask size in pixels, percentage string, or resolver callback. |
|
|
384
|
-
| `radius` | Circle radius in pixels, percentage string, or resolver callback. |
|
|
385
|
-
| `rx` / `ry` | Ellipse radius or rectangle corner radius. |
|
|
386
|
-
| `points` | Polygon points as `{ x, y }` objects or `[x, y]` tuples. |
|
|
387
|
-
| `left` / `top` | Mask position in pixels, percentage string, or resolver callback. |
|
|
388
|
-
| `angle` | Initial rotation angle in degrees. |
|
|
389
|
-
| `color` | Fill color. |
|
|
390
|
-
| `alpha` | Opacity from `0` to `1`. |
|
|
391
|
-
| `selectable` | Whether the mask can be selected. |
|
|
392
|
-
| `hasControls` | Whether Fabric transform controls are shown. |
|
|
393
|
-
| `styles` | Additional Fabric style properties, such as `stroke`, `strokeWidth`, or `strokeDashArray`. |
|
|
394
|
-
| `fabricGenerator` | Factory callback for creating a custom Fabric object. |
|
|
395
|
-
| `onCreate` | Callback invoked after the mask is added to the canvas. |
|
|
396
|
-
|
|
397
|
-
`fabricGenerator` runs before the mask is committed. If it throws or returns an invalid object, `createMask()` reports a warning and returns `null`. `onCreate` runs after the mask and history entry are committed; if it throws, the mask remains on the canvas and the error is reported as a warning.
|
|
398
|
-
|
|
399
|
-
Label callbacks are also isolated. If `label.create` throws or returns an invalid object, the editor uses the default Fabric text label. If `label.getText` throws, the editor uses `mask.maskName`.
|
|
400
|
-
|
|
401
|
-
Example:
|
|
402
|
-
|
|
403
|
-
```javascript
|
|
404
|
-
const mask = editor.createMask({
|
|
405
|
-
shape: "rect",
|
|
406
|
-
width: 120,
|
|
407
|
-
height: 80,
|
|
408
|
-
left: 20,
|
|
409
|
-
top: 20,
|
|
410
|
-
color: "rgba(0, 0, 0, 0.5)",
|
|
411
|
-
alpha: 0.5,
|
|
412
|
-
});
|
|
413
|
-
```
|
|
414
|
-
|
|
415
|
-
## Crop Behavior
|
|
416
|
-
|
|
417
|
-
By default, applying crop removes unmerged masks.
|
|
418
|
-
|
|
419
|
-
This is intentional: an unmerged mask is still an editable overlay object, not part of the image pixels. When `crop.preserveMasksAfterCrop` is `false`, applying crop discards unmerged masks instead of trying to keep or partially crop those overlay objects.
|
|
203
|
+
In v2, `require('@bensitu/image-editor')` returns a namespace object with
|
|
204
|
+
`ImageEditor`, `default`, and `isMaskObject`; it does not return the
|
|
205
|
+
constructor directly.
|
|
420
206
|
|
|
421
|
-
|
|
207
|
+
## Public API
|
|
422
208
|
|
|
423
|
-
|
|
209
|
+
`ImageEditor` is the only public class. The package barrel re-exports it as
|
|
210
|
+
both the default export and a named export, alongside `isMaskObject` and the
|
|
211
|
+
documented public types. Internal helpers (animation queue, command, history
|
|
212
|
+
manager, controllers, services, managers, utility modules) are intentionally
|
|
213
|
+
not exported and may change without notice.
|
|
424
214
|
|
|
425
|
-
|
|
215
|
+
### Constructor
|
|
426
216
|
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
- **Keep the default `crop.preserveMasksAfterCrop: false`** when unmerged masks should be discarded by crop.
|
|
431
|
-
|
|
432
|
-
### Preserve editable masks after crop
|
|
433
|
-
|
|
434
|
-
```javascript
|
|
435
|
-
const editor = new ImageEditor({
|
|
436
|
-
crop: {
|
|
437
|
-
preserveMasksAfterCrop: true,
|
|
438
|
-
},
|
|
439
|
-
});
|
|
217
|
+
```ts
|
|
218
|
+
new ImageEditor(fabric: FabricModule, options?: ImageEditorOptions)
|
|
219
|
+
new ImageEditor(options?: ImageEditorOptions) // UMD: reads globalThis.fabric
|
|
440
220
|
```
|
|
441
221
|
|
|
442
|
-
###
|
|
222
|
+
### Lifecycle
|
|
443
223
|
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
await editor.applyCrop();
|
|
449
|
-
} catch (error) {
|
|
450
|
-
console.error("Crop workflow failed:", error);
|
|
451
|
-
}
|
|
452
|
-
```
|
|
224
|
+
| Method | Description |
|
|
225
|
+
| -------------- | ------------------------------------------------------------------------------------ |
|
|
226
|
+
| `init(idMap?)` | Bind the editor to DOM elements. Pass an `ElementIdMap`; any key may be omitted. |
|
|
227
|
+
| `dispose()` | Tear down the editor, drain DOM bindings, and dispose the Fabric canvas. Idempotent. |
|
|
453
228
|
|
|
454
|
-
|
|
229
|
+
### Image loading
|
|
455
230
|
|
|
456
|
-
|
|
231
|
+
| Method | Description |
|
|
232
|
+
| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
233
|
+
| `loadImage(base64, options?)` | Load an image from a `data:image/...` URL. Returns `Promise<void>`. Transactional: any failure restores the prior canvas, scroll, overflow, and snapshot state. |
|
|
234
|
+
| `isImageLoaded()` | Returns `true` if a valid image is currently loaded on the canvas. |
|
|
235
|
+
| `isBusy()` | Returns `true` while the editor is loading, animating, or in crop mode. |
|
|
236
|
+
| `setLayoutMode(mode)` | Select the layout strategy for future image loads. `mode` is `'fit'`, `'cover'`, or `'expand'`. |
|
|
457
237
|
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
fileType: "jpeg",
|
|
462
|
-
quality: 0.92,
|
|
463
|
-
multiplier: 1,
|
|
464
|
-
});
|
|
238
|
+
`LoadImageOptions` currently includes `preserveScroll?: boolean` for
|
|
239
|
+
preserving the container's scroll position across both successful loads and
|
|
240
|
+
rollback paths.
|
|
465
241
|
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
console.error("Export failed:", error);
|
|
469
|
-
}
|
|
470
|
-
```
|
|
242
|
+
Use `setLayoutMode()` instead of mutating internal options when a UI lets users
|
|
243
|
+
choose how the next image should be placed:
|
|
471
244
|
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
const file = await editor.exportImageFile({
|
|
477
|
-
fileName: "edited_image.jpg",
|
|
478
|
-
fileType: "jpeg",
|
|
479
|
-
quality: 0.92,
|
|
480
|
-
mergeMask: true,
|
|
481
|
-
});
|
|
482
|
-
|
|
483
|
-
console.log(file);
|
|
484
|
-
} catch (error) {
|
|
485
|
-
console.error("File export failed:", error);
|
|
486
|
-
}
|
|
245
|
+
```ts
|
|
246
|
+
editor.setLayoutMode('fit');
|
|
247
|
+
editor.setLayoutMode('cover');
|
|
248
|
+
editor.setLayoutMode('expand');
|
|
487
249
|
```
|
|
488
250
|
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
251
|
+
File-input helpers accept JPG, PNG, WebP, GIF, and BMP files. GIF and BMP are
|
|
252
|
+
decoded as static raster input for canvas editing; GIF animation and BMP/GIF
|
|
253
|
+
source-format preservation are not retained. Export output remains controlled by
|
|
254
|
+
the JPEG, PNG, or WebP export options.
|
|
255
|
+
|
|
256
|
+
### Transforms
|
|
257
|
+
|
|
258
|
+
| Method | Description |
|
|
259
|
+
| ----------------------- | --------------------------------------------------------------------------------------------------- |
|
|
260
|
+
| `scaleImage(factor)` | Scale to `factor` (clamped to `[minScale, maxScale]`). Non-finite values are no-ops. Animated. |
|
|
261
|
+
| `rotateImage(degrees)` | Rotate to `degrees`. Non-finite values resolve without changing canvas state. Animated. |
|
|
262
|
+
| `resetImageTransform()` | Animate to scale 1 and rotation 0. Records exactly one history entry covering the entire transform. |
|
|
263
|
+
|
|
264
|
+
### Masks
|
|
265
|
+
|
|
266
|
+
| Method | Description |
|
|
267
|
+
| -------------------------- | ----------------------------------------------------------------------------- |
|
|
268
|
+
| `createMask(config?)` | The single mask-creation entry point. Returns the new `MaskObject` or `null`. |
|
|
269
|
+
| `removeSelectedMask()` | Remove the currently selected mask and push one history entry. |
|
|
270
|
+
| `removeAllMasks(options?)` | Remove every mask. `options.saveHistory` defaults to `true`. |
|
|
271
|
+
|
|
272
|
+
`MaskConfig` supports rect, circle, ellipse, polygon, and a custom
|
|
273
|
+
`fabricGenerator`. Falsy values in `styles` (`0`, `false`, `null`, `''`,
|
|
274
|
+
`NaN`) are applied verbatim.
|
|
275
|
+
|
|
276
|
+
### Crop
|
|
277
|
+
|
|
278
|
+
| Method | Description |
|
|
279
|
+
| ----------------- | ------------------------------------------------------------------------------------ |
|
|
280
|
+
| `enterCropMode()` | Add an interactive crop rectangle on top of the image. |
|
|
281
|
+
| `applyCrop()` | Apply the current crop region. Atomic: failure rolls back to the pre-crop snapshot. |
|
|
282
|
+
| `cancelCrop()` | Cancel crop mode and restore the prior canvas state without pushing a history entry. |
|
|
283
|
+
|
|
284
|
+
### Merge and export
|
|
285
|
+
|
|
286
|
+
| Method | Description |
|
|
287
|
+
| ----------------------------- | ---------------------------------------------------------------------------------------------- |
|
|
288
|
+
| `mergeMasks()` | Bake masks into the base image atomically. Returns `Promise<void>`. |
|
|
289
|
+
| `exportImageBase64(options?)` | Returns `Promise<string>` (data URL). Resolves to `''` with a warning when no image is loaded. |
|
|
290
|
+
| `exportImageFile(options?)` | Returns `Promise<File>`. Rejects when no image is loaded. |
|
|
291
|
+
| `downloadImage(fileName?)` | Triggers a browser download. No-op when no image is loaded. |
|
|
292
|
+
|
|
293
|
+
`Base64ExportOptions` and `ImageFileExportOptions` separate mask compositing
|
|
294
|
+
from export region selection:
|
|
295
|
+
|
|
296
|
+
| Option | Default | Description |
|
|
297
|
+
| ------------ | --------- | --------------------------------------------------------------------------- |
|
|
298
|
+
| `mergeMask` | `true` | Flatten masks into exported pixels. Mask labels are never exported. |
|
|
299
|
+
| `exportArea` | `'image'` | `'image'` clips to the image bounding box; `'canvas'` exports the canvas. |
|
|
300
|
+
| `fileType` | `'jpeg'` | `'png'`, `'jpeg'`, `'jpg'`, `'webp'`, or matching full MIME strings. |
|
|
301
|
+
| `format` | `'jpeg'` | Alias for `fileType` on `exportImageBase64`; `fileType` wins when both set. |
|
|
302
|
+
| `quality` | `0.92` | Lossy quality clamped to `[0, 1]`; ignored for PNG. |
|
|
303
|
+
| `multiplier` | `1` | Output resolution multiplier. |
|
|
304
|
+
| `fileName` | option | `ImageFileExportOptions` only. Defaults to `defaultDownloadFileName`. |
|
|
305
|
+
|
|
306
|
+
```ts
|
|
307
|
+
await editor.exportImageBase64({ exportArea: 'image', mergeMask: true });
|
|
308
|
+
await editor.exportImageBase64({ exportArea: 'image', mergeMask: false });
|
|
309
|
+
await editor.exportImageBase64({ exportArea: 'canvas', mergeMask: true });
|
|
310
|
+
await editor.exportImageBase64({ exportArea: 'canvas', mergeMask: false });
|
|
495
311
|
```
|
|
496
312
|
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
313
|
+
### State and history
|
|
314
|
+
|
|
315
|
+
| Method | Description |
|
|
316
|
+
| ------------------------- | ------------------------------------------------------------------------------------- |
|
|
317
|
+
| `saveState()` | Capture a snapshot of the canvas plus editor metadata into the history stack. |
|
|
318
|
+
| `loadFromState(snapshot)` | Restore canvas, masks, and editor metadata from a snapshot. Returns `Promise<void>`. |
|
|
319
|
+
| `undo()` | Undo the last state change. Routed through the animation queue. No-op while disposed. |
|
|
320
|
+
| `redo()` | Redo the next state change. Routed through the animation queue. No-op while disposed. |
|
|
321
|
+
|
|
322
|
+
## Configuration options
|
|
323
|
+
|
|
324
|
+
Pass an `ImageEditorOptions` object as the second constructor argument
|
|
325
|
+
(or as the only argument when using the UMD global form). Unknown keys are
|
|
326
|
+
ignored; nested `label` and `crop` objects are deep-merged with the defaults.
|
|
327
|
+
|
|
328
|
+
| Option | Default | Description |
|
|
329
|
+
| ------------------------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
330
|
+
| `canvasWidth` | `800` | Initial and hidden-container fallback canvas width in pixels. |
|
|
331
|
+
| `canvasHeight` | `600` | Initial and hidden-container fallback canvas height in pixels. |
|
|
332
|
+
| `backgroundColor` | `'transparent'` | Fabric canvas background color. |
|
|
333
|
+
| `animationDuration` | `300` | Duration of scale and rotate animations (ms). |
|
|
334
|
+
| `minScale` | `0.1` | Minimum scale factor. |
|
|
335
|
+
| `maxScale` | `5.0` | Maximum scale factor. |
|
|
336
|
+
| `scaleStep` | `0.05` | Scale delta per zoom step. |
|
|
337
|
+
| `rotationStep` | `90` | Rotation step in degrees. |
|
|
338
|
+
| `expandCanvasToImage` | `true` | Grow the canvas to fit the loaded image (lowest layout precedence). |
|
|
339
|
+
| `fitImageToCanvas` | `false` | Fit the image inside the visible workspace viewport (highest layout precedence). |
|
|
340
|
+
| `coverImageToCanvas` | `false` | Scale large images down to cover the visible workspace, cap at native size, and expand overflowing canvas axes so the container can scroll. |
|
|
341
|
+
| `downsampleOnLoad` | `true` | Downsample large images on load. |
|
|
342
|
+
| `downsampleMaxWidth` | `4000` | Max width before downsampling kicks in. |
|
|
343
|
+
| `downsampleMaxHeight` | `3000` | Max height before downsampling kicks in. |
|
|
344
|
+
| `downsampleQuality` | `0.92` | Lossy quality used when downsampling and exporting. |
|
|
345
|
+
| `preserveSourceFormat` | `true` | Preserve PNG/WebP MIME through downsampling unless `downsampleMimeType` is set. |
|
|
346
|
+
| `downsampleMimeType` | `null` | Explicit downsample MIME type. Overrides `preserveSourceFormat`. |
|
|
347
|
+
| `imageLoadTimeoutMs` | `30000` | Maximum duration for both decode and Fabric image creation during `loadImage`. |
|
|
348
|
+
| `exportMultiplier` | `1` | Output resolution multiplier. |
|
|
349
|
+
| `maxExportPixels` | `50000000` | Maximum output pixel count after applying the export multiplier. Invalid values fall back to this default. |
|
|
350
|
+
| `maxHistorySize` | `50` | Maximum undo-history entries. Snapshots may include full image data URLs, so large images can duplicate memory across history entries. Lower this for memory-constrained pages. |
|
|
351
|
+
| `exportAreaByDefault` | `'image'` | Default export region for `exportImageBase64`, `exportImageFile`, and `downloadImage`. |
|
|
352
|
+
| `mergeMaskByDefault` | `true` | Default mask compositing behavior for `exportImageBase64`, `exportImageFile`, and `downloadImage`. |
|
|
353
|
+
| `defaultMaskWidth` | `50` | Default mask width. |
|
|
354
|
+
| `defaultMaskHeight` | `80` | Default mask height. |
|
|
355
|
+
| `maskRotatable` | `false` | Allow masks to be rotated by the user. |
|
|
356
|
+
| `maskLabelOnSelect` | `true` | Show a label above a selected mask. |
|
|
357
|
+
| `maskLabelOffset` | `3` | Pixel offset of the label from the mask's top-left corner. |
|
|
358
|
+
| `maskName` | `'mask'` | Prefix used for auto-generated mask names. |
|
|
359
|
+
| `groupSelection` | `false` | Allow Fabric multi-object group selection on the canvas. |
|
|
360
|
+
| `showPlaceholder` | `true` | Show a placeholder element while no image is loaded. |
|
|
361
|
+
| `initialImageBase64` | `null` | Base64 data URL auto-loaded after construction. |
|
|
362
|
+
| `defaultDownloadFileName` | `'edited_image.jpg'` | Default file name used by `downloadImage()`. |
|
|
363
|
+
| `onImageLoadStart` | `null` | Called before a valid image load begins. |
|
|
364
|
+
| `onImageLoaded` | `null` | Called as `(info, context)` once after a successful `loadImage`. Extra arguments are ignored by existing zero-argument JavaScript handlers. |
|
|
365
|
+
| `onImageCleared` | `null` | Called when a committed image is replaced or cleared. |
|
|
366
|
+
| `onImageChanged` | `null` | Called with a safe editor state snapshot after visible editor state changes. |
|
|
367
|
+
| `onBusyChange` | `null` | Called only when the public busy state changes. |
|
|
368
|
+
| `onEditorDisposed` | `null` | Called once when `dispose()` performs teardown. |
|
|
369
|
+
| `onMasksChanged` | `null` | Called with a shallow copy of current mask objects after the mask collection changes. |
|
|
370
|
+
| `onSelectionChange` | `null` | Called with selected mask payload after mask selection changes. |
|
|
371
|
+
| `onError` | `null` | Called as `(error, message)` when the editor reports an error. |
|
|
372
|
+
| `onWarning` | `null` | Called as `(error, message)` when the editor reports a recoverable warning. |
|
|
373
|
+
| `label` | see source | `LabelConfig` for selected-mask labels (`getText`, `textOptions`, `create`). |
|
|
374
|
+
| `crop` | see source | `CropConfig` (`minWidth`, `minHeight`, `padding`, `hideMasksDuringCrop`, `preserveMasksAfterCrop`, `allowRotationOfCropRect`, `exportFileType`, `exportQuality`). `applyCrop()` preserves the current image format by default (`'source'`) and falls back to PNG when unknown. |
|
|
375
|
+
|
|
376
|
+
`crop.exportFileType` defaults to `'source'`. Supported explicit values are
|
|
377
|
+
`'png'`, `'jpeg'`, `'jpg'`, `'webp'`, and full image MIME strings. PNG is
|
|
378
|
+
lossless and ignores `crop.exportQuality`; JPEG/WebP use `crop.exportQuality`
|
|
379
|
+
when finite, otherwise `downsampleQuality`, otherwise `0.92`. Choose JPEG/WebP
|
|
380
|
+
only when smaller intermediate crop output is preferred.
|
|
381
|
+
|
|
382
|
+
## Example workflow
|
|
383
|
+
|
|
384
|
+
1. Construct `ImageEditor` with options and call `init(idMap)` to wire it up.
|
|
385
|
+
2. Load an image via `loadImage(base64)` or the bound file input.
|
|
386
|
+
3. Adjust with `scaleImage`, `rotateImage`, `resetImageTransform`, and the
|
|
387
|
+
crop session.
|
|
388
|
+
4. Add `createMask` calls and inspect via the `maskList` element.
|
|
389
|
+
5. Use `mergeMasks` to bake masks into the image, then
|
|
390
|
+
`exportImageBase64`, `exportImageFile`, or `downloadImage` to produce
|
|
391
|
+
the final output.
|
|
392
|
+
6. Call `dispose()` when the editor is unmounted.
|
|
393
|
+
|
|
394
|
+
## Building from source
|
|
506
395
|
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
Recommended usage:
|
|
512
|
-
|
|
513
|
-
- Wrap initialization and manual API calls in `try...catch`.
|
|
514
|
-
- Always `await` Promise-based methods such as `loadImage()`, `scaleImage()`, `rotateImage()`, `resetImageTransform()`, `mergeMasks()`, `applyCrop()`, `undo()`, `redo()`, `exportImageBase64()`, `exportImageFile()`, and `loadFromState()`.
|
|
515
|
-
- Use `onError` and `onWarning` for centralized logging or UI notifications.
|
|
516
|
-
- Do not rely only on `onError`; manual API calls should still handle thrown errors or rejected Promises at the call site.
|
|
517
|
-
- Check `editor.isBusy()` before starting user-triggered operations when needed, especially before loading, cropping, rotating, scaling, merging, undoing, redoing, or exporting.
|
|
518
|
-
- Show user-friendly messages in your application instead of exposing raw error text directly.
|
|
519
|
-
|
|
520
|
-
Example:
|
|
521
|
-
|
|
522
|
-
```javascript
|
|
523
|
-
const editor = new ImageEditor({
|
|
524
|
-
onError: (error, message) => {
|
|
525
|
-
console.error("[ImageEditor]", message, error);
|
|
526
|
-
showEditorMessage("The image editor could not complete the operation.");
|
|
527
|
-
},
|
|
528
|
-
|
|
529
|
-
onWarning: (error, message) => {
|
|
530
|
-
console.warn("[ImageEditor]", message, error);
|
|
531
|
-
},
|
|
532
|
-
});
|
|
533
|
-
|
|
534
|
-
async function rotateSafely(degrees) {
|
|
535
|
-
if (editor.isBusy()) {
|
|
536
|
-
return;
|
|
537
|
-
}
|
|
538
|
-
|
|
539
|
-
try {
|
|
540
|
-
await editor.rotateImage(degrees);
|
|
541
|
-
} catch (error) {
|
|
542
|
-
console.error("Rotate failed:", error);
|
|
543
|
-
showEditorMessage("Rotation failed. Please try again.");
|
|
544
|
-
}
|
|
545
|
-
}
|
|
546
|
-
|
|
547
|
-
function showEditorMessage(message) {
|
|
548
|
-
// Replace this with your own toast, alert, or inline message UI.
|
|
549
|
-
console.log(message);
|
|
550
|
-
}
|
|
396
|
+
```bash
|
|
397
|
+
npm install
|
|
398
|
+
npm run build
|
|
551
399
|
```
|
|
552
400
|
|
|
553
|
-
|
|
401
|
+
`npm run build` runs `clean → build:esm → build:cjs → build:types →
|
|
402
|
+
build:umd` in order, emitting:
|
|
554
403
|
|
|
555
|
-
|
|
404
|
+
- `dist/esm/index.js` (and the rest of the decomposed source tree)
|
|
405
|
+
- `dist/cjs/index.cjs`
|
|
406
|
+
- `dist/types/index.d.ts`
|
|
407
|
+
- `dist/umd/image-editor.umd.js`
|
|
556
408
|
|
|
557
|
-
|
|
558
|
-
- The configured canvas element cannot be found.
|
|
559
|
-
- The image data URL or selected file is invalid, unsupported, too large, or times out while loading.
|
|
560
|
-
- Another operation is already running, such as image loading, animation, crop, undo, redo, merge, or export.
|
|
561
|
-
- The editor has been disposed before the operation completes.
|
|
562
|
-
- The requested export exceeds `maxExportPixels`, uses an invalid multiplier, or the browser cannot create a canvas export because of platform, memory, or security restrictions.
|
|
563
|
-
- A custom callback such as `onImageLoaded`, `onCreate`, `fabricGenerator`, `label.create`, or `label.getText` throws. These are isolated where possible and reported through `onWarning` without rolling back already committed successful work.
|
|
409
|
+
`npm test` runs the Node-based unit and property tests under `tests/`.
|
|
564
410
|
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
The recommended order depends on whether masks should remain editable, be baked into the image, or be discarded.
|
|
568
|
-
|
|
569
|
-
### Common workflow: crop first, then add masks
|
|
570
|
-
|
|
571
|
-
Use this flow when masks are only needed on the final cropped image.
|
|
572
|
-
|
|
573
|
-
1. **Load an image** - Via file input or base64 data URL.
|
|
574
|
-
2. **Adjust positioning** - Zoom in/out, rotate, or reset as needed.
|
|
575
|
-
3. **Crop** - Optionally crop the image area.
|
|
576
|
-
4. **Add masks** - Highlight or cover specific areas on the cropped image.
|
|
577
|
-
5. **Merge result** - Flatten masks into the base image when needed.
|
|
578
|
-
6. **Download / export** - Save the final image.
|
|
579
|
-
|
|
580
|
-
### Alternative workflow: add masks before crop
|
|
581
|
-
|
|
582
|
-
If masks are added before crop, choose one of these behaviors before applying crop:
|
|
583
|
-
|
|
584
|
-
- Call `mergeMasks()` before `applyCrop()` if masks should become part of the cropped image pixels.
|
|
585
|
-
- Set `crop.preserveMasksAfterCrop: true` if masks should stay editable after crop.
|
|
586
|
-
- Keep the default `crop.preserveMasksAfterCrop: false` if unmerged masks should be removed by crop.
|
|
587
|
-
|
|
588
|
-
Example:
|
|
589
|
-
|
|
590
|
-
```javascript
|
|
591
|
-
// Masks become part of the image pixels before crop.
|
|
592
|
-
await editor.mergeMasks();
|
|
593
|
-
editor.enterCropMode();
|
|
594
|
-
await editor.applyCrop();
|
|
595
|
-
```
|
|
596
|
-
|
|
597
|
-
## Local Build
|
|
411
|
+
For the full local release gate, run:
|
|
598
412
|
|
|
599
413
|
```bash
|
|
414
|
+
npm run format:check
|
|
415
|
+
npm run lint
|
|
416
|
+
npm run typecheck
|
|
417
|
+
npm test
|
|
600
418
|
npm run build
|
|
419
|
+
npm run package:check
|
|
420
|
+
npm audit --audit-level=high
|
|
421
|
+
npm pack --dry-run
|
|
601
422
|
```
|
|
602
423
|
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
```
|
|
424
|
+
`npm run ci` combines format, lint, typecheck, tests, build, and package
|
|
425
|
+
linting. The test suite also supports a clean checkout where `dist/` has not
|
|
426
|
+
been built yet; integration helpers use source modules until build artifacts
|
|
427
|
+
exist, while partial `dist/` trees still fail the artifact checks.
|
|
608
428
|
|
|
609
|
-
## Browser
|
|
429
|
+
## Browser support
|
|
610
430
|
|
|
611
431
|
- Chrome 100+
|
|
612
432
|
- Firefox 100+
|
|
613
433
|
- Safari 15+
|
|
614
434
|
- Edge 100+
|
|
615
435
|
|
|
616
|
-
The
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
##
|
|
621
|
-
|
|
622
|
-
|
|
436
|
+
The library uses modern DOM and ES2022 features (optional chaining, classes,
|
|
437
|
+
`async`/`await`, native promises). Older targets must be transpiled by the
|
|
438
|
+
consumer.
|
|
439
|
+
|
|
440
|
+
## Type declarations
|
|
441
|
+
|
|
442
|
+
Public types are re-exported from the package root:
|
|
443
|
+
|
|
444
|
+
```ts
|
|
445
|
+
import type {
|
|
446
|
+
ImageEditorOptions,
|
|
447
|
+
ResolvedOptions,
|
|
448
|
+
LabelConfig,
|
|
449
|
+
CropConfig,
|
|
450
|
+
LoadImageOptions,
|
|
451
|
+
RemoveAllMasksOptions,
|
|
452
|
+
MaskConfig,
|
|
453
|
+
MaskObject,
|
|
454
|
+
MaskNumericProp,
|
|
455
|
+
ResolvedMaskConfig,
|
|
456
|
+
ImageMimeType,
|
|
457
|
+
ImageFileType,
|
|
458
|
+
NormalizedImageFormat,
|
|
459
|
+
ExportArea,
|
|
460
|
+
CropExportFileType,
|
|
461
|
+
Base64ExportOptions,
|
|
462
|
+
ImageFileExportOptions,
|
|
463
|
+
ImageInfo,
|
|
464
|
+
ImageEditorState,
|
|
465
|
+
ImageEditorSelection,
|
|
466
|
+
ImageEditorCallbackContext,
|
|
467
|
+
ImageEditorOperation,
|
|
468
|
+
ElementIdMap,
|
|
469
|
+
FabricModule,
|
|
470
|
+
} from '@bensitu/image-editor';
|
|
471
|
+
```
|
|
623
472
|
|
|
624
473
|
## License
|
|
625
474
|
|
|
626
|
-
MIT ©
|
|
475
|
+
MIT © Ben Situ.
|
|
627
476
|
|
|
628
|
-
Fabric.js is
|
|
477
|
+
Fabric.js is distributed under its own MIT license.
|