@digilabscz/image-cropper-js
v1.0.0
Published
Image cropper
Readme
@digilabscz/image-cropper-js
Framework-independent browser image cropper. It lets a user move and zoom an image, resize or move the crop area, and export a physically cropped File and Blob locally with canvas. The package never uploads data and does not rotate images.
Installation
npm install @digilabscz/image-cropper-jsUsage
<input type="file" id="image" accept="image/*">
<div id="cropper"></div>import {
ImageCropper,
createImageCropFormData
} from '@digilabscz/image-cropper-js';
let imageCropper = new ImageCropper(document.querySelector('#cropper'), {
onConfirm: async (result, context) => {
let formData = context.createFormData();
// Uploading is intentionally controlled by the consuming application.
await fetch('/api/images', {
method: 'POST',
body: formData
});
},
onError: (error) => {
console.error(error);
}
});
document.querySelector('#image').addEventListener('change', async (event) => {
if (event.target.files[0]) {
await imageCropper.load(event.target.files[0]);
}
});The user can drag the image or crop area, resize from all four corners, use the zoom slider or mouse wheel, and confirm or cancel the selection.
Holding Shift while resizing temporarily locks the crop area to a 1:1 square without changing the selected aspect ratio.
Demo
Run the local demo server to try the cropper with an upload endpoint:
cd ..
node demo-server.jsThen open http://127.0.0.1:8000/demo.html. The demo uploads the cropped file and crop metadata to POST /api/images, stores files in uploads/, and renders the URL returned by the server. If you open demo.html through another static server, keep node demo-server.js running on port 8000; the demo will use it as a fallback upload backend.
The demo supports selecting multiple files. It opens the first image, stores each confirmed crop in a queue, automatically loads the next image, and uploads all cropped files together after the last confirmation.
From the workspace root you can also run:
node demo-quality-test.jsThe test posts a frontend crop and an original image with crop metadata to the demo server, verifies the expected pixel dimensions, and compares the resulting frontend/backend images pixel by pixel.
For a real browser canvas comparison, run this from the workspace root after installing Playwright locally:
node demo-playwright-quality-test.jsThat test opens the demo in Chromium, uses the actual browser canvas cropper, then separately asks the demo server for a backend crop from the original image and compares both returned images pixel by pixel.
Options
let imageCropper = new ImageCropper(containerNode, {
locale: null,
translations: {},
initialCrop: null,
initialAspectRatio: null,
aspectRatios: [
{ label: 'Free', value: null },
{ label: '1:1', value: 1 },
{ label: '4:3', value: 4 / 3 },
{ label: '3:4', value: 3 / 4 },
{ label: '16:9', value: 16 / 9 },
{ label: '9:16', value: 9 / 16 },
{ label: '3:2', value: 3 / 2 },
{ label: '2:3', value: 2 / 3 }
],
onConfirm: null,
onCancel: null,
onError: null,
confirmLabel: null,
cancelLabel: null,
aspectRatioLabel: null,
zoomLabel: null
});The package does not expose output format controls. It creates a cropped file for upload and returns crop metadata; any final image conversion or normalization can be handled by the backend.
Translations
The cropper uses locale or the document <html lang> value to choose translations. The bundled languages are en, cs, and sk; unsupported languages fall back to English.
let imageCropper = new ImageCropper(containerNode, {
locale: 'sk',
translations: {
sk: {
Confirm: 'Pouzit vyrez',
Cancel: 'Zahodit',
AspectRatio: 'Format',
AspectRatioFree: 'Bez obmedzenia',
Zoom: 'Priblizenie'
}
},
aspectRatios: [
{ labelKey: 'AspectRatioFree', value: null },
{ label: 'Stvorec', value: '1:1' },
{ label: 'Banner', value: '16:9' }
]
});Legacy label options such as confirmLabel, cancelLabel, aspectRatioLabel, and zoomLabel still work and override translated values when provided.
Public API
await imageCropper.load(file);
let crop = imageCropper.getCrop();
imageCropper.setCrop({
x: 0.1,
y: 0.1,
width: 0.8,
height: 0.8
});
imageCropper.setAspectRatio('16:9');
let result = await imageCropper.getResult();
let blob = await imageCropper.createCroppedBlob();
let file = await imageCropper.createCroppedFile();
await imageCropper.confirm();
imageCropper.cancel();
imageCropper.reset();
imageCropper.setDisabled(true);
imageCropper.destroy();getCrop() returns integer pixel coordinates relative to the original image. setCrop() accepts normalized coordinates between 0 and 1. setAspectRatio() accepts null, a number, or a ratio string such as '16:9'.
confirm() creates the result before calling onConfirm. If the callback returns a promise, controls remain in a loading state until it settles. Repeated confirmation is blocked, and failures are forwarded to onError and rethrown.
Result
{
originalFile,
croppedFile,
croppedBlob,
crop: { x, y, width, height },
normalizedCrop: { x, y, width, height },
aspectRatio,
originalImage: { width, height, type, name, size },
croppedImage: { width, height, type, name, size }
}FormData
let formData = createImageCropFormData(result, {
fileFieldName: 'image',
metadataFieldName: 'cropData',
includeOriginalFile: true,
originalFileFieldName: 'originalImage'
});By default, the cropped file is stored in image and JSON metadata in crop. Set includeOriginalFile: true when the backend should crop from the untouched original image.
Requirements
- Modern browser with
File,Blob,URL.createObjectURL,FormData, and canvas support - No framework or runtime dependency
License
MIT
