JavaScript image editor built on FabricJS, allowing you to create instances with an integrated montage area and providing an API to modify and manage state.
npm install @anu3ev/fabric-image-editorA modern, powerful browser-based image editor built with FabricJS and TypeScript. This library provides a complete image editing solution with professional features for web applications.
๐ Live Demo
Alt with a selection to display distance guides to the hovered object or montage area@font-face registration``bash`
npm install @anu3ev/fabric-image-editor
Requirements:
- Node.js โฅ 20.0.0
- NPM โฅ 9.0.0
- Modern browser with ES2016+ support
Create a container in your HTML and initialize the editor:
`html`
`javascript
import initEditor from '@anu3ev/fabric-image-editor'
document.addEventListener('DOMContentLoaded', async () => {
const editor = await initEditor('editor', {
montageAreaWidth: 512,
montageAreaHeight: 512,
editorContainerWidth: '100%',
editorContainerHeight: '100vh'
})
// The editor is now ready to use!
console.log('Editor initialized:', editor)
})
`
`javascript
// Import an image
await editor.imageManager.importImage({
source: 'path/to/image.jpg',
scale: 'image-contain' // 'image-contain', 'image-cover', 'scale-montage'
})
// Export the canvas
const result = await editor.imageManager.exportCanvasAsImageFile({
fileName: 'edited-image.png',
contentType: 'image/png' // Supports: 'image/png', 'image/jpeg', 'image/svg+xml', 'application/pdf'
})
// Handle the exported file (result.image is File, Blob, or Base64 string)
const url = URL.createObjectURL(result.image)
// Use the URL for download or display
`
`javascript
// Set a color background
editor.backgroundManager.setColorBackground({ color: '#ff0000' })
// Set a gradient background (supports multi-stop ramps)
editor.backgroundManager.setGradientBackground({
gradient: {
type: 'linear', // 'linear' or 'radial'
angle: 120,
colorStops: [
{ offset: 0, color: '#ff8a00' },
{ offset: 45, color: '#e52e71' },
{ offset: 100, color: '#4a00e0' }
]
},
customData: {
customProperty: 'value'
},
withoutSave: false
})
// Simple two-stop gradients still work:
// use startColor/endColor with optional startPosition/endPosition (0-100).
// For radial gradients pass centerX/centerY/radius in percentages.
// Set an image background
await editor.backgroundManager.setImageBackground({ imageSource: 'bg-image.jpg' })
// Remove background
editor.backgroundManager.removeBackground()
`
Offsets in colorStops use percentages from 0 to 100 and are normalized for Fabric gradients.
`javascript
// Add a text layer with custom style
const textbox = editor.textManager.addText({
text: 'ะัะธะฒะตั, Fabric!',
fontFamily: 'Merriweather',
fontSize: 64,
bold: true,
align: 'center',
color: '#1f2933'
})
// Update existing text
editor.textManager.updateText({
target: textbox,
style: {
text: 'HELLO FABRIC',
uppercase: true,
strokeColor: '#2563eb',
strokeWidth: 2
}
})
// Background styling with padding and rounded corners
const bgTextbox = editor.textManager.addText({
text: 'New text',
backgroundColor: '#ffffff',
backgroundOpacity: 0.85,
paddingTop: 24,
paddingRight: 32,
paddingBottom: 24,
paddingLeft: 32,
radiusTopLeft: 8,
radiusTopRight: 8,
radiusBottomRight: 8,
radiusBottomLeft: 8
})
editor.textManager.updateText({
target: bgTextbox,
style: {
paddingTop: 40,
paddingBottom: 40,
radiusTopLeft: 16,
radiusTopRight: 16
}
})
`
By default the editor ships with a curated Google Fonts collection (Latin + Cyrillic coverage).
If you want to use your own fonts, supply a fonts array โ the provided list will replace the defaults.
`typescript
import initEditor from '@anu3ev/fabric-image-editor'
await initEditor('editor', {
fonts: [
{
family: 'Alegreya Sans',
source: "url('https://fonts.gstatic.com/s/alegreyasans/v26/5aUz9_-1phKLFgshYDvh6Vwt7VptvQ.woff2') format('woff2')",
descriptors: {
style: 'normal',
weight: '400',
display: 'swap'
}
},
{
family: 'My Custom Font',
source: "url('https://example.com/fonts/my-font.woff2') format('woff2')",
descriptors: {
style: 'normal',
weight: '400',
display: 'swap',
unicodeRange: 'U+0000-00FF'
}
}
]
})
`
> โน๏ธ Leave fonts undefined to rely on the built-in defaults. Passing the property replaces that set with the fonts you specify.
The repository includes a comprehensive demo showcasing all features:
`bash`
git clone https://github.com/Anu3ev/image-editor.git
cd image-editor
npm install
npm run dev
Visit the demo at: https://anu3ev.github.io/image-editor/
The editor follows a modular architecture with specialized managers:
- Image import/export, format handling, PDF generation - Canvas sizing, scaling, and viewport management - Undo/redo functionality with state persistence - Text object creation, styling, uppercase handling, and history integration - Object layering, z-index management, send to back/front - Background colors, gradients, and images - Object transformations, fitting, and scaling - Zoom limits, fit calculations, and smooth viewport centering - Object selection and multi-selection handling - Copy/paste with system clipboard integration - Object grouping and ungrouping operations - Object deletion with group handling - Shape creation (rectangles, circles, triangles) - Object locking and unlocking functionality - Alignment guides and equal-spacing snaps while moving objects - ALT-triggered distance guides to hovered objects or the montage area - Constrains canvas panning relative to zoom and montage bounds - Web Worker integration for heavy operations - Font loading via FontFace API or fallback @font-face injection - Dynamic module loading (jsPDF, etc.) - Error handling and user notifications (src/editor/template-manager/index.ts) - Serializes and reapplies object/group templates with optional background preservation$3
- ToolbarManager - Dynamic toolbar with configurable actions
- CustomizedControls - Custom FabricJS controls and interactions
- InteractionBlocker - UI blocking during operations
- AngleIndicatorManager - Rotation angle badge shown while rotating selected objects (toggle via showRotationAngle)๐ API Reference
$3
`javascript
initEditor(containerId, options): Promise
`Parameters:
-
containerId (string) - HTML container element ID
- options (CanvasOptions) - Configuration objectCommon Options:
`javascript
{
// Canvas dimensions (internal resolution)
montageAreaWidth: 512,
montageAreaHeight: 512, // Container dimensions (display size)
editorContainerWidth: '800px',
editorContainerHeight: '600px',
// Initial image
initialImage: {
source: 'path/to/image.jpg',
scale: 'image-contain'
},
// Content types for import
acceptContentTypes: ['image/png', 'image/jpeg', 'image/svg+xml'],
// Callback when ready
_onReadyCallback: (editor) => console.log('Ready!')
}
`$3
#### Image Operations
`javascript
// Import image from file or URL
await editor.imageManager.importImage({
source: File | string,
scale: 'image-contain' // or 'image-cover', 'scale-montage'
})// Export canvas as image
await editor.imageManager.exportCanvasAsImageFile({
fileName: 'export.png',
contentType: 'image/png' // 'image/png', 'image/jpeg', 'image/svg+xml', 'application/pdf'
})
`#### Canvas Control
`javascript
// Scale montage area to fit image
editor.canvasManager.scaleMontageAreaToImage()// Set canvas dimensions
editor.canvasManager.setCanvasBackstoreWidth(800)
editor.canvasManager.setCanvasBackstoreHeight(600)
// Zoom operations
editor.canvas.zoomToPoint(point, zoomLevel)
`#### Object Transformations
`javascript
// Fit object to montage area
editor.transformManager.fitObject({
type: 'contain',
fitAsOneObject: true
})// Reset object transformations
editor.transformManager.resetObject()
// Flip operations
editor.transformManager.flipX()
editor.transformManager.flipY()
`#### Layer Management
`javascript
// Layer operations
editor.layerManager.sendToBack(object)
editor.layerManager.bringToFront(object)
editor.layerManager.sendBackwards(object)
editor.layerManager.bringForward(object)
`#### Alignment & Guides
- Objects snap to montage area edges/centers and nearby objects while dragging, with guides for matches and equal spacing.
- Hold
Ctrl during drag to temporarily disable snapping (movement still follows the configured move step).
- Hold Alt with an active selection to show measurement overlays to the hovered object or montage area; distances are labeled on the helper layer and the toolbar hides temporarily until guides clear.#### History Control
`javascript
// Undo/Redo
editor.historyManager.undo()
editor.historyManager.redo()// Save state
editor.historyManager.saveState()
// Load from JSON
editor.historyManager.loadStateFromFullState(jsonState)
`$3
`javascript
// Serialize current selection to JSON template
const templateJson = editor.templateManager.serializeSelection({
includeBackground: false
})// Apply template to canvas
await editor.templateManager.applyTemplate({
templateJson,
clearCanvas: false
})
`TemplateManager keeps layout fidelity by storing positions, styles, and (optionally) background data so you can rehydrate saved compositions.๐ ๏ธ Development
$3
`bash
Development mode with demo app and watch
npm run devDevelopment build to dev-build folder
npm run dev:buildProduction build (library to dist/)
npm run buildBuild for GitHub Pages (demo to docs/)
npm run build:docs
`$3
`bash
Run all tests
npm testWatch mode for development
npm run test:watchCoverage report
npm run test:coverageCI mode
npm run test:ci
`$3
`
src/
โโโ main.ts # Entry point, exports initEditor()
โโโ editor/
โ โโโ index.ts # ImageEditor class
โ โโโ defaults.ts # Default configuration
โ โโโ constants.ts # Constants and limits
โ โโโ listeners.ts # Event handling
โ โโโ background-manager/ # Background functionality
โ โโโ canvas-manager/ # Canvas operations
โ โโโ clipboard-manager/ # Copy/paste operations
โ โโโ customized-controls/ # Custom FabricJS controls
โ โโโ deletion-manager/ # Object deletion
โ โโโ error-manager/ # Error handling
โ โโโ grouping-manager/ # Object grouping
โ โโโ history-manager/ # Undo/redo system
โ โโโ image-manager/ # Image import/export
โ โโโ interaction-blocker/ # UI blocking during operations
โ โโโ layer-manager/ # Layer management
โ โโโ module-loader/ # Dynamic module loading
โ โโโ object-lock-manager/ # Object locking
โ โโโ selection-manager/ # Selection handling
โ โโโ shape-manager/ # Shape creation
โ โโโ text-manager/ # Text objects and styling
โ โโโ font-manager/ # Font loading utilities
โ โโโ transform-manager/ # Object transformations
โ โโโ worker-manager/ # Web Worker management
โ โโโ ui/ # UI components (toolbar)
โ โโโ types/ # TypeScript definitions
โโโ editor/default-fonts.ts # Built-in Google font presets
โโโ demo/ # Demo application
specs/ # Test specifications
docs/ # GitHub Pages build output
dev-build/ # Development build output
dist/ # Production library build
vite.config.*.js # Vite configurations
jest.config.ts # Jest test configuration
`๐ฏ Planned Features
The following features are planned for future releases:
- Drawing Mode - Freehand drawing tools and brushes
- Filters & Effects - Image filters and visual effects
- Extended Shape Library - Additional shapes beyond current rectangles, circles, and triangles
- Multi-language - Internationalization support
๐ค Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
$3
`bash
git clone https://github.com/Anu3ev/image-editor.git
cd image-editor
npm install
npm run dev
`$3
`bash
npm test # Run all tests
npm run test:watch # Development mode
npm run test:coverage # Coverage report
``- Chrome โฅ 88
- Firefox โฅ 85
- Safari โฅ 14
- Edge โฅ 88
All modern browsers with ES2016+ and Web Workers support.
MIT License - see LICENSE file for details.
- Built with FabricJS - Powerful HTML5 canvas library
- Vite - Lightning fast build tool
- TypeScript - Type safety and developer experience
- Jest - Comprehensive testing framework
---
Repository: github.com/Anu3ev/image-editor
NPM Package: @anu3ev/fabric-image-editor
Live Demo: anu3ev.github.io/image-editor