2mundos-cropperjs 中文文档教程

发布于 7年前 浏览 32 项目主页 更新于 3年前

Cropper.js

构建状态 下载版本

JavaScript 图像裁剪器。

Table of contents

Features

  • Supports 38 options
  • Supports 27 methods
  • Supports 6 events
  • Supports touch (mobile)
  • Supports zooming
  • Supports rotating
  • Supports scaling (flipping)
  • Supports multiple croppers
  • Supports to crop on a canvas
  • Supports to crop image in the browser-side by canvas
  • Supports to translate Exif Orientation information
  • Cross-browser support

Main

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

包含文件:

<link  href="/path/to/cropper.css" rel="stylesheet">
<script src="/path/to/cropper.js"></script>

cdnjs 为 Cropper.js 的 CSS 和 JavaScript 提供 CDN 支持。 您可以在此处找到链接。

Usage

使用Cropper构造函数初始化:

  • Browser: window.Cropper
  • CommonJS: var Cropper = require('cropperjs')
  • ES2015: import Cropper from 'cropperjs'
<!-- Wrap the image or canvas element with a block element (container) -->
<div>
  <img id="image" src="picture.jpg">
</div>
/* Limit image width to avoid overflow the container */
img {
  max-width: 100%; /* This rule is very important, please do not ignore this! */
}
var image = document.getElementById('image');
var cropper = new Cropper(image, {
  aspectRatio: 16 / 9,
  crop: function(e) {
    console.log(e.detail.x);
    console.log(e.detail.y);
    console.log(e.detail.width);
    console.log(e.detail.height);
    console.log(e.detail.rotate);
    console.log(e.detail.scaleX);
    console.log(e.detail.scaleY);
  }
});

FAQ

放大或缩小后如何裁剪新区域?

只需双击鼠标即可进入裁剪模式。

裁剪区域后如何移动图像?

只需双击鼠标即可进入移动模式。

如何在自由比例模式下固定纵横比?

调整裁剪框大小时,只需按住 shift 键即可。

如何在自由比例模式下裁剪方形区域?

裁剪图像时,只需按住 shift 键即可。

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.

如果您在模态中使用裁剪器,则应在模态完全显示后初始化裁剪器。 否则,您将无法获得正确的裁剪器。

  • 输出的裁剪数据基于原始图像大小,因此您可以使用它们直接裁剪图像。

  • 如果您尝试在跨源图像上启动裁剪器,请确保您的浏览器支持 HTML5 CORS设置属性,并且您的图像服务器支持Access-Control-Allow-Origin 选项(参见HTTP 访问控制 (CORS))。

Known issues

  • 已知的 iOS 资源限制:由于 iOS 设备限制内存,因此当您裁剪大图像(iPhone 相机分辨率)时,浏览器可能会崩溃。 为避免这种情况,您可以在开始裁剪之前先调整图像大小(最好低于 1024 像素)。

  • 已知图像尺寸增加:当使用 HTMLCanvasElement.toDataURL 方法在浏览器端导出裁剪后的图像时,导出图像的尺寸可能会大于原始图像。 这是因为导出的图像类型与原始图像的类型不同。 因此,只需将原始图像的类型作为第一个参数传递给 toDataURL 即可解决此问题。 例如,如果原始类型为 JPEG,则使用 cropper.getCroppedCanvas().toDataURL('image/jpeg') 导出图像。

⬆ 返回顶部

Options

您可以使用 new Cropper(image, options) 设置裁剪选项。 如果你想改变全局默认选项,你可以使用 Cropper.setDefaults(options)

viewMode

  • Type: Number
  • Default: 0
  • Options:
  • 0: no restrictions
  • 1: restrict the crop box to not exceed the size of the canvas.
  • 2: restrict the minimum canvas size to fit within the container. If the proportions of the 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.

定义裁剪器的视图模式。 如果将 viewMode 设置为 0,则裁剪框可以延伸到画布之外,而值为 123 会将裁剪框限制为画布的大小。 23viewMode 会将画布限制在容器内。 请注意,如果画布和容器的比例相同,则 23 没有区别。

dragMode

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

定义裁剪器的拖动模式。

aspectRatio

  • Type: Number
  • Default: NaN

