Gathering detailed insights and metrics for cropperjs
Gathering detailed insights and metrics for cropperjs
Gathering detailed insights and metrics for cropperjs
Gathering detailed insights and metrics for cropperjs
npm install cropperjs
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
13,149 Stars
743 Commits
2,417 Forks
172 Watching
4 Branches
42 Contributors
Updated on 27 Nov 2024
Minified
Minified + Gzipped
JavaScript (95.91%)
SCSS (2.09%)
CSS (1.94%)
Shell (0.06%)
Cumulative downloads
Total Downloads
Last day
-3.7%
166,834
Compared to previous day
Last week
0.2%
847,398
Compared to previous week
Last month
14.4%
3,600,559
Compared to previous month
Last year
30.4%
37,191,907
Compared to previous year
39
JavaScript image cropper. This is the branch for v1.x, for v2.x, check out the
v2
branch.
1dist/ 2├── cropper.css 3├── cropper.min.css (compressed) 4├── cropper.js (UMD) 5├── cropper.min.js (UMD, compressed) 6├── cropper.common.js (CommonJS, default) 7└── cropper.esm.js (ES Module)
1npm install cropperjs
In browser:
1<link href="/path/to/cropper.css" rel="stylesheet"> 2<script src="/path/to/cropper.js"></script>
cdnjs provides CDN support for Cropper.js's CSS and JavaScript. You can find the links here.
1new Cropper(element[, options])
element
HTMLImageElement
or HTMLCanvasElement
options (optional)
Object
1<!-- Wrap the image or canvas element with a block element (container) --> 2<div> 3 <img id="image" src="picture.jpg"> 4</div>
1/* Make sure the size of the image fits perfectly into the container */ 2img { 3 display: block; 4 5 /* This rule is very important, please don't ignore this */ 6 max-width: 100%; 7}
1// import 'cropperjs/dist/cropper.css'; 2import Cropper from 'cropperjs'; 3 4const image = document.getElementById('image'); 5const cropper = new Cropper(image, { 6 aspectRatio: 16 / 9, 7 crop(event) { 8 console.log(event.detail.x); 9 console.log(event.detail.y); 10 console.log(event.detail.width); 11 console.log(event.detail.height); 12 console.log(event.detail.rotate); 13 console.log(event.detail.scaleX); 14 console.log(event.detail.scaleY); 15 }, 16});
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.
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 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.
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)
.
Number
0
0
: no restrictions1
: 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.
String
'crop'
'crop'
: create a new crop box'move'
: move the canvas'none'
: do nothingDefine the dragging mode of the cropper.
Number
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 toNaN
.
Number
NaN
Define the fixed aspect ratio of the crop box. By default, the crop box has a free ratio.
Object
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 thetrue
.
Element
, Array
(elements), NodeList
or String
(selector)''
Add extra elements (containers) for preview.
Notes:
aspectRatio
option, be sure to set the same aspect ratio to the preview container.overflow: hidden
style to the preview container.Boolean
true
Re-render the cropper when resizing the window.
Boolean
true
Restore the cropped area after resizing the window.
Boolean
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.
Boolean
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+).
Boolean
true
Show the black modal above the image and under the crop box.
Boolean
true
Show the dashed lines above the crop box.
Boolean
true
Show the center indicator above the crop box.
Boolean
true
Show the white modal above the crop box (highlight the crop box).
Boolean
true
Show the grid background of the container.
Boolean
true
Enable to crop the image automatically when initialized.
Number
0.8
(80% of the image)It should be a number between 0 and 1. Define the automatic cropping area size (percentage).
Boolean
true
Enable to move the image.
Boolean
true
Enable to rotate the image.
Boolean
true
Enable to scale the image.
Boolean
true
Enable to zoom the image.
Boolean
true
Enable to zoom the image by dragging touch.
Boolean
true
Enable to zoom the image by mouse wheeling.
Number
0.1
Define zoom ratio when zooming the image by mouse wheeling.
Boolean
true
Enable to move the crop box by dragging.
Boolean
true
Enable to resize the crop box by dragging.
Boolean
true
Enable to toggle drag mode between "crop"
and "move"
when clicking twice on the cropper.
Requires
dblclick
event support.
Number
200
The minimum width of the container.
Number
100
The minimum height of the container.
Number
0
The minimum width of the canvas (image wrapper).
Number
0
The minimum height of the canvas (image wrapper).
Number
0
The minimum width of the crop box.
Note: This size is relative to the page, not the image.
Number
0
The minimum height of the crop box.
Note: This size is relative to the page, not the image.
Function
null
A shortcut to the ready
event.
Function
null
A shortcut to the cropstart
event.
Function
null
A shortcut to the cropmove
event.
Function
null
A shortcut to the cropend
event.
Function
null
A shortcut to the crop
event.
Function
null
A shortcut to the zoom
event.
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.
1new Cropper(image, { 2 ready() { 3 // this.cropper[method](argument1, , argument2, ..., argumentN); 4 this.cropper.move(1, -1); 5 6 // Allows chain composition 7 this.cropper.move(1, -1).rotate(45).scale(1, -1); 8 }, 9});
Show the crop box manually.
1new Cropper(image, {
2 autoCrop: false,
3 ready() {
4 // Do something here
5 // ...
6
7 // And then
8 this.cropper.crop();
9 },
10});
Reset the image and crop box to its initial states.
Clear the crop box.
url:
String
hasSameSize (optional):
Boolean
false
Replace the image's src and rebuild the cropper.
Enable (unfreeze) the cropper.
Disable (freeze) the cropper.
Destroy the cropper and remove the instance from the image.
offsetX:
Number
offsetY (optional):
Number
offsetX
.Move the canvas (image wrapper) with relative offsets.
1cropper.move(1); 2cropper.move(1, 0); 3cropper.move(0, -1);
x:
Number
left
value of the canvasy (optional):
Number
top
value of the canvasx
.Move the canvas (image wrapper) to an absolute point.
Number
Zoom the canvas (image wrapper) with a relative ratio.
1cropper.zoom(0.1); 2cropper.zoom(-0.1);
ratio:
Number
pivot (optional):
Object
{ x: Number, y: Number }
Zoom the canvas (image wrapper) to an absolute ratio.
1cropper.zoomTo(1); // 1:1 (canvasData.width === canvasData.naturalWidth)
2
3const containerData = cropper.getContainerData();
4
5// Zoom to 50% from the center of the container.
6cropper.zoomTo(.5, {
7 x: containerData.width / 2,
8 y: containerData.height / 2,
9});
Number
Rotate the image to a relative degree.
Requires CSS3 2D Transforms support (IE 9+).
1cropper.rotate(90); 2cropper.rotate(-90);
Number
Rotate the image to an absolute degree.
scaleX:
Number
1
1
it does nothing.scaleY (optional):
Number
scaleX
.Scale the image.
Requires CSS3 2D Transforms support (IE 9+).
1cropper.scale(-1); // Flip both horizontal and vertical 2cropper.scale(-1, 1); // Flip horizontal 3cropper.scale(1, -1); // Flip vertical
Number
1
1
it does nothing.Scale the abscissa of the image.
Number
1
1
it does nothing.Scale the ordinate of the image.
rounded (optional):
Boolean
false
true
to get rounded values.(return value):
Object
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 imageOutput 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:
- Rotate the image with the
rotate
property.- Scale the image with the
scaleX
andscaleY
properties.- Crop the image with the
x
,y
,width
, andheight
properties.
Object
getData
method.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 to1
.
Object
width
: the current width of the containerheight
: the current height of the containerOutput the container size data.
Object
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 it is 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 scaledOutput the image position, size, and other related data.
Object
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)Output the canvas (image wrapper) position and size data.
1const imageData = cropper.getImageData(); 2const canvasData = cropper.getCanvasData(); 3 4if (imageData.rotate % 180 === 0) { 5 console.log(canvasData.naturalWidth === imageData.naturalWidth); 6 // > true 7}
Object
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 canvasChange the canvas (image wrapper) position and size with new data.
Object
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 boxOutput the crop box position and size data.
Object
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 boxChange the crop box position and size with new data.
options (optional):
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 the 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".rounded
: set true
to use rounded values (the cropped area position and size data), the default value is false
.(return value):
HTMLCanvasElement
Notes:
fillColor
option first, if not, the transparent part in the JPEG image will become black by default.Browser support:
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.
1cropper.getCroppedCanvas(); 2 3cropper.getCroppedCanvas({ 4 width: 160, 5 height: 90, 6}); 7 8cropper.getCroppedCanvas({ 9 minWidth: 256, 10 minHeight: 256, 11 maxWidth: 4096, 12 maxHeight: 4096, 13}); 14 15cropper.getCroppedCanvas({ 16 fillColor: '#fff', 17 imageSmoothingEnabled: false, 18 imageSmoothingQuality: 'high', 19}); 20 21// Upload cropped image to server if the browser supports `HTMLCanvasElement.toBlob`. 22// The default value for the second parameter of `toBlob` is 'image/png', change it if necessary. 23cropper.getCroppedCanvas().toBlob((blob) => { 24 const formData = new FormData(); 25 26 // Pass the image file name as the third parameter if necessary. 27 formData.append('croppedImage', blob/*, 'example.png' */); 28 29 // Use `jQuery.ajax` method for example 30 $.ajax('/path/to/upload', { 31 method: 'POST', 32 data: formData, 33 processData: false, 34 contentType: false, 35 success() { 36 console.log('Upload success'); 37 }, 38 error() { 39 console.log('Upload error'); 40 }, 41 }); 42}/*, 'image/png' */);
Number
Change the aspect ratio of the crop box.
String
'none'
'none'
, 'crop'
, 'move'
Change the drag mode.
Tips: You can toggle the "crop" and "move" mode by double clicking on the cropper.
This event fires when the target image has been loaded and the cropper instance is ready for operating.
1let cropper; 2 3image.addEventListener('ready', function () { 4 console.log(this.cropper === cropper); 5 // > true 6}); 7 8cropper = new Cropper(image);
event.detail.originalEvent:
Event
pointerdown
, touchstart
, and mousedown
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)This event fires when the canvas (image wrapper) or the crop box starts to change.
1image.addEventListener('cropstart', (event) => { 2 console.log(event.detail.originalEvent); 3 console.log(event.detail.action); 4});
event.detail.originalEvent:
Event
pointermove
, touchmove
, and mousemove
.event.detail.action: the same as "cropstart".
This event fires when the canvas (image wrapper) or the crop box is changing.
event.detail.originalEvent:
Event
pointerup
, pointercancel
, touchend
, touchcancel
, and mouseup
.event.detail.action: the same as "cropstart".
This event fires when the canvas (image wrapper) or the crop box stops changing.
About these properties, see the
getData
method.
This event fires when the canvas (image wrapper) or the crop box changes.
Notes:
autoCrop
option is set to the true
, a crop
event will be triggered before the ready
event.data
option is set, another crop
event will be triggered before the ready
event.event.detail.originalEvent:
Event
wheel
, pointermove
, touchmove
, and mousemove
.event.detail.oldRatio:
Number
event.detail.ratio:
Number
canvasData.width / canvasData.naturalWidth
)This event fires when a cropper instance starts to zoom in or zoom out its canvas (image wrapper).
1image.addEventListener('zoom', (event) => { 2 // Zoom in 3 if (event.detail.ratio > event.detail.oldRatio) { 4 event.preventDefault(); // Prevent zoom in 5 } 6 7 // Zoom out 8 // ... 9});
If you have to use another cropper with the same namespace, just call the Cropper.noConflict
static method to revert to it.
1<script src="other-cropper.js"></script> 2<script src="cropper.js"></script> 3<script> 4 Cropper.noConflict(); 5 // Code that uses other `Cropper` can follow here. 6</script>
Please read through our contributing guidelines.
Maintained under the Semantic Versioning guidelines.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
8 commit(s) and 13 issue activity found in the last 90 days -- score normalized to 10
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
3 existing vulnerabilities detected
Details
Reason
Found 6/30 approved changesets -- score normalized to 2
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More