Project Icon

cropperjs

功能全面的JavaScript图像裁剪工具

Cropper.js是一款功能丰富的JavaScript图像裁剪工具。该库提供39个配置选项、27个方法和6个事件,支持触摸操作、缩放、旋转和翻转等功能。Cropper.js具有跨浏览器兼容性,可创建多个裁剪器实例,并通过Canvas在浏览器端实现图像裁剪。此外,它还能解析Exif方向信息,为开发者提供灵活高效的图像处理方案。

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

  • Supports 39 options
  • Supports 27 methods
  • Supports 6 events
  • Supports touch (mobile)
  • Supports zooming
  • Supports rotating
  • Supports scaling (flipping)
  • Supports multiple croppers
  • Supports cropping on a canvas
  • Supports cropping an image on the browser-side by canvas
  • Supports translating Exif Orientation information
  • Cross-browser support

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="/path/to/cropper.css" rel="stylesheet">
<script src="/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])
  • element

    • Type: HTMLImageElement or HTMLCanvasElement
    • The target image or canvas element for cropping.
  • options (optional)

    • Type: Object
    • The options for cropping. Check out the available options.

Example

<!-- Wrap the image or canvas element with a block element (container) -->
<div>
  <img id="image" src="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

  • The size of the cropper inherits from the size of the image's parent element (wrapper), so be sure to wrap the image with a visible block element.

    If you are using cropper in a modal, you should initialize the cropper after the modal is shown completely. Otherwise, you will not get the correct cropper.

  • The outputted cropped data is based on the original image size, so you can use them to crop the image directly.

  • If you try to start cropper on a cross-origin image, please make sure that your browser supports HTML5 CORS settings attributes, and your image server supports the Access-Control-Allow-Origin option (see the HTTP access control (CORS)).

Known issues

  • Known iOS resource limits: As iOS devices limit memory, the browser may crash when you are cropping a large image (iPhone camera resolution). To avoid this, you may resize the image first (preferably below 1024 pixels) before starting a cropper.

  • Known image size increase: When exporting the cropped image on the browser side with the HTMLCanvasElement.toDataURL method, the size of the exported image may be greater than the original image's. This is because the type of the exported image is not the same as the original image. So just pass the original image's type as the first parameter to toDataURL to fix this. For example, if the original type is JPEG, then use cropper.getCroppedCanvas().toDataURL('image/jpeg') to export image.

⬆ 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

  • Type: Number
  • Default: 0
  • Options:
    • 0: no restrictions
    • 1: restrict the crop box not to exceed the size of the canvas.
    • 2: restrict the minimum canvas size to fit within the container. If the proportions of the canvas and the container differ, the minimum canvas will be surrounded by extra space in one of the dimensions.
    • 3: restrict the minimum canvas size to fill fit the container. If the proportions of the canvas and the container are different, the container will not be able to fit the whole canvas in one of the dimensions.

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

  • Type: String
  • Default: 'crop'
  • Options:
    • 'crop': create a new crop box
    • 'move': move the canvas
    • 'none': do nothing

Define the dragging mode of the cropper.

initialAspectRatio

  • Type: Number
  • Default: NaN

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

  • Type: Number
  • Default: NaN

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

data

  • Type: Object
  • Default: null

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

  • Type: Element, Array (elements), NodeList or String (selector)
  • Default: ''
  • An element or an array of elements or a node list object or a valid selector for Document.querySelectorAll

Add extra elements (containers) for preview.

Notes:

  • The maximum width is the initial width of the preview container.
  • The maximum height is the initial height of the preview container.
  • If you set an aspectRatio option, be sure to set the same aspect ratio to the preview container.
  • If the preview does not display correctly, set the overflow: hidden style to the preview container.

responsive

  • Type: Boolean
  • Default: true

Re-render the cropper when resizing the window.

restore

  • Type: Boolean
  • Default: true

Restore the cropped area after resizing the window.

checkCrossOrigin

  • Type: Boolean
  • Default: true

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

  • Type: Boolean
  • Default: true

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

  • Type: Boolean
  • Default: true

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

guides

  • Type: Boolean
  • Default: true

Show the dashed lines above the crop box.

center

  • Type: Boolean
  • Default: true

Show the center indicator above the crop box.

highlight

  • Type: Boolean
  • Default: true

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

background

  • Type: Boolean
  • Default: true

Show the grid background of the container.

autoCrop

  • Type: Boolean
  • Default: true

Enable to crop the image automatically when initialized.

autoCropArea

  • Type: Number
  • Default: 0.8 (80% of the image)

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

movable

  • Type: Boolean
  • Default: true

Enable to move the image.

rotatable

  • Type: Boolean
  • Default: true

Enable to rotate the image.

scalable

  • Type: Boolean
  • Default: true

Enable to scale the image.

zoomable

  • Type: Boolean
  • Default: true

Enable to zoom the image.

zoomOnTouch

  • Type: Boolean
  • Default: true

Enable to zoom the image by dragging touch.

zoomOnWheel

  • Type: Boolean
  • Default: true

Enable to zoom the image by mouse wheeling.

wheelZoomRatio

  • Type: Number
  • Default: 0.1

Define zoom ratio when zooming the image by mouse wheeling.