设置裁剪框的纵横比。 默认情况下,裁剪框是自由比例的。

data

  • Type: Object
  • Default: null

如果您存储了先前裁剪的数据,将在构建时自动传递给 setData 方法。

preview

添加额外的元素(容器)进行预览。

注意:

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

responsive

  • Type: Boolean
  • Default: true

调整窗口大小时重新渲染裁剪器。

restore

  • Type: Boolean
  • Default: true

调整窗口大小后恢复裁剪区域。

checkCrossOrigin

  • Type: Boolean
  • Default: true

检查当前图片是否为跨源图片。

如果是,当克隆图像时,一个crossOrigin属性将被添加到克隆的图像元素,并且一个时间戳将被添加到src属性以重新加载源图像到避免浏览器缓存错误。

通过向图像添加 crossOrigin 属性将停止向图像 url 添加时间戳,并停止重新加载图像。

如果图像的 crossOrigin 属性的值为 "use-credentials",则 withCredentials 属性将设置为 true 当通过 XMLHttpRequest 读取图像数据时。

checkOrientation

  • Type: Boolean
  • Default: true

检查当前图像的 Exif 方向信息。

更准确地说,读取用于旋转或翻转图像的 Orientation 值,然后用 1(默认值)覆盖 Orientation 值以避免一些问题(1, 2) 在 iOS 设备上。

需要同时将 rotatablescalable 选项设置为 true

注意:不要一直相信这一点,因为某些 JPG 图像的方向值不正确(非标准)。

需要Typed Arrays 支持(IE 10+)。

  • Type: Boolean
  • Default: true

在图像上方和裁剪框下方显示黑色模态。

guides

  • Type: Boolean
  • Default: true

在裁剪框上方显示虚线。

center

  • Type: Boolean
  • Default: true

在裁剪框上方显示中心指示器。

highlight

  • Type: Boolean
  • Default: true

在裁剪框上方显示白色模式(突出显示裁剪框)。

background

  • Type: Boolean
  • Default: true

显示容器的网格背景。

autoCrop

  • Type: Boolean
  • Default: true

启用初始化时自动裁剪图像。

autoCropArea

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

一个介于 0 和 1 之间的数字。定义自动裁剪区域的大小(百分比)。

movable

  • Type: Boolean
  • Default: true

启用移动图像。

rotatable

  • Type: Boolean
  • Default: true

启用旋转图像。

scalable

  • Type: Boolean
  • Default: true

启用缩放图像。

zoomable

  • Type: Boolean
  • Default: true

启用缩放图像。

zoomOnTouch

  • Type: Boolean
  • Default: true

启用通过拖动触摸来缩放图像。

zoomOnWheel

  • Type: Boolean
  • Default: true

启用通过滚轮鼠标缩放图像。

wheelZoomRatio

  • Type: Number
  • Default: 0.1

通过滚轮鼠标缩放图像时定义缩放比例。

cropBoxMovable

  • Type: Boolean
  • Default: true

启用通过拖动移动裁剪框。

cropBoxResizable

  • Type: Boolean
  • Default: true

启用以通过拖动调整裁剪框的大小。

toggleDragModeOnDblclick

  • Type: Boolean
  • Default: true

在裁剪器上单击两次时启用在“裁剪”和“移动”之间切换拖动模式。

minContainerWidth

  • Type: Number
  • Default: 200

容器的最小宽度。

minContainerHeight

  • Type: Number
  • Default: 100

容器的最小高度。

minCanvasWidth

  • Type: Number
  • Default: 0

画布的最小宽度(图像包装器)。

minCanvasHeight

  • Type: Number
  • Default: 0

画布的最小高度(图像包装器)。

minCropBoxWidth

  • Type: Number
  • Default: 0

裁剪框的最小宽度。

注意:此尺寸是相对于页面的,而不是图像。

minCropBoxHeight

  • Type: Number
  • Default: 0

裁剪框的最小高度。

注意:此尺寸是相对于页面的,而不是图像。

ready

  • Type: Function
  • Default: null

“就绪”事件的快捷方式。

cropstart

  • Type: Function
  • Default: null

“cropstart”事件的快捷方式。

cropmove

  • Type: Function
  • Default: null

“cropmove”事件的快捷方式。

