Cropper.js - JavaScript Image Cropper

2.1.1 · active · verified Sun Apr 19

Cropper.js is a powerful, pure JavaScript library for image cropping that provides extensive functionalities including moving, zooming, rotating, and scaling images directly within web browsers. The current stable version is 2.1.1, with the project demonstrating active maintenance through consistent patch and minor releases, indicating ongoing development and bug fixes. A key differentiator is its standalone nature, operating without external dependencies like jQuery, making it lightweight and suitable for modern JavaScript ecosystems. It offers a highly configurable and extensible API, allowing developers to tailor the cropping experience precisely. The library ships with comprehensive TypeScript declaration files, ensuring excellent developer experience in TypeScript projects, and supports both UMD and ESM module formats for broad compatibility across different environments.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize Cropper.js with an image element, including essential CSS and basic configuration options like aspect ratio and view mode, and logs crop events.

import Cropper from 'cropperjs';
import 'cropperjs/dist/cropper.css';

document.addEventListener('DOMContentLoaded', () => {
  const container = document.createElement('div');
  container.style.width = '800px';
  container.style.height = '600px';
  container.style.margin = '20px auto';
  container.style.border = '1px solid #ccc';
  container.style.display = 'flex';
  container.style.justifyContent = 'center';
  container.style.alignItems = 'center';
  document.body.appendChild(container);

  const image = document.createElement('img');
  image.id = 'image-to-crop';
  image.src = 'https://picsum.photos/800/600'; // Example image source
  image.alt = 'Image for cropping';
  image.style.maxWidth = '100%';
  image.style.maxHeight = '100%';
  container.appendChild(image);

  // Wait for the image to load before initializing Cropper
  image.onload = () => {
    const cropper = new Cropper(image, {
      aspectRatio: 16 / 9,
      viewMode: 1, // 0: no restrictions, 1: restrict to container, 2: restrict to canvas, 3: restrict to image
      background: false, // Hide the grid background
      crop(event) {
        console.log('Crop data:', event.detail);
      },
      ready() {
        console.log('Cropper is ready!');
      }
    });

    // Example: Destroy cropper after 10 seconds
    // setTimeout(() => {
    //   cropper.destroy();
    //   console.log('Cropper destroyed.');
    // }, 10000);
  };
});

view raw JSON →