fengyuanchen / cropperjs

JavaScript image cropper.
https://fengyuanchen.github.io/cropperjs/
MIT License
12.98k stars 2.4k forks source link
cropper cropperjs image-cropper image-processing javascript

Cropper.js

Downloads Version Gzip Size

JavaScript image cropper. This is the branch for v1.x, for v2.x, check out the v2 branch.

Table of contents

Features

Main files

dist/
├── cropper.css
├── cropper.min.css   (compressed)
├── cropper.js        (UMD)
├── cropper.min.js    (UMD, compressed)
├── cropper.common.js (CommonJS, default)
└── cropper.esm.js    (ES Module)

Getting started

Installation

npm install cropperjs

In browser:

<link  href="https://github.com/fengyuanchen/cropperjs/blob/main/path/to/cropper.css" rel="stylesheet">
<script src="https://github.com/fengyuanchen/cropperjs/raw/main/path/to/cropper.js"></script>

cdnjs provides CDN support for Cropper.js's CSS and JavaScript. You can find the links here.

Usage

Syntax

new Cropper(element[, options])

Example

<!-- Wrap the image or canvas element with a block element (container) -->
<div>
  <img id="image" src="https://github.com/fengyuanchen/cropperjs/raw/main/picture.jpg">
</div>
/* Make sure the size of the image fits perfectly into the container */
img {
  display: block;

  /* This rule is very important, please don't ignore this */
  max-width: 100%;
}
// import 'cropperjs/dist/cropper.css';
import Cropper from 'cropperjs';

const image = document.getElementById('image');
const cropper = new Cropper(image, {
  aspectRatio: 16 / 9,
  crop(event) {
    console.log(event.detail.x);
    console.log(event.detail.y);
    console.log(event.detail.width);
    console.log(event.detail.height);
    console.log(event.detail.rotate);
    console.log(event.detail.scaleX);
    console.log(event.detail.scaleY);
  },
});

FAQ

How to crop a new area after zooming in or zooming out?

Just double-click your mouse to enter crop mode.

How to move the image after cropping an area?

Just double-click your mouse to enter move mode.

How to fix the aspect ratio in free ratio mode?

Just hold the Shift key when you resize the crop box.

How to crop a square area in free ratio mode?

Just hold the Shift key when you crop on the image.

Notes

Known issues

⬆ back to top

Options

You may set cropper options with new Cropper(image, options). If you want to change the global default options, You may use Cropper.setDefaults(options).

viewMode

Define the view mode of the cropper. If you set viewMode to 0, the crop box can extend outside the canvas, while a value of 1, 2, or 3 will restrict the crop box to the size of the canvas. viewMode of 2 or 3 will additionally restrict the canvas to the container. There is no difference between 2 and 3 when the proportions of the canvas and the container are the same.

dragMode

Define the dragging mode of the cropper.

initialAspectRatio

Define the initial aspect ratio of the crop box. By default, it is the same as the aspect ratio of the canvas (image wrapper).

Only available when the aspectRatio option is set to NaN.

aspectRatio

Define the fixed aspect ratio of the crop box. By default, the crop box has a free ratio.

data

The previous cropped data you stored will be passed to the setData method automatically when initialized.

Only available when the autoCrop option had set to the true.

preview

Add extra elements (containers) for preview.

Notes:

responsive

Re-render the cropper when resizing the window.

restore

Restore the cropped area after resizing the window.

checkCrossOrigin

Check if the current image is a cross-origin image.

If so, a crossOrigin attribute will be added to the cloned image element, and a timestamp parameter will be added to the src attribute to reload the source image to avoid browser cache error.

Adding a crossOrigin attribute to the image element will stop adding a timestamp to the image URL and stop reloading the image. But the request (XMLHttpRequest) to read the image data for orientation checking will require a timestamp to bust the cache to avoid browser cache error. You can set the checkOrientation option to false to cancel this request.

If the value of the image's crossOrigin attribute is "use-credentials", then the withCredentials attribute will set to true when read the image data by XMLHttpRequest.

checkOrientation

Check the current image's Exif Orientation information. Note that only a JPEG image may contain Exif Orientation information.

Exactly, read the Orientation value for rotating or flipping the image, and then override the Orientation value with 1 (the default value) to avoid some issues (1, 2) on iOS devices.

Requires to set both the rotatable and scalable options to true at the same time.

Note: Do not trust this all the time as some JPG images may have incorrect (non-standard) Orientation values