cropend

  • Type: Function
  • Default: null

“cropend”事件的快捷方式。

crop

  • Type: Function
  • Default: null

“crop”事件的快捷方式。

zoom

  • Type: Function
  • Default: null

“缩放”事件的快捷方式。

⬆ back to top

Methods

由于加载图片时有一个异步进程,所以应该在之后调用大部分方法就绪,除了“setAspectRatio”、“replace”和“destroy”。

如果一个方法不需要返回任何值,它将返回 cropper 实例 (this) 用于链组合。

new Cropper(image, {
  ready: function () {
    // 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()

手动显示裁剪框。

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

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

reset()

将图像和裁剪框重置为初始状态。

clear()

清除裁剪框。

replace(url[, onlyColorChanged])

  • url

  • 类型:String

  • 一个新的图片 url。

  • onlyColorChanged(可选):

  • 类型:Boolean

  • 如果只改变颜色,不改变尺寸,裁剪器只需要改变所有相关图片的src,不需要重建收割机。 这可用于应用过滤器。

  • 如果不存在,其默认值为 false

替换图像的 src 并重建裁剪器。

enable()

启用(解冻)裁剪器。

disable()

禁用(冻结)裁剪器。

destroy()

销毁裁剪器并从图像中删除实例。

move(offsetX[, offsetY])

  • offsetX

  • 类型:Number

  • 水平方向移动大小(px)。

  • offsetY(可选):

  • 类型:Number

  • 垂直方向移动大小(px)。

  • 如果不存在,其默认值为 offsetX

使用相对偏移移动画布(图像包装器)。

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

moveTo(x[, y])

  • x

  • 类型:Number

  • 画布的left

  • y(可选):

  • 类型:Number

  • 画布的 top

  • 如果不存在,则其默认值为 x

将画布(图像包装器)移动到一个绝对点。

zoom(ratio)

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

以相对比例缩放画布(图像包装器)。

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

zoomTo(ratio[, pivot])

  • ratio

  • 类型:Number

  • 需要正数(ratio > 0)

  • pivot(可选):

  • 类型:Object

  • Schema: { x: Number, y: Number }

  • 缩放中心点的坐标,基于裁剪器容器的左上角。

将画布(图像包装器)缩放到绝对比例。

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)

  • degree:
  • Type: Number
  • Rotate right: requires a positive number (degree > 0)
  • Rotate left: requires a negative number (degree < 0)

以相对度数旋转图像。

需要 CSS3 2D Transforms 支持(IE 9+).

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

rotateTo(degree)

  • degree:
  • Type: Number

将图像旋转到绝对度数。

scale(scaleX[, scaleY])

  • scaleX

  • 类型:Number

  • 默认值:1

  • 应用于图像横坐标的缩放因子。

  • 当等于 1 时,它什么都不做。

  • scaleY(可选):

  • 类型:Number

  • 应用于图像纵坐标的比例因子。

  • 如果不存在,其默认值为 scaleX

缩放图像。

需要 CSS3 2D Transforms 支持(IE 9+).

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

scaleX(scaleX)

  • scaleX:
  • Type: Number
  • Default: 1
  • The scaling factor to apply on the abscissa of the image.
  • When equal to 1 it does nothing.

缩放图像的横坐标。

scaleY(scaleY)

  • scaleY:
  • Type: Number
  • Default: 1
  • The scaling factor to apply on the ordinate of the image.
  • When equal to 1 it does nothing.

缩放图像的纵坐标。

getData([rounded])

  • rounded(可选):

  • 类型:Boolean

  • 默认值:false

  • 设置 true 以获得四舍五入的值。

  • (返回值):

  • 类型: Object

  • 属性:

    • x: the offset left of the cropped area
    • y: the offset top of the cropped area
    • width: the width of the cropped area
    • height: the height of the cropped area
    • rotate: the rotated degrees of the image
    • scaleX: the scaling factor to apply on the abscissa of the image
    • scaleY: the scaling factor to apply on the ordinate of the image

输出最终裁剪区域的位置和大小数据(基于原始图像的自然大小)。

可以将数据发送到服务端直接裁剪

  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.

图片

setData(data)

  • data:
  • Type: Object
  • Properties: See the getData method.
  • You may need to round the data properties before passing them in.

:基于原始图像)。

注意:此方法仅在viewMode选项大于或等于1时可用。

getContainerData()

  • (return value):
  • Type: Object
  • Properties:
    • width: the current width of the container
    • height: the current height of the container

输出容器尺寸数据。

cropper图层示意图

getImageData()

  • (return value):
  • Type: Object
  • Properties:
    • left: the offset left of the image
    • top: the offset top of the image
    • width: the width of the image
    • height: the height of the image
    • naturalWidth: the natural width of the image
    • naturalHeight: the natural height of the image
    • aspectRatio: the aspect ratio of the image
    • rotate: the rotated degrees of the image if rotated
    • scaleX: the scaling factor to apply on the abscissa of the image if scaled
    • scaleY: the scaling factor to apply on the ordinate of the image if scaled

输出图像位置、大小等相关数据。

getCanvasData()

  • (return value):
  • Type: Object
  • Properties:
    • left: the offset left of the canvas
    • top: the offset top of the canvas
    • width: the width of the canvas
    • height: the height of the canvas
    • naturalWidth: the natural width of the canvas (read only)
    • naturalHeight: the natural height of the canvas (read only)

输出画布(图像包装器)位置和大小数据。

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

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

setCanvasData(data)

  • data:
  • Type: Object
  • Properties:
    • left: the new offset left of the canvas
    • top: the new offset top of the canvas
    • width: the new width of the canvas
    • height: the new height of the canvas

使用新数据更改画布(图像包装器)的位置和大小。

getCropBoxData()

  • (return value):
  • Type: Object
  • Properties:
    • left: the offset left of the crop box
    • top: the offset top of the crop box
    • width: the width of the crop box
    • height: the height of the crop box

输出裁剪框位置和大小数据。

setCropBoxData(data)

  • data:
  • Type: Object
  • Properties:
    • left: the new offset left of the crop box
    • top: the new offset top of the crop box
    • width: the new width of the crop box
    • height: the new height of the crop box

使用新数据更改裁剪框的位置和大小。

getCroppedCanvas([options])

  • options(可选):

  • 类型:Object

  • 属性:(

    • width: the destination width of the output canvas.
    • height: the destination height of the output canvas.
    • minWidth: the minimum destination width of the output canvas, the default value is 0.
    • minHeight: the minimum destination height of the output canvas, the default value is 0.
    • maxWidth: the maximum destination width of the output canvas, the default value is Infinity.
    • maxHeight: the maximum destination height of the output canvas, the default value is Infinity.
    • fillColor: a color to fill any alpha values in the output canvas, the default value is transparent.
    • imageSmoothingEnabled: set to change if images are smoothed (true, default) or not (false).
    • imageSmoothingQuality: set the quality of image smoothing, one of "low" (default), "medium", or "high".
  • 返回值):

  • 类型:HTMLCanvasElement

  • 绘制裁剪图像的画布。

  • 注意:

  • 输出画布的纵横比将自动适应裁剪框的纵横比。

  • 如果您打算从输出画布中获取 JPEG 图像,您应该首先设置 fillColor 选项,否则,JPEG 图像中的透明部分将默认变为黑色。

  • 浏览器支持:

  • 基本图像:需要 Canvas 支持(IE 9+)。

  • 旋转图像:需要 CSS3 2D Transforms 支持(IE 9+)。

  • 跨源图像:需要 HTML5 CORS 设置属性支持(IE 11+)。

获取绘制裁剪图像的画布。 如果未裁剪,则返回绘制整个图像的画布。

之后,您可以直接将画布显示为图像,或者使用 HTMLCanvasElement.toDataURL 获取数据 URL,或使用 HTMLCanvasElement.toBlob 获取blob 并使用 FormData 将其上传到服务器(如果浏览器支持这些 API)。

避免获得空白输出图像,您可能需要将 maxWidthmaxHeight 属性设置为有限的数字,因为 画布元素的大小限制

cropper.getCroppedCanvas();

cropper.getCroppedCanvas({
  width: 160,
  height: 90,
  minWidth: 256,
  minHeight: 256,
  maxWidth: 4096,
  maxHeight: 4096,
  fillColor: '#fff',
  imageSmoothingEnabled: false,
  imageSmoothingQuality: 'high',
});

// Upload cropped image to server if the browser supports `HTMLCanvasElement.toBlob`
cropper.getCroppedCanvas().toBlob(function (blob) {
  var formData = new FormData();

  formData.append('croppedImage', blob);

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

setAspectRatio(aspectRatio)

  • aspectRatio:
  • Type: Number
  • Requires a positive number.

更改裁剪框的纵横比。

setDragMode([mode])

  • mode (optional):
  • Type: String
  • Default: 'none'
  • Options: 'none', 'crop', 'move'

更改拖动模式。

提示:您可以通过双击裁剪器来切换“裁剪”和“移动”模式。

⬆ 返回页首

Events

ready

当目标图像已加载且裁剪器实例已准备好裁剪时,将触发此事件。

var cropper;

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

cropper = new Cropper(image);

cropstart

  • event.detail.originalEvent

  • 类型:Event

  • 选项:mousedowntouchstartpointerdown

  • event.detail.action

  • 类型:String

  • 选项:

    • 'crop': create a new crop box
    • 'move': move the canvas (image wrapper)
    • 'zoom': zoom in / out the canvas (image wrapper) by touch.
    • 'e': resize the east side of the crop box
    • 'w': resize the west side of the crop box
    • 's': resize the south side of the crop box
    • 'n': resize the north side of the crop box
    • 'se': resize the southeast side of the crop box
    • 'sw': resize the southwest side of the crop box
    • 'ne': resize the northeast side of the crop box
    • 'nw': resize the northwest side of the crop box
    • 'all': move the crop box (all directions)

当画布(图像包装器)或裁剪框开始更改时触发此事件。

image.addEventListener('cropstart', function (e) {
  console.log(e.detail.originalEvent);
  console.log(e.detail.action);
});

cropmove

  • event.detail.originalEvent

  • 类型:Event

  • 选项:mousemovetouchmovepointermove

  • event.detail.action:与“cropstart”相同。

当画布(图像包装器)或裁剪框发生变化时会触发此事件。

cropend

  • event.detail.originalEvent

  • 类型:Event

  • 选项:mouseuptouchendtouchcancelpointeruppointercancel

  • event.detail.action:与“cropstart”相同。

当画布(图像包装器)或裁剪框停止更改时会触发此事件。

crop

  • event.detail.x
  • event.detail.y
  • event.detail.width
  • event.detail.height
  • event.detail.rotate
  • event.detail.scaleX
  • event.detail.scaleY

关于这些属性,请参阅 getData 方法。

当画布(图像包装器)或裁剪框更改时会触发此事件。

zoom

  • event.detail.originalEvent

  • 类型:Event

  • 选项:wheeltouchmove

  • event.detail.oldRatio

  • 类型:Number

  • 画布的旧(当前)比率

  • event.detail.ratio

  • 类型:Number

  • 画布的新(下一个)比例 (canvasData.width / canvasData.naturalWidth)

当裁剪器实例开始放大或缩小其画布(图像包装器)时会触发此事件.

image.addEventListener('zoom', function (e) {

  // Zoom in
  if (e.detail.ratio > e.detail.oldRatio) {
    e.preventDefault(); // Prevent zoom in
  }

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

⬆ 回到顶部

No conflict

如果您必须使用具有相同命名空间的其他裁剪器,只需调用 Cropper.noConflict 静态方法来恢复给它。

<script src="other-cropper.js"></script>
<script src="cropper.js"></script>
<script>
  Cropper.noConflict();
  // Code that uses other `Cropper` can follow here.
</script>

Browser support

  • Chrome (latest)
  • Firefox (latest)
  • Safari (latest)
  • Opera (latest)
  • Edge (latest)
  • Internet Explorer 9+

Contributing

请通读我们的贡献指南

Versioning

根据语义版本控制指南进行维护。

License

麻省理工学院 © 陈丰源

Related projects

Cropper.js

Build StatusDownloadsVersion

JavaScript image cropper.

Table of contents

Features

  • Supports 38 options
  • Supports 27 methods
  • Supports 6 events
  • Supports touch (mobile)
  • Supports zooming
  • Supports rotating
  • Supports scaling (flipping)
  • Supports multiple croppers
  • Supports to crop on a canvas
  • Supports to crop image in the browser-side by canvas
  • Supports to translate Exif Orientation information
  • Cross-browser support

Main

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

Include files:

<link  href="/path/to/cropper.css" rel="stylesheet">
<script src="/path/to/cropper.js"></script>

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

Usage

Initialize with Cropper constructor:

  • Browser: window.Cropper
  • CommonJS: var Cropper = require('cropperjs')
  • ES2015: import Cropper from 'cropperjs'
<!-- Wrap the image or canvas element with a block element (container) -->
<div>
  <img id="image" src="picture.jpg">
</div>
/* Limit image width to avoid overflow the container */
img {
  max-width: 100%; /* This rule is very important, please do not ignore this! */
}
var image = document.getElementById('image');
var cropper = new Cropper(image, {
  aspectRatio: 16 / 9,
  crop: function(e) {
    console.log(e.detail.x);
    console.log(e.detail.y);
    console.log(e.detail.width);
    console.log(e.detail.height);
    console.log(e.detail.rotate);
    console.log(e.detail.scaleX);
    console.log(e.detail.scaleY);
  }
});

FAQ

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

Just double click your mouse to enter crop mode.

How to move the image after crop an area?

Just double click your mouse to enter move mode.

How to fix 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 shown completely. Otherwise, you will not get a correct cropper.

  • The outputted cropped data bases 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 start a cropper.

  • Known image size increase: When export the cropped image on 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's. So just pass the type the original image's 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 to not exceed the size of the canvas.
  • 2: restrict the minimum canvas size to fit within the container. If the proportions of the 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. A viewMode of 2 or 3 will additionally restrict the canvas to the container. Note that if the proportions of the canvas and the container are the same, there is no difference between 2 and 3.

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.

aspectRatio

  • Type: Number
  • Default: NaN

Set the aspect ratio of the crop box. By default, the crop box is free ratio.

data

  • Type: Object
  • Default: null

The previous cropped data if you had stored, will be passed to setData method automatically when built.

preview

Add extra elements (containers) for previewing.

Notes:

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

responsive

  • Type: Boolean
  • Default: true

Re-render the cropper when resize the window.

restore

  • Type: Boolean
  • Default: true

Restore the cropped area after resize the window.

checkCrossOrigin

  • Type: Boolean
  • Default: true

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

If it is, when clone the image, a crossOrigin attribute will be added to the cloned image element and a timestamp will be added to the src attribute to reload the source image to avoid browser cache error.

By adding crossOrigin attribute to image will stop adding timestamp to image url, and stop reload of image.

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.

More 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: Don't trust this all the time as some JPG images have incorrect (not standard) Orientation values.

Requires Typed Arrays support (IE 10+).

  • 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 initialize.

autoCropArea

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

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 wheeling mouse.

wheelZoomRatio

  • Type: Number
  • Default: 0.1

Define zoom ratio when zoom the image by wheeling mouse.

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 click twice on the cropper.

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 of the "ready" event.

cropstart

  • Type: Function
  • Default: null

A shortcut of the "cropstart" event.

cropmove

  • Type: Function
  • Default: null

A shortcut of the "cropmove" event.

cropend

  • Type: Function
  • Default: null

A shortcut of the "cropend" event.

crop

  • Type: Function
  • Default: null

A shortcut of the "crop" event.

zoom

  • Type: Function
  • Default: null

A shortcut of the "zoom" event.

⬆ back to top

Methods

As there is an asynchronous process when load 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: function () {
    // 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: function () {
    // Do something here
    // ...

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

reset()

Reset the image and crop box to their initial states.

clear()

Clear the crop box.

replace(url[, onlyColorChanged])

  • url:

  • Type: String

  • A new image url.

  • onlyColorChanged (optional):

  • Type: Boolean

  • If only change the color, not the size, then the cropper only need to change the srcs of all related images, not need to rebuild the cropper. This can be used for applying filters.

  • If not present, its default value is false.

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 zooming, base on the top left corner of the cropper container.

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)

  • degree:
  • Type: Number
  • Rotate right: requires a positive number (degree > 0)
  • Rotate left: requires a negative number (degree < 0)

Rotate the image with a relative degree.

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

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

rotateTo(degree)

  • degree:
  • Type: Number

Rotate the image to an absolute degree.

scale(scaleX[, scaleY])

  • scaleX:

  • Type: Number

  • Default: 1

  • The scaling factor to apply on the abscissa of the image.

  • When equal to 1 it does nothing.

  • scaleY (optional):

  • Type: Number

  • The scaling factor to apply on the ordinate of the image.

  • If not present, its default value is scaleX.

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)

  • scaleX:
  • Type: Number
  • Default: 1
  • The scaling factor to apply on the abscissa of the image.
  • When equal to 1 it does nothing.

Scale the abscissa of the image.

scaleY(scaleY)

  • scaleY:
  • Type: Number
  • Default: 1
  • The scaling factor to apply on the ordinate of the image.
  • When equal to 1 it does nothing.

Scale the ordinate of the image.

getData([rounded])

  • rounded (optional):

  • Type: Boolean

  • Default: false

  • Set true to get rounded values.

  • (return value):

  • Type: Object

  • Properties:

    • x: the offset left of the cropped area
    • y: the offset top of the cropped area
    • width: the width of the cropped area
    • height: the height of the cropped area
    • rotate: the rotated degrees of the image
    • scaleX: the scaling factor to apply on the abscissa of the image
    • scaleY: the scaling factor to apply on the ordinate of the image

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

You can send the data to 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)

  • data:
  • Type: Object
  • Properties: See the getData method.
  • You may need to round the data properties before passing them in.

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

Note: This method only available when the viewMode option great than or equal to 1.

getContainerData()

  • (return value):
  • Type: Object
  • Properties:
    • width: the current width of the container
    • height: the current height of the container

Output the container size data.

A schematic diagram for cropper's layers

getImageData()

  • (return value):
  • Type: Object
  • Properties:
    • left: the offset left of the image
    • top: the offset top of the image
    • width: the width of the image
    • height: the height of the image
    • naturalWidth: the natural width of the image
    • naturalHeight: the natural height of the image
    • aspectRatio: the aspect ratio of the image
    • rotate: the rotated degrees of the image if rotated
    • scaleX: the scaling factor to apply on the abscissa of the image if scaled
    • scaleY: the scaling factor to apply on the ordinate of the image if scaled

Output the image position, size and other related data.

getCanvasData()

  • (return value):
  • Type: Object
  • Properties:
    • left: the offset left of the canvas
    • top: the offset top of the canvas
    • width: the width of the canvas
    • height: the height of the canvas
    • naturalWidth: the natural width of the canvas (read only)
    • naturalHeight: the natural height of the canvas (read only)

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

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

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

setCanvasData(data)

  • data:
  • Type: Object
  • Properties:
    • left: the new offset left of the canvas
    • top: the new offset top of the canvas
    • width: the new width of the canvas
    • height: the new height of the canvas

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

getCropBoxData()

  • (return value):
  • Type: Object
  • Properties:
    • left: the offset left of the crop box
    • top: the offset top of the crop box
    • width: the width of the crop box
    • height: the height of the crop box

Output the crop box position and size data.

setCropBoxData(data)

  • data:
  • Type: Object
  • Properties:
    • left: the new offset left of the crop box
    • top: the new offset top of the crop box
    • width: the new width of the crop box
    • height: the new height of the crop box

Change the crop box position and size with new data.

getCroppedCanvas([options])

  • options (optional):

  • Type: Object

  • Properties:

    • width: the destination width of the output canvas.
    • height: the destination height of the output canvas.
    • minWidth: the minimum destination width of the output canvas, the default value is 0.
    • minHeight: the minimum destination height of the output canvas, the default value is 0.
    • maxWidth: the maximum destination width of the output canvas, the default value is Infinity.
    • maxHeight: the maximum destination height of the output canvas, the default value is Infinity.
    • fillColor: a color to fill any alpha values in the output canvas, the default value is transparent.
    • imageSmoothingEnabled: set to change if images are smoothed (true, default) or not (false).
    • imageSmoothingQuality: set the quality of image smoothing, one of "low" (default), "medium", or "high".
  • (return value):

  • Type: HTMLCanvasElement

  • A canvas drawn the cropped image.

  • Notes:

  • The aspect ratio of the output canvas will be fitted to aspect ratio of the crop box automatically.

  • If you intend to get a JPEG image from the output canvas, you should set the fillColor option first, if not, the transparent part in the JPEG image will become black by default.

  • Browser support:

  • Basic image: requires Canvas support (IE 9+).

  • Rotated image: requires CSS3 2D Transforms support (IE 9+).

  • Cross-origin image: requires HTML5 CORS settings attributes support (IE 11+).

Get a canvas drawn the cropped image. 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 to get a blank output image, you might need to set the maxWidth and maxHeight properties to limited numbers, because of the size limits of a canvas element.

cropper.getCroppedCanvas();

cropper.getCroppedCanvas({
  width: 160,
  height: 90,
  minWidth: 256,
  minHeight: 256,
  maxWidth: 4096,
  maxHeight: 4096,
  fillColor: '#fff',
  imageSmoothingEnabled: false,
  imageSmoothingQuality: 'high',
});

// Upload cropped image to server if the browser supports `HTMLCanvasElement.toBlob`
cropper.getCroppedCanvas().toBlob(function (blob) {
  var formData = new FormData();

  formData.append('croppedImage', blob);

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

setAspectRatio(aspectRatio)

  • aspectRatio:
  • Type: Number
  • Requires a positive number.

Change the aspect ratio of the crop box.

setDragMode([mode])

  • mode (optional):
  • Type: String
  • Default: 'none'
  • Options: 'none', 'crop', 'move'

Change the drag mode.

Tips: You can toggle the "crop" and "move" mode by double click 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 cropping.

var cropper;

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

cropper = new Cropper(image);

cropstart

  • event.detail.originalEvent:

  • Type: Event

  • Options: mousedown, touchstart and pointerdown

  • event.detail.action:

  • Type: String

  • Options:

    • 'crop': create a new crop box
    • 'move': move the canvas (image wrapper)
    • 'zoom': zoom in / out the canvas (image wrapper) by touch.
    • 'e': resize the east side of the crop box
    • 'w': resize the west side of the crop box
    • 's': resize the south side of the crop box
    • 'n': resize the north side of the crop box
    • 'se': resize the southeast side of the crop box
    • 'sw': resize the southwest side of the crop box
    • 'ne': resize the northeast side of the crop box
    • 'nw': resize the northwest side of the crop box
    • 'all': move the crop box (all directions)

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

image.addEventListener('cropstart', function (e) {
  console.log(e.detail.originalEvent);
  console.log(e.detail.action);
});

cropmove

  • event.detail.originalEvent:

  • Type: Event

  • Options: mousemove, touchmove and pointermove.

  • event.detail.action: the same as "cropstart".

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

cropend

  • event.detail.originalEvent:

  • Type: Event

  • Options: mouseup, touchend, touchcancel, pointerup and pointercancel.

  • event.detail.action: the same as "cropstart".

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

crop

  • event.detail.x
  • event.detail.y
  • event.detail.width
  • event.detail.height
  • event.detail.rotate
  • event.detail.scaleX
  • event.detail.scaleY

About these properties, see the getData method.

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

zoom

  • event.detail.originalEvent:

  • Type: Event

  • Options: wheel, touchmove.

  • event.detail.oldRatio:

  • Type: Number

  • The old (current) ratio of the canvas

  • event.detail.ratio:

  • Type: Number

  • The new (next) ratio of the canvas (canvasData.width / canvasData.naturalWidth)

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

image.addEventListener('zoom', function (e) {

  // Zoom in
  if (e.detail.ratio > e.detail.oldRatio) {
    e.preventDefault(); // Prevent zoom in
  }

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

⬆ back to top

No conflict

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

<script src="other-cropper.js"></script>
<script src="cropper.js"></script>
<script>
  Cropper.noConflict();
  // Code that uses other `Cropper` can follow here.
</script>

Browser support

  • Chrome (latest)
  • Firefox (latest)
  • Safari (latest)
  • Opera (latest)
  • Edge (latest)
  • Internet Explorer 9+

Contributing

Please read through our contributing guidelines.

Versioning

Maintained under the Semantic Versioning guidelines.

License

MIT © Chen Fengyuan

Related projects

⬆ back to top

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文