Giter Site home page Giter Site logo

fengyuanchen / cropperjs Goto Github PK

View Code? Open in Web Editor NEW
12.7K 173.0 2.4K 13.03 MB

JavaScript image cropper.

Home Page: https://fengyuanchen.github.io/cropperjs/

License: MIT License

CSS 1.94% JavaScript 95.91% SCSS 2.09% Shell 0.06%
image-cropper image-processing cropper cropperjs javascript

cropperjs's Introduction

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 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 to 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 applies to 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 applies to 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 (based on the natural size of the original image).

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

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

A schematic diagram for data's properties

setData(data)

  • 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 (based on the original image).

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

getContainerData()

  • (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 it is 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.

const imageData = cropper.getImageData();
const 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 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):

    • Type: HTMLCanvasElement
    • A canvas drawn the cropped image.
  • Notes:

    • The aspect ratio of the output canvas will be fitted to the 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.
    • Uses the Browser's native canvas.toBlob API to do the compression work, which means it is lossy compression. For better image quality, you can upload the original image and the cropped data to a server and do the crop work on the server.
  • 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.

cropper.getCroppedCanvas();

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

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

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

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

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

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

setAspectRatio(aspectRatio)

  • 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 clicking on the cropper.

⬆ back to top

Events

ready

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

let cropper;

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

cropper = new Cropper(image);

cropstart

  • event.detail.originalEvent:

    • Type: Event
    • Options: pointerdown, touchstart, and mousedown
  • 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', (event) => {
  console.log(event.detail.originalEvent);
  console.log(event.detail.action);
});

cropmove

  • event.detail.originalEvent:

    • Type: Event
    • Options: 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.

cropend

  • event.detail.originalEvent:

    • Type: Event
    • Options: 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.

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 changes.

Notes:

  • When the autoCrop option is set to the true, a crop event will be triggered before the ready event.
  • When the data option is set, another crop event will be triggered before the ready event.

zoom

  • event.detail.originalEvent:

    • Type: Event
    • Options: wheel, pointermove, touchmove, and mousemove.
  • 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', (event) => {
  // Zoom in
  if (event.detail.ratio > event.detail.oldRatio) {
    event.preventDefault(); // Prevent zoom in
  }

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

⬆ back to top

No conflict

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

<script src="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

cropperjs's People

Contributors

7anshuai avatar akccakcctw avatar anyexinglu avatar arusakov avatar badalsurana avatar bilal-io avatar biomedia-thomas avatar bryanakitchen avatar dependabot[bot] avatar elf-pavlik avatar epzee avatar fengyuanchen avatar gaborfeher avatar johnmarkbeaty avatar joshmccullough avatar kgathuru avatar larsrdev avatar lcp0578 avatar maks3w avatar manduro avatar maxymgorn avatar musaffa avatar nelsonblaha avatar pbojinov avatar septs avatar shekhar-shubhendu avatar stof avatar vincecyliao avatar vinnymac avatar w3blogfr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cropperjs's Issues

How to rotate ?

Hi, first, I apologize for asking this here, but I don't know where to put it.
I wanted to give a try to the demo and I can't figure out how I can modify the degree variable, I tried to put function in the console of Chrome such as : $('#image').rotate(5) but it says that it doesn't "recognize the function rotate", tried several ways since the beginning of the week but I really don't know what to do...

Regards

After calling replace(), getCroppedCanvas returns original image