cropBoxMovable

  • Type: Boolean
  • Default: true

Enable to move the crop box by dragging.

cropBoxResizable

  • Type: Boolean
  • Default: true

Enable to resize the crop box by dragging.

toggleDragModeOnDblclick

  • Type: Boolean
  • Default: true

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

Requires dblclick event support.

minContainerWidth

  • Type: Number
  • Default: 200

The minimum width of the container.

minContainerHeight

  • Type: Number
  • Default: 100

The minimum height of the container.

minCanvasWidth

  • Type: Number
  • Default: 0

The minimum width of the canvas (image wrapper).

minCanvasHeight

  • Type: Number
  • Default: 0

The minimum height of the canvas (image wrapper).

minCropBoxWidth

  • Type: Number
  • Default: 0

The minimum width of the crop box.

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

minCropBoxHeight

  • Type: Number
  • Default: 0

The minimum height of the crop box.

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

ready

  • Type: Function
  • Default: null

A shortcut to the ready event.

cropstart

  • Type: Function
  • Default: null

A shortcut to the cropstart event.

cropmove

  • Type: Function
  • Default: null

A shortcut to the cropmove event.

cropend

  • Type: Function
  • Default: null

A shortcut to the cropend event.

crop

  • Type: Function
  • Default: null

A shortcut to the crop event.

zoom

  • Type: Function
  • Default: null

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])

  • url:

    • Type: String
    • A new image url.
  • hasSameSize (optional):

    • Type: Boolean
    • Default: false
    • If the new image has the same size as the old one, then it will not rebuild the cropper and only update the URLs of all related images. This can be used for applying filters.

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])

  • offsetX:

    • Type: Number
    • Moving size (px) in the horizontal direction.
  • offsetY (optional):

    • Type: Number
    • Moving size (px) in the vertical direction.
    • If not present, its default value is offsetX.

Move the canvas (image wrapper) with relative offsets.

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

moveTo(x[, y])

  • x:

    • Type: Number
    • The left value of the canvas
  • y (optional):

    • Type: Number
    • The top value of the canvas
    • If not present, its default value is x.

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

zoom(ratio)

  • ratio:
    • Type: Number
    • Zoom in: requires a positive number (ratio > 0)
    • Zoom out: requires a negative number (ratio < 0)

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

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

zoomTo(ratio[, pivot])

  • ratio:

    • Type: Number
    • Requires a positive number (ratio > 0)
  • pivot (optional):

    • Type: Object
    • Schema: { x: Number, y: Number }
    • The coordinate of the center point for
项目侧边栏1项目侧边栏2
推荐项目
Project Cover

豆包MarsCode

豆包 MarsCode 是一款革命性的编程助手,通过AI技术提供代码补全、单测生成、代码解释和智能问答等功能,支持100+编程语言,与主流编辑器无缝集成,显著提升开发效率和代码质量。

Project Cover

AI写歌

Suno AI是一个革命性的AI音乐创作平台,能在短短30秒内帮助用户创作出一首完整的歌曲。无论是寻找创作灵感还是需要快速制作音乐,Suno AI都是音乐爱好者和专业人士的理想选择。

Project Cover

有言AI

有言平台提供一站式AIGC视频创作解决方案,通过智能技术简化视频制作流程。无论是企业宣传还是个人分享,有言都能帮助用户快速、轻松地制作出专业级别的视频内容。

Project Cover

Kimi

Kimi AI助手提供多语言对话支持,能够阅读和理解用户上传的文件内容,解析网页信息,并结合搜索结果为用户提供详尽的答案。无论是日常咨询还是专业问题,Kimi都能以友好、专业的方式提供帮助。

Project Cover

阿里绘蛙

绘蛙是阿里巴巴集团推出的革命性AI电商营销平台。利用尖端人工智能技术,为商家提供一键生成商品图和营销文案的服务,显著提升内容创作效率和营销效果。适用于淘宝、天猫等电商平台,让商品第一时间被种草。

Project Cover

吐司

探索Tensor.Art平台的独特AI模型,免费访问各种图像生成与AI训练工具,从Stable Diffusion等基础模型开始,轻松实现创新图像生成。体验前沿的AI技术,推动个人和企业的创新发展。

Project Cover

SubCat字幕猫

SubCat字幕猫APP是一款创新的视频播放器,它将改变您观看视频的方式!SubCat结合了先进的人工智能技术,为您提供即时视频字幕翻译,无论是本地视频还是网络流媒体,让您轻松享受各种语言的内容。

Project Cover

美间AI

美间AI创意设计平台,利用前沿AI技术,为设计师和营销人员提供一站式设计解决方案。从智能海报到3D效果图,再到文案生成,美间让创意设计更简单、更高效。

Project Cover

稿定AI

稿定设计 是一个多功能的在线设计和创意平台,提供广泛的设计工具和资源,以满足不同用户的需求。从专业的图形设计师到普通用户,无论是进行图片处理、智能抠图、H5页面制作还是视频剪辑,稿定设计都能提供简单、高效的解决方案。该平台以其用户友好的界面和强大的功能集合,帮助用户轻松实现创意设计。

投诉举报邮箱: service@vectorlightyear.com
@2024 懂AI·鲁ICP备2024100362号-6·鲁公网安备37021002001498号