intelogie / cropper
Installs: 101
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 2
Forks: 1 735
Language:JavaScript
This package is auto-updated.
Last update: 2024-10-29 03:38:17 UTC
README
A simple jQuery image cropping plugin.
Table of contents
- Features
- Main
- Getting started
- Options
- Methods
- Events
- No conflict
- Browser support
- Contributing
- Versioning
- License
Features
- Supports 39 options
- Supports 27 methods
- Supports 7 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 ( 5 KB)
├── cropper.min.css ( 4 KB)
├── cropper.js (78 KB)
└── cropper.min.js (28 KB)
Getting started
Quick start
Four quick start options are available:
- Download the latest release.
- Clone the repository:
git clone https://github.com/fengyuanchen/cropper.git
. - Install with NPM:
npm install cropper
. - Install with Bower:
bower install cropper
.
Installation
Include files:
<script src="/path/to/jquery.js"></script><!-- jQuery is required --> <link href="/path/to/cropper.css" rel="stylesheet"> <script src="/path/to/cropper.js"></script>
The cdnjs provides CDN support for Cropper's CSS and JavaScript. You can find the links here.
Usage
Initialize with $.fn.cropper
method.
<!-- 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! */ }
$('#image').cropper({ aspectRatio: 16 / 9, crop: function(e) { // Output the result data for cropping image. console.log(e.x); console.log(e.y); console.log(e.width); console.log(e.height); console.log(e.rotate); console.log(e.scaleX); console.log(e.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 (below 1024px) 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 totoDataURL
to fix this. For example, if the original type is JPEG, then use$().cropper('getCroppedCanvas').toDataURL('image/jpeg')
to export image.
Options
You may set cropper options with $().cropper(options)
.
If you want to change the global default options, You may use $.fn.cropper.setDefaults(options)
.
viewMode
- Type:
Number
- Default:
0
- Options:
0
: the crop box is just within the container1
: the crop box should be within the canvas2
: the canvas should not be within the container3
: the container should be within the canvas
Define the view mode of the cropper.
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.
preview
- Type:
String
(jQuery selector) - Default:
''
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 preview container with the same aspect ratio. - If preview is not getting properly displayed, set
overflow:hidden
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.
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 (#120, #509) 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+).
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 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.
build
- Type:
Function
- Default:
null
A shortcut of the "build.cropper" event.
built
- Type:
Function
- Default:
null
A shortcut of the "built.cropper" event.
cropstart
- Type:
Function
- Default:
null
A shortcut of the "cropstart.cropper" event.
cropmove
- Type:
Function
- Default:
null
A shortcut of the "cropmove.cropper" event.
cropend
- Type:
Function
- Default:
null
A shortcut of the "cropend.cropper" event.
crop
- Type:
Function
- Default:
null
A shortcut of the "crop.cropper" event.
zoom
- Type:
Function
- Default:
null
A shortcut of the "zoom.cropper" event.
Methods
As there is an asynchronous process when load the image, you should call most of the methods after built, except "setAspectRatio", "replace" and "destroy".
$().cropper({ built: function () { $().cropper('method', argument1, , argument2, ..., argumentN); } });
crop()
Show the crop box manually.
$().cropper({ autoCrop: false, built: 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.
- Type:
-
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
.
- Type:
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.
- Type:
-
offsetY (optional):
- Type:
Number
- Moving size (px) in the vertical direction.
- If not present, its default value is
offsetX
.
- Type:
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
- Type:
-
y (optional):
- Type:
Number
- The
top
value of the canvas - If not present, its default value is
x
.
- Type:
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)
- Type:
Zoom the canvas (image wrapper) with a relative ratio.
$().cropper('zoom', 0.1); $().cropper('zoom', -0.1);
zoomTo(ratio)
- ratio:
- Type:
Number
- Type:
Zoom the canvas (image wrapper) to an absolute ratio.
$().cropper('zoomTo', 1); // 1:1 (canvasData.width === canvasData.naturalWidth)
rotate(degree)
- degree:
- Type:
Number
- Rotate right: requires a positive number (degree > 0)
- Rotate left: requires a negative number (degree < 0)
- Type:
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
- Type:
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.
- Type:
-
scaleY (optional):
- Type:
Number
- The scaling factor to apply on the ordinate of the image.
- If not present, its default value is
scaleX
.
- Type:
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.
- Type:
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.
- Type:
Scale the ordinate of the image.
getData([rounded])
-
rounded (optional):
- Type:
Boolean
- Default:
false
- Set
true
to get rounded values.
- Type:
-
(return value):
- Type:
Object
- Properties:
x
: the offset left of the cropped areay
: the offset top of the cropped areawidth
: the width of the cropped areaheight
: the height of the cropped arearotate
: the rotated degrees of the imagescaleX
: the scaling factor to apply on the abscissa of the imagescaleY
: the scaling factor to apply on the ordinate of the image
- Type:
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.
setData(data)
- data:
- Type:
Object
- Properties: See the
getData
method.
- Type:
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 to1
.
getContainerData()
- (return value):
- Type:
Object
- Properties:
width
: the current width of the containerheight
: the current height of the container
- Type:
Output the container size data.
getImageData()
- (return value):
- Type:
Object
- Properties:
left
: the offset left of the imagetop
: the offset top of the imagewidth
: the width of the imageheight
: the height of the imagenaturalWidth
: the natural width of the imagenaturalHeight
: the natural height of the imageaspectRatio
: the aspect ratio of the imagerotate
: the rotated degrees of the image if rotatedscaleX
: the scaling factor to apply on the abscissa of the image if scaledscaleY
: the scaling factor to apply on the ordinate of the image if scaled
- Type:
Output the image position, size and other related data.
getCanvasData()
- (return value):
- Type:
Object
- Properties:
left
: the offset left of the canvastop
: the offset top of the canvaswidth
: the width of the canvasheight
: the height of the canvasnaturalWidth
: the natural width of the canvas (read only)naturalHeight
: the natural height of the canvas (read only)
- Type:
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 canvastop
: the new offset top of the canvaswidth
: the new width of the canvasheight
: the new height of the canvas
- Type:
Change the canvas (image wrapper) position and size with new data.
getCropBoxData()
- (return value):
- Type:
Object
- Properties:
left
: the offset left of the crop boxtop
: the offset top of the crop boxwidth
: the width of the crop boxheight
: the height of the crop box
- Type:
Output the crop box position and size data.
setCropBoxData(data)
- data:
- Type:
Object
- Properties:
left
: the new offset left of the crop boxtop
: the new offset top of the crop boxwidth
: the new width of the crop boxheight
: the new height of the crop box
- Type:
Change the crop box position and size with new data.
getCroppedCanvas([options])
-
options (optional):
- Type:
Object
- Properties:
width
: the destination width of the output canvasheight
: the destination height of the output canvasfillColor
: a color to fill any alpha values in the output canvas
- Note: The aspect ratio of the output canvas will be fitted to aspect ratio of the crop box automatically.
- Type:
-
(return value):
- Type:
HTMLCanvasElement
- A canvas drawn the cropped image.
- Type:
-
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 the whole canvas.
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.
$().cropper('getCroppedCanvas'); $().cropper('getCroppedCanvas', { width: 160, height: 90 }); // Upload cropped image to server if the browser supports `HTMLCanvasElement.toBlob` $().cropper('getCroppedCanvas').toBlob(function (blob) { var formData = new FormData(); formData.append('croppedImage', blob); $.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.
- Type:
Change the aspect ratio of the crop box.
setDragMode([mode])
- mode (optional):
- Type:
String
- Default:
'none'
- Options:
'none'
,'crop'
,'move'
- Type:
Change the drag mode.
Tips: You can toggle the "crop" and "move" mode by double click on the cropper.
Events
build.cropper
This event fires when a cropper instance starts to load an image.
built.cropper
This event fires when a cropper instance has built completely.
cropstart.cropper
-
event.originalEvent:
- Type:
Event
- Options:
mousedown
,touchstart
andpointerdown
- Type:
-
event.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)
- Type:
This event fires when the canvas (image wrapper) or the crop box starts to change.
$().on('cropstart.cropper', function (e) { console.log(e.type); // cropstart console.log(e.namespace); // cropper console.log(e.action); // ... console.log(e.originalEvent.pageX); // Prevent to start cropping, moving, etc if necessary if (e.action === 'crop') { e.preventDefault(); } });
cropmove.cropper
-
event.originalEvent:
- Type:
Event
- Options:
mousemove
,touchmove
andpointermove
.
- Type:
-
event.action: the same as "cropstart.cropper".
This event fires when the canvas (image wrapper) or the crop box is changing.
cropend.cropper
-
event.originalEvent:
- Type:
Event
- Options:
mouseup
,touchend
,touchcancel
,pointerup
andpointercancel
.
- Type:
-
event.action: the same as "cropstart.cropper".
This event fires when the canvas (image wrapper) or the crop box stops to change.
crop.cropper
- event.x
- event.y
- event.width
- event.height
- event.rotate
- event.scaleX
- event.scaleY
About these properties, see the
getData
method.
This event fires when the canvas (image wrapper) or the crop box changed.
zoom.cropper
-
event.originalEvent:
- Type:
Event
- Options:
wheel
,touchmove
.
- Type:
-
event.oldRatio:
- Type:
Number
- The old (current) ratio of the canvas
- Type:
-
event.ratio:
- Type:
Number
- The new (next) ratio of the canvas (
canvasData.width / canvasData.naturalWidth
)
- Type:
This event fires when a cropper instance starts to zoom in or zoom out its canvas (image wrapper).
$().on('zoom.cropper', function (e) { // Zoom in if (e.ratio > e.oldRatio) { // Prevent zoom in e.preventDefault(); } // Zoom out // ... });
No conflict
If you have to use other plugin with the same namespace, just call the $.fn.cropper.noConflict
method to revert to it.
<script src="other-plugin.js"></script> <script src="cropper.js"></script> <script> $.fn.cropper.noConflict(); // Code that uses other plugin's "$().cropper" can follow here. </script>
Browser support
- Chrome (latest)
- Firefox (latest)
- Safari (latest)
- Opera (latest)
- Edge (latest)
- Internet Explorer 8+
As a jQuery plugin, you also need to see the jQuery Browser Support.
Contributing
Please read through our contributing guidelines.
Versioning
Maintained under the Semantic Versioning guidelines.
License
Related projects
- ember-cli-image-cropper by @mhretab
- Image Widget Crop - the main Crop solution in Drupal 8
- meteor-cropper by @jonblum
- ngCropper by @koorgoo
- redux-cropper by @lapanoid