Requires Typed Arrays support (IE 10+).

modal

Show the black modal above the image and under the crop box.

guides

Show the dashed lines above the crop box.

center

Show the center indicator above the crop box.

highlight

Show the white modal above the crop box (highlight the crop box).

background

Show the grid background of the container.

autoCrop

Enable to crop the image automatically when initialized.

autoCropArea

It should be a number between 0 and 1. Define the automatic cropping area size (percentage).

movable

Enable to move the image.

rotatable

Enable to rotate the image.

scalable

Enable to scale the image.

zoomable

Enable to zoom the image.

zoomOnTouch

Enable to zoom the image by dragging touch.

zoomOnWheel

Enable to zoom the image by mouse wheeling.

wheelZoomRatio

Define zoom ratio when zooming the image by mouse wheeling.

cropBoxMovable

Enable to move the crop box by dragging.

cropBoxResizable

Enable to resize the crop box by dragging.

toggleDragModeOnDblclick

Enable to toggle drag mode between "crop" and "move" when clicking twice on the cropper.

Requires dblclick event support.

minContainerWidth

The minimum width of the container.

minContainerHeight

The minimum height of the container.

minCanvasWidth

The minimum width of the canvas (image wrapper).

minCanvasHeight

The minimum height of the canvas (image wrapper).

minCropBoxWidth

The minimum width of the crop box.

Note: This size is relative to the page, not the image.

minCropBoxHeight

The minimum height of the crop box.

Note: This size is relative to the page, not the image.

ready

A shortcut to the ready event.

cropstart

A shortcut to the cropstart event.

cropmove

A shortcut to the cropmove event.

cropend

A shortcut to the cropend event.

crop

A shortcut to the crop event.

zoom

A shortcut to the zoom event.

⬆ back to top

Methods

As there is an asynchronous process when loading the image, you should call most of the methods after ready, except setAspectRatio, replace and destroy.

If a method doesn't need to return any value, it will return the cropper instance (this) for chain composition.

new Cropper(image, {
  ready() {
    // this.cropper[method](argument1, , argument2, ..., argumentN);
    this.cropper.move(1, -1);

    // Allows chain composition
    this.cropper.move(1, -1).rotate(45).scale(1, -1);
  },
});

crop()

Show the crop box manually.

new Cropper(image, {
  autoCrop: false,
  ready() {
    // Do something here
    // ...

    // And then
    this.cropper.crop();
  },
});

reset()

Reset the image and crop box to its initial states.

clear()

Clear the crop box.

replace(url[, hasSameSize])

Replace the image's src and rebuild the cropper.

enable()

Enable (unfreeze) the cropper.

disable()

Disable (freeze) the cropper.

destroy()

Destroy the cropper and remove the instance from the image.

move(offsetX[, offsetY])

Move the canvas (image wrapper) with relative offsets.

cropper.move(1);
cropper.move(1, 0);
cropper.move(0, -1);

moveTo(x[, y])

Move the canvas (image wrapper) to an absolute point.

zoom(ratio)

Zoom the canvas (image wrapper) with a relative ratio.

cropper.zoom(0.1);
cropper.zoom(-0.1);

zoomTo(ratio[, pivot])

Zoom the canvas (image wrapper) to an absolute ratio.

cropper.zoomTo(1); // 1:1 (canvasData.width === canvasData.naturalWidth)

const containerData = cropper.getContainerData();

// Zoom to 50% from the center of the container.
cropper.zoomTo(.5, {
  x: containerData.width / 2,
  y: containerData.height / 2,
});

rotate(degree)

Rotate the image to a relative degree.

Requires CSS3 2D Transforms support (IE 9+).

cropper.rotate(90);
cropper.rotate(-90);

rotateTo(degree)

Rotate the image to an absolute degree.

scale(scaleX[, scaleY])

Scale the image.

Requires CSS3 2D Transforms support (IE 9+).

cropper.scale(-1); // Flip both horizontal and vertical
cropper.scale(-1, 1); // Flip horizontal
cropper.scale(1, -1); // Flip vertical

scaleX(scaleX)

Scale the abscissa of the image.

scaleY(scaleY)

Scale the ordinate of the image.

getData([rounded])

Output the final cropped area position and size data (based on the natural size of the original image).

You can send the data to the server-side to crop the image directly:

  1. Rotate the image with the rotate property.
  2. Scale the image with the scaleX and scaleY properties.
  3. Crop the image with the x, y, width, and height properties.