To reproduce:

  1. Create a cropper, initialize it with an image
  2. Load another image with a different img tag.
  3. Once loaded, call replace() (it doesn't matter if the 2nd argument is true or false)
  4. Call getCroppedCanvas() and note the image isn't the one from replace(), it's the original image.

I'm doing manipulation on an image, then calling replace(). I'm taking the original image, altering it, then setting a different image element with the resulting DataURL. I take that new image element and call replace() on cropper. Instead of seeing the replaced image as output from the the getCroppedCanvas, it only shows the original image cropped. I've tried replacing the original image's src with the updated image but cropper still returns the wrong image

Just to note: I do see the updated image in the cropper.

Error uploading/cropping data in Safari

I am experiencing a Safari specici issue. Everything works fine in Chrome.

But when I upload an image I get two errors in Safari on line 118:77 of cropper.min.js

2016-05-15_0630

The data is in data:image/png format so I am not sure if it is some sort of CORS related issue. Any ideas?

Access-Control-Allow-Origin error while using remote urls

Hi i am using Cropper.js plugin in my site it is really fabulous ,it has everything what i need.but i am having some problem while using remote url in the image src. if i am referencing an image from the local drive means ,the cropper crops the image and send the data to the server without issues.but i am having problem while using remote urls as the example below.and the image is the container is present only if i add the option checkCrossOrigin:false when i am using remote url. couldn't figure out what is going wrong please help me out.

<!DOCTYPE html>
<html>
<head>
    <title> Cropperjs issue </title>
    <link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">
    <link rel="stylesheet" href="css/cropper.css" >
    <style>
         #cropper-container{
            width:500px;
            max-height:516px;
            position:relative;
         }
         #cropper-container img{
            max-width:100%;
         }
         #cropper-controls{
            position:absolute;
            left:50%;
            bottom:0px;
            z-index:2015;
            width:256px;
            height:32px;
            margin-left:-128px;
            background-color:rgba(0,0,0,0.5);
            color:#fff;
         }
         #cropper-controls .cropper-control-button{
            margin:0px;
            padding:0px;
            float: left;
            display: block;
            width: 32px;
            height: 32px;
            border-width: 0;
            font-size: 14px;
            text-align: center;
            background-color: transparent;
            color: #fff;
            cursor: pointer;
            box-shadow:none;
        }
        #cropper-controls .cropper-control-button:hover{
            background-color: #2ba6cb;
        }
    </style>
</head>
<body>

   <div id="cropper-container">
      <img id="cropper-img" src="http://az697095.vo.msecnd.net/vnext/products/137/3264/32a_149_137_3264_683.jpg" />
      <div id="cropper-controls">
            <button class="cropper-control-button cropper-dragMode" > <span class="icon-move" ></span> </button> 
            <button class="cropper-control-button cropper-cropMode" > <span class="icon-crop"></span> </button> 
            <button class="cropper-control-button cropper-zoomIn" > <span class="icon-zoom-in" ></span> </button> 
            <button class="cropper-control-button cropper-ZoomOut" > <span class="icon-zoom-out" ></span> </button> 
            <button class="cropper-control-button cropper-rotateLeft" > <span class="icon-rotate-left"></span> </button> 
            <button class="cropper-control-button cropper-rotateRight" > <span class="icon-rotate-right"></span> </button> 
            <button class="cropper-control-button cropper-refresh" > <span class="icon-refresh" ></span> </button> 
            <button class="cropper-control-button cropper-crop" > <span class="icon-ok"></span> </button> 
      </div>
   </div>

   <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
   <script src="js/cropper.js" ></script>
   <script>
        //initialize the cropper
        $('#cropper-img').cropper({
            checkCrossOrigin:false
        });

        $('.cropper-dragMode').on('click',function(){
            $("#cropper-img").cropper('setDragMode','move');
        });

        $('.cropper-cropMode').on('click',function(){
            $("#cropper-img").cropper('setDragMode','crop');
        });

        $('.cropper-zoomIn').on('click',function(){
            $('#cropper-img').cropper('zoom', 0.1);
        });

        $('.cropper-ZoomOut').on('click',function(){
            $('#cropper-img').cropper('zoom', -0.1);
        });

        $('.cropper-rotateRight').on('click',function(){
             $('#cropper-img').cropper('rotate', 45);
        });

        $('.cropper-rotateLeft').on('click',function(){
             $('#cropper-img').cropper('rotate', -45);
        });

        $('.cropper-refresh').on("click",function(){
            $('#cropper-img').cropper('reset');
        });

        $('.cropper-crop').on("click",function(){
            $('#cropper-img').cropper('getCroppedCanvas').toBlob(function (blob) {
              var formData = new FormData();

              formData.append('croppedImage', blob);

              $.ajax('upload.php', {
                method: "POST",
                data: formData,
                processData: false,
                contentType: false,
                success: function () {
                  console.log('Upload success');
                },
                error: function () {
                  console.log('Upload error');
                }
              });
            }); 
        });

   </script>
</body>
</html>

Bug whereby cropbox moves past container