A schematic diagram for data's properties

setData(data)

Change the cropped area position and size with new data (based on the original image).

Note: This method only available when the value of the viewMode option is greater than or equal to 1.

getContainerData()

Output the container size data.

A schematic diagram for cropper's layers

getImageData()

Output the image position, size, and other related data.

getCanvasData()

Output the canvas (image wrapper) position and size data.

const imageData = cropper.getImageData();
const canvasData = cropper.getCanvasData();

if (imageData.rotate % 180 === 0) {
  console.log(canvasData.naturalWidth === imageData.naturalWidth);
  // > true
}

setCanvasData(data)

Change the canvas (image wrapper) position and size with new data.

getCropBoxData()

Output the crop box position and size data.

setCropBoxData(data)

Change the crop box position and size with new data.

getCroppedCanvas([options])

Get a canvas drawn from the cropped image (lossy compression). If it is not cropped, then returns a canvas drawn the whole image.

After then, you can display the canvas as an image directly, or use HTMLCanvasElement.toDataURL to get a Data URL, or use HTMLCanvasElement.toBlob to get a blob and upload it to server with FormData if the browser supports these APIs.

Avoid getting a blank (or black) output image, you might need to set the maxWidth and maxHeight properties to limited numbers, because of the size limits of a canvas element. Also, you should limit the maximum zoom ratio (in the zoom event) for the same reason.

cropper.getCroppedCanvas();

cropper.getCroppedCanvas({
  width: 160,
  height: 90,
});

cropper.getCroppedCanvas({
  minWidth: 256,
  minHeight: 256,
  maxWidth: 4096,
  maxHeight: 4096,
});

cropper.getCroppedCanvas({
  fillColor: '#fff',
  imageSmoothingEnabled: false,
  imageSmoothingQuality: 'high',
});

// Upload cropped image to server if the browser supports `HTMLCanvasElement.toBlob`.
// The default value for the second parameter of `toBlob` is 'image/png', change it if necessary.
cropper.getCroppedCanvas().toBlob((blob) => {
  const formData = new FormData();

  // Pass the image file name as the third parameter if necessary.
  formData.append('croppedImage', blob/*, 'example.png' */);

  // Use `jQuery.ajax` method for example
  $.ajax('/path/to/upload', {
    method: 'POST',
    data: formData,
    processData: false,
    contentType: false,
    success() {
      console.log('Upload success');
    },
    error() {
      console.log('Upload error');
    },
  });
}/*, 'image/png' */);

setAspectRatio(aspectRatio)

Change the aspect ratio of the crop box.

setDragMode([mode])

Change the drag mode.

Tips: You can toggle the "crop" and "move" mode by double clicking on the cropper.

⬆ back to top

Events

ready

This event fires when the target image has been loaded and the cropper instance is ready for operating.

let cropper;

image.addEventListener('ready', function () {
  console.log(this.cropper === cropper);
  // > true
});

cropper = new Cropper(image);

cropstart

This event fires when the canvas (image wrapper) or the crop box starts to change.

image.addEventListener('cropstart', (event) => {
  console.log(event.detail.originalEvent);
  console.log(event.detail.action);
});

cropmove

This event fires when the canvas (image wrapper) or the crop box is changing.

cropend

This event fires when the canvas (image wrapper) or the crop box stops changing.

crop

About these properties, see the getData method.

This event fires when the canvas (image wrapper) or the crop box changes.

Notes:

zoom

This event fires when a cropper instance starts to zoom in or zoom out its canvas (image wrapper).

image.addEventListener('zoom', (event) => {
  // Zoom in
  if (event.detail.ratio > event.detail.oldRatio) {
    event.preventDefault(); // Prevent zoom in
  }

  // Zoom out
  // ...
});

⬆ back to top

No conflict

If you have to use another cropper with the same namespace, just call the Cropper.noConflict static method to revert to it.

<script src="https://github.com/fengyuanchen/cropperjs/raw/main/other-cropper.js"></script>
<script src="https://github.com/fengyuanchen/cropperjs/raw/main/cropper.js"></script>
<script>
  Cropper.noConflict();
  // Code that uses other `Cropper` can follow here.
</script>

Browser support

Contributing

Please read through our contributing guidelines.

Versioning

Maintained under the Semantic Versioning guidelines.

License

MIT © Chen Fengyuan

Related projects

⬆ back to top