Hey friend. Your tool is amazing. But i've found this issue - happens on both cropper and JQUERY

How to reproduce:

  • Select aspect ratio cropper / VM: 1 / setDraggable: "move"
  • Move image past the top of the container as to take a crop from the bottom
  • Using the bottom-right toggle on the cropbox pull the box out as far as you can.
  • Cropbox exceeds container

image

Get a error on chrome, how to fix it ?

Uncaught TypeError: cropper.getCroppedCanvas(...).toBlob is not a function

My code is simple, just like the example, it's function is uploading the picture:
function uploadCrop()
{

    cropper.getCroppedCanvas().toBlob(function (blob) {
    var formData = new FormData();

    formData.append('mypic', blob);

    var xhr = new XMLHttpRequest();  

Crop box text input : Bug

Hi,

The crop box doesn't seem to resize if entering dimensions manually. Might be ignoring the dimensions because of the aspect ratio.

In case of manually entering dimensions, shouldn't the manual data override the aspect ratio?

3 questions

First of all thanks for this amazing plugin and keeping it up-to-date!

  1. In some previous versions you had a demo for cropping and uploading a avatar, but in the newest release I can't find this example?
  2. So now I use the example of uploading a avatar of a previous Cropper.js release, and in this example you used the function "initIframe()" when "formData" is not supported. I assume this is only for Safari because all the other browsers such as Chrome does support "formData"?
  3. Could you create or include in the next release a new example of avatar rotating, cropping and uploading?

After calling the .replace(url), "crossOrigin" values are not updated

fixed:

  if (options.checkCrossOrigin && isCrossOriginURL(url)) {
    crossOrigin = element.crossOrigin;

    if (!crossOrigin) {
      crossOrigin = 'anonymous';
      bustCacheUrl = addTimestamp(url);
    }

    this.crossOrigin = crossOrigin;
  }else{
    this.crossOrigin = undefined; // reset crossOrigin value
  }

Image to fit container

Hello, and thank you for your great tool.
I would like to know if it's possible to scale the cropper container to fit the image's exact size. So, that means no "transparent" area on the right and left of the image.
I tried to use background: false but it didn't work as I thought it would. The "transparent" area just became gray.
Thanks!

cropper-drag-box covers buttons

Hello,
I have built an implmentation of a fixed cropper on mobile, using Cordova/phonegap.
my problem is, when I zoom in the Img, the cropper-drag-box covers the bottom buttons and I can't press them. I have tried changing the z-indexes with no success. Is there some setting that I'm not aware of that sets that element as "always on top" or something similar?
screenshot (through chrome//inspect) : http://imgur.com/2v0xlJP

canvasData option

Hi,

Can you add canvasData as an option?
I'm setting canvasData after the built event now. But you can see the old canvas flash before it updates

Thanks in advance

Remote image 'reloads' before built

Im trying to obtain cropper.getCroppedCanvas() inside the built function of my cropper instance. This works if I load a file from local drive but there's a weird issue when trying with a remote image (perhaps because its cross origin?).

When I build my new Cropper() the image will 'reload' and turn gray for a second. Inside my built function I have to use setTimeout to give the image time to reload before I can get the canvas:

cropper = new Cropper(image, {
      responsive: true,
      restore: false,
      guides: false,
      background: false,
      rotatable: false,
      movable: false,
      scalable: false,
      zoomable: false,
      zoomOnTouch: false,
      zoomOnWheel: false,
      built: function(e){
        setTimeout(function(){
          cropper.getCroppedCanvas()
        },1000);
      }
    });

If I put a breakpoint inside built I can see the image is grayed out as it seems cropper is reloading it:

screen shot 2016-05-02 at 10 12 41 pm

Using setTimeout seems like a hack that is prone to error. What should I do? I'd like to start processing the initial crop as soon as cropper initializes.

UPDATE:

  • This has nothing to do with cross origin. An image on the same host experiences the same issue.

Problem to spread out cropbox

I have a problem when I start the crop (only with default aspectRatio), cropbox becomes a line and I can't spread out it.
problem

"setCropBoxData()" not working as expected when resizing the container

Hi,

I have a container that can be resized (height only), after resizing the container I want to resize the height of the crop box to fit the container's height. The crop box is not movable and resizable. Only the canvas can be moved and scaled.
So I call the setCropBoxData() method with the new Height but It doesn't work... I also call the setCanvasData() method to update the canvas height too.

This is the options I use:

{
  viewMode: 1,
  dragMode: 'move',
  cropBoxMovable: false,
  cropBoxResizable: false,
  toggleDragModeOnDblclick: false,
  autoCropArea: 1
}

Before resizing:
beforeresize
After resizing:
afterresize
As you can see the canvas has been resized but the crop box not...

I'm noticed that the cropper's cropBoxData object has a maxHeight (equals to the initial image height) and a maxTop properties that is not updated on setCropBoxData() call. So the crop box height is never bigger than the image's initial height (in this case : 446px). When the container is smaller than 446px it works.

How can I resize the crop box so it always fit the container when it is resized ?

Thanks !

Upload > Crop > Download

Hello,

Neat plugin for the crops. Works as intended!
Trying to get an image to upload, resize / crop to 300x300px

And then I want that cropped image to be downloadable as well.
Any thoughts on how to accomplish that?

Thanks

Canvas file type

When i try to upload my image it dosn't set the file type from the canvas:

cropper.getCroppedCanvas().toBlob(function (blob) {
    var file = new File([blob], "some_random_file_name.jpg");
    console.log("file: ", file);

    Upload
        .upload({
            url: '/wp-json/add_posts/v1/add_post_image',
            file: file,
            headers: {
                'Content-Type': 'image/jpg'
            }
        })
        .progress(function (evt) {
            // Set progress
            console.log("parseInt(100.0 * evt.loaded / evt.total): ", parseInt(100.0 * evt.loaded / evt.total));
        })
        .success(function (data, status, headers, config) {
            console.log("data: ", data);
            console.log("headers: ", headers);
            console.log("config: ", config);
        });
});

This outputs:

file: {
    lastModified: 1446807554707
    lastModifiedDate: Fri Nov 06 2015 11:59:14 GMT+0100 (CET)
    name: "some_random_file_name.jpg"
    size: 4165066
    type: ""
    webkitRelativePath: ""
}

SetData (set coordinates) works not equal on Chrome and Safari(Mac)

Hello,
i use this awesome plugin for my private project. I generate automatically crop coordinates and give it to your plugin. I found out that Safari(Mac) and Chrome works not equal.

Or maybe i used the code wrong :/

Here is my code to set crop data to the plugin:
1.) I destroy the old image
3.) I set the new images based on a Base64 string
2.) I give the plugin some information
4.) I will set the coordinates

$g_image2crop.cropper("destroy");
$g_image2crop.attr("src", b64ImgData);
$g_image2crop.cropper(g_options);
$g_image2crop.cropper("setData", {
    x: parseInt(IMAGE_DATA[stringId].image.crop.x),
    y: parseInt(IMAGE_DATA[stringId].image.crop.y),
    height: parseInt(IMAGE_DATA[stringId].image.crop.h),
    width: parseInt(IMAGE_DATA[stringId].image.crop.w),
    rotate: 0,
    scaleX: 1,
    scaleY: 1
});

Can you help me to fix this?
Or is this a known issue?
Sry for my bad english ;)

Thanks a lot!

Best
Andre

unmovable cropbox moved when restoring data

Hi,

First, setup a cropper with cropbox fixed and image movable:

{
            viewMode: 0,
            dragMode: 'move',
            cropBoxMovable: false,
            cropBoxResizable: false,
}

2016-03-08 16 45 33

Then, crop the top-right corner and save the data
2016-03-08 16 45 45

And finally, rebuild cropper and restore the data, we got
2016-03-08 16 42 08

The cropbox move to top-right corner! (which is expected to stay center!) In the worst situation, the cropbox may be entirely outside the container.

getCroppedCanvas + Google Nexus 6 issue

Hi,

A great plugin for cropping, thanks for that. But the issue I am facing is that I am unable to get the cropped image on Nexus 6 device (android 5.0 - google chrome browser). Modal appears with a white background without the cropped image. A quick help is needed.

Thank you,
Nijagun.

Public resize

Hi,

Can you make the _resize function public?
I'm using the private _resize for now but it would feel better if it was public instead :)

The reason I need this is because the crop box position and size changes dynamically when the user selects different "models".

Thanks in advance
Peter

Set cropbox size and scale the image to match in viewmode 1

Great tool, but i ran into this issue,

Im trying to set minCropBoxWidth on viewmode 1 but it returns a smaller cropbox, actually i would love to be able to se a cropbox size and scale the image to that size

vm.cropper = new Cropper(image, {
    viewMode: 1,
    dragMode: 'move',
    aspectRatio: 1,
    autoCropArea: 1,
    minCropBoxWidth: 578,
    minCropBoxHeight: 578,
    center: true,
    highlight: false
});

Zoom on Mac with Magicmouse is too fast

When you swipe up or down on a magicmouse the zoom in/out is far too fast to allow any form of precision.

(This used to be a similar problem on Google Maps, they eventually programmed around it - perhaps you can find the answer in their code)

Need GIF Animation Save

Heya! Great plugin! It works great for my application, but just one thing that I ran into. I would love to crop an animated gif. I've kept the gif format in my .toDataURL call but it still just saves it as a one frame gif. Let me know if this library supports it, and if not, if and when it could. Thank you!

Scale is not reflected when zooming in/out

Version: Cropper v2.3.0
OS: Mac OS 10.11.13
Browser: Chrome 49.0.2623.110 (64-bit)

When I zoom in and out on images using the scroll wheel/trackpad, the image scales, but the change isn't reflected in the scaleX and scaleY properties returned by the cropper's getData.

Here's how I'm implementing the library:

Cropper initialization

$imageBox.children('img').eq(i).wrap('div'); 
$imageBox.children('.crop-image-holder').eq(i).find('img').cropper({
                        checkCrossOrigin: false,
                        data:{ //set up focal point of crop
                            x: (x * $imageBox.children('.crop-image-holder').eq(i).width()) - (cw/2),
                            y: (y * $imageBox.children('.crop-image-holder').eq(i).height()) - (ch/2),
                            width: cw, //predetermined crop width
                            height: ch},//predetermined crop height
                        crop: function(e){
                        },
                        built: function(){
                            croppers.splice(i, 0, $(this)); //add to croppers array
                        }
                    });

I have an array of croppers called croppers. When I want to get the data from one of them, I call the following function:

/*
 * returns all the active crops on the screen
 */
var activeCrops = function () {
    var crops = [];
    for ( var i = 0; i < croppers.length; i++){
        crops.push(croppers[i].cropper('getData'));
        }
    return crops;
};

Result of activeCrops()[0]:

{
   "height": 294.53039077737657,
   "rotate":0,
   "scaleX":1,
   "scaleY":1,
   "width":442.1703067650182,
   "x":583.4753387898007,
   "y":162.59414612484034
}

ScaleX and ScaleY stay at 1, no matter how much I zoom the image.

Rotation on iOS 8

Hi,

I'm using this lib to rotate pictures, and it seems that vendor prefixes for the CSS transform property are needed on Safari (iOs 8) to be able to preview the rotation correctly. This is also written on the Can I Use page linked in the README (http://caniuse.com/#feat=transforms2d).

Would it be possible to add the -webkit- and the -ms- to support Safari iOs 8 and IE 9 ?

I can make a PR if needed.

Thanks :)

Removal of 'strict' on v0.3.0

Not sure why this function was removed? It was something I'm using in order to prevent "dead space" from being saved against a print product crop. Is there a replacement, or was it error-prone?

I have to revert to 0.2.1 for the time being.

P.s. I love your work with this plugin, it has really been great!

return final cropped image as blob

got some issues with below function
$('#profile_image').cropper('getCroppedCanvas').toBlob(function (blob) {
console.log(blob);
});
console print something like below.
Blob {size: 71238, type: "image/png"}
size
71238
type
"image/png"
That's all. not returing the image and cannot upload the cropped image

Unable to select the cropped area

Hi !

I am using cropper js and I'm experiencing a little issue.
When I leave aspectRatio set to free, I can't select (via the mouse) the cropper area (click & drag).

here are my options :

new Cropper(cropimage, {
        preview: '.preview',
        viewMode: 1,
        guides: false,
        center: false,
        highlight: false
    });

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.