Giter VIP home page Giter VIP logo

react-cropper's Introduction

react-cropper

Cropperjs as React component

NPM NPM NPM downloads Bundle Size minZip Bundle Size min License codecov

Demo

Click for a Demo

Docs

Installation

Install via npm

npm install --save react-cropper

You need cropper.css in your project which is from cropperjs. Since this project have dependency on cropperjs, it located in /node_modules/react-cropper/node_modules/cropperjs/dist/cropper.css or node_modules/cropperjs/dist/cropper.css for npm version 3.0.0 later

Quick Example

import React, { useRef } from "react";
import Cropper, { ReactCropperElement } from "react-cropper";
import "cropperjs/dist/cropper.css";

const Demo: React.FC = () => {
  const cropperRef = useRef<ReactCropperElement>(null);
  const onCrop = () => {
    const cropper = cropperRef.current?.cropper;
    console.log(cropper.getCroppedCanvas().toDataURL());
  };

  return (
    <Cropper
      src="https://raw.githubusercontent.com/roadmanfong/react-cropper/master/example/img/child.jpg"
      style={{ height: 400, width: "100%" }}
      // Cropper.js options
      initialAspectRatio={16 / 9}
      guides={false}
      crop={onCrop}
      ref={cropperRef}
    />
  );
};

Options

src

  • Type: string
  • Default: null
<Cropper src="http://fengyuanchen.github.io/cropper/images/picture.jpg" />

alt

  • Type: string
  • Default: picture

crossOrigin

  • Type: string
  • Default: null

dragMode

https://github.com/fengyuanchen/cropperjs#dragmode

scaleX

https://github.com/fengyuanchen/cropperjs#scalexscalex

scaleY

https://github.com/fengyuanchen/cropperjs#scalexscaley

enable

https://github.com/fengyuanchen/cropperjs#enable

disable

https://github.com/fengyuanchen/cropperjs#disable

zoomTo

https://github.com/fengyuanchen/cropperjs#zoomto

rotateTo

https://github.com/fengyuanchen/cropperjs#rotateto

Other options

Accept all options in the docs as properties.

Methods

Use the cropper instance from onInitialized to access cropperjs methods

Build

npm run build

Development

npm start

Author

Fong Kuanghuei

Maintainer

Shubhendu Shekhar

License

MIT

react-cropper's People

Contributors

alexdong avatar amitava82 avatar awylie199 avatar bardt avatar belief-cyf avatar bohdan-romanchenko avatar circlingthesun avatar dantman avatar dependabot-preview[bot] avatar dependabot[bot] avatar dougshamoo avatar gaboesquivel avatar gfx avatar iamtchelo avatar jtag05 avatar jyash97 avatar lgtm-com[bot] avatar meanphil avatar moaxaca avatar mokto avatar oknoah avatar rizvanua avatar roadmanfong avatar shekhar-shubhendu avatar silentsakky avatar vladislao 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

react-cropper's Issues

Rotate

Thanks for the awesome plugin. Are there options to rotate the image?

Cheers

Problem with initial cropper width calculation when display: none applied

I try to implement simple cropper slider. In my app I can upload some image files and these are mapped into cropper components. Only one component is displayed at a time, I can use arrows to display next one etc.

All of the components are present in the DOM, I just hide components with display: none property.
On the bottom, preview images are displayed.

the render function looks like this:

_renderCroppers () {
    return this.state.files.map( (file, index) => {
      return (
        <Cropper ref={this._bindRef}
                 key={`cropper-${index}`}
                 className={cn({'hide' : this.state.currentCropper !== index})}
                 preview={`.grid-item-${index}`}
                 responsive={true}
                 src={file.preview}
                 viewMode={3}
                 aspectRatio={16/9}
        />
        );
    });
  }

Now, the problem is that when the Cropper component is initialized with display: none and then i get rid of this property(i.e by clicking next arrow) its size is different(width: 200px) from component that was initialized without display: none applied on it(has width 100%).

1. After uploading 2 images - first cropper is displayed correctly.
screenshot from 2017-03-21 01-34-54

2. After pressing next arrow (changing currentCropper state) the size is different:
screenshot from 2017-03-21 01-35-18

When there is no display none applied, all of the croppers are rendered with proper width (100%), so how does cropper calculate its width initially?

Does anyone has a clue why it behaves like this?

Crop SVGs

Hello,

I've been using react-cropper for a while now (awesome by the way), mainly with PNGs, but I was wondering if it were possible to use it with SVGs? Because when I use this.ref.getCroppedCanvas(), I seem to get a PNG.

Thanks in advance!

Require css crashes Meteor

Latest Meteor lets you use npm but

require('cropperjs/dist/cropper.css')

in react-cropper.js crashes it. I can comment it out and its working fine.

Is it intended? I didn't know you can require css with nodejs.

Unexpected token

Including 'react-cropper' causes an unexpected token error, I'm using ES6 so:
import Cropper from 'react-cropper'; is the offending code.

Can't zoom the image on mobile device.

In my mobile chrome. if I try to zoom the image itself, (not the crop box). The picture will be lost。

But cropperjs's demo is ok.

after zoom image use fingers:

2017-03-23_162023

Regards.

Please remove "react" etc as npm dependencies

Can you please remove "react" and "react-dom" from the "dependencies" section of package.json?

(but leave them in peerDependencies and devDependencies)

Our app breaks due to there being two versions of react.
Thanks!

Remove jquery dependency

reactjs should provide all the events and you can easily point to elements with refs.

We shouldn't need to add jquery to bloat up the library

Cannot get image data

I have a cropper component inside of a fixed-width div. I'd like to make sure that the height of the cropper container matches the height of the image.

I thought I could do this by grabbing the image data after the component mounts, calculating the aspect ratio from the natural dimensions, and then calculating the appropriate height to match the actual width of the image.

class Cropper extends Component {
  constructor (props) {
    super(props)
    this.state = {}
  }

  componentDidMount () {
    const imageData = this.refs.cropper.getImageData()

    const aspectRatio = imageData.naturalWidth / imageData.naturalHeight
    const containerHeight = imageData.width / aspectRatio

    this.setState({ containerHeight })
  }

  getCropperStyles () {
    const styles = { width: '100%' }

    if (this.state.containerHeight) {
      styles.height = this.state.containerHeight
    }

    return styles
  }

  render () {
    return <ReactCropper ref='cropper' src={this.props.src} styles={this.getCropperStyles()} />
  }
}

But when I do this, this.refs.cropper.getImageData() doesn't seem to return what I'm expecting. I think this has to do with the fact that the image has not actually loaded even when componentDidMount is called. Is there a callback I can pass in as a prop to update my component's state when the image loads?

base64 to jpeg

Is there a way to decode the base64 cropper image into a jpeg file?

Low Framerate

Hi,

First of all, congratulations on porting it over, it looks good!

The only thing I've noticed at the moment is that the framerate seems significantly lower than the original plugin. Is there a reason for this?

Breaks on Safari

Hi, I'm getting an error when trying to crop on Safari :

TypeError: this.refs.debAddBillCropper.getCroppedCanvas({fillColor:"#FFFFFF"}).toBlob is not a function. (In 'this.refs.debAddBillCropper.getCroppedCanvas({fillColor:"#FFFFFF"}).toBlob(function(t){var n=new FormData;n.append("bill",t),(0,c.addBill)(n,e)})', 'this.refs.debAddBillCropper.getCroppedCanvas({fillColor:"#FFFFFF"}).toBlob' is undefined)

It works totally fine on Chrome & Firefox, but breaks on Safari.

Any ideas why?

Cannot find SourceMap 'cropper.js.map'

When I am using wabpack with typescript, there is a warning:

WARNING in .//react-cropper//cropperjs/dist/cropper.js
Cannot find SourceMap 'cropper.js.map': Error: Cannot resolve 'file' or 'directory' ./cropper.js.map in C:\Users\liliu\Desktop\Demo\webapp\node_modules\react-cropper\node_modules\cropperjs\dist

Crop zone exceeds natural image size

The image returned by cropper is much larger than the original image.

It seems that fengyuanchen cropper had this issue, but it is fixed now. See issue:
fengyuanchen/cropper#34

Can you confirm witch version of fengyuanchen is used by react-cropper?

Also I still have this problem, so when uploading a 300kb file it become 1.9Mb after cropping; the difference is huge.

x,y coordinates of the crop

hi,
is it possible to get the (x,y) coordinates and the width and length of the cropped image related to the original image?

Drag and Drop from Google images or other window tab

Hi,

It is possible to drag and drop an image from another window tab? When I do that it detects something but it's empty.

<DropzoneUpload getFile={this.getFileDragged} />

getFileDragged: function(item) {
    if (item.length > 0) {
        this.setState({
            files: item
        });
    }
},

Thank you!

throw Error is not good idea

"Throw error" breaks render of another component. In this case you just notify programmer , i think we should use console.error , cause its more safely

Negative scale selection

It's currently possible to drag left-top corner to the bottom and right of bottom-right corner. Found in demo that is linked on title page.

CORS policy

Backend: AdonisJs
Proxy: Express-http-proxy
Frontend: React-redux

Scenario:
Right after I successfully uploaded the image, and trying to load the src to the cropper.

Error:

Access to Image at 'http://localhost:3333/images/profiles/ID1_20170206-145755.jpg?timestamp=1486364893261' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

Use with browserify

Hello there,

Is there a way to use this component with Browserify ? I use reactify to compile all my jsx files into one js file, but on compilation, I get an error because of the require('cropper/dist/cropper.css'); line.
The exact error is:
.cropper-container {
^
ParseError: Unexpected token

Thanks for your help

window is not defined

After install react-cropper just starting my dev server gives me

/node_modules/react-cropper/node_modules/cropper/dist/cropper.js:27
  var $window = $(window);

ReferenceError: window is not defined

Passing some props which are not resulting in visible change

I'm trying to animate a canvas to be a certain size, as well as the cropbox, by using the props canvasData and cropBoxData. But when I load the page and finally get the image into the cropper (after it's uploaded to a server), neither of values I put in these two props are having any effect. Also I am passing dragMode, which does not appear to do anything -- at least on a Macbook Pro.

There are other props that do work such as the aspect ratio, and disabling zooming.

The source for the cropper is set to a property of the state which is not always populated.

Wrapped in a div in the render function is my cropper component:

        <Cropper
          ref="cropper"
          dragMode="none"
          src={this.state.file.preview}
          style={this.cropperStyles}
          aspectRatio={16 / 5}
          cropBoxData={{left:0, top:0, width:50, height:50}}
          canvasData={{left:0, top:0, width: 500, height: 300 }}
          crop={this._crop.bind(this)}>
        </Cropper>

Here are the functions that alter the data in the cropper. When I call _setCanvasData, then those functions work. But not when passed as props.

  onFinishS3Put = (public_url, file) => {

    this.setState({
      file: file
    });

  }

  _setCanvasData = () =>{

    this.refs.cropper.setCropBoxData({top:0, left:0, width:50, height: 50});
    this.refs.cropper.setCanvasData({top: 0, left: 0, width: 500 , height: 300 });
    this.cropper.scale(1,-1);

  }

upgrade to newer version

sorry for this inconvenience!
I want to use this react-cropper with newer version of cropper, currently, cropper version is 0.11.1
But I dont know how to upgrade and rebuild it!
thanks for your help!

Problem getting the example to work with a local image file

I'm having a problem getting the example to work with a local image file.

When I run the hosted example at http://roadmanfong.github.io/react-cropper/example/ everything works fine, even when choosing a local jpg file. But when I try to use react-cropper in my own app and choose a local jpg, or run the example from the repo and choose a local jpg, I get the following error:

Uncaught TypeError: this.refs.cropper.getCroppedCanvas(...).toDataURL is not a function

Its fine with the default image

In order to debug I changed the the _crop function as follows

  _crop(){
    var imageCropper = this.refs.cropper.getCroppedCanvas()  
    this.setState({
      preview: imageCropper.toDataURL()
    });
  }

When using the default image, imageCropper is a canvas type. When I select a local .jpg file the imageCropper object becomes a jquery object and the error occurs.

Any idea what's wrong?

Canvas to Blob -> toBlob is not a function

Hey guys, this plugin is amazing though i am having problems with getting the base64 output to my server via ajax call. If i just try to send the getCroppedCanvas.toDataUrl() my browser almost crashes due to the huge base64 string so i am looking at the toBlob method from the jquery cropper.

I was trying to approach it like this:
this.refs.cropper.getCroppedCanvas().toBlob() ...
I get toBlob is not a function; from researching this happens because the whole canvas is not rendered yet so i would have to wrap it inside a "built" function which i don't know how to do in this example.

Can anybody help me with a working example on how to post the cropped image via ajax? Any form is fine.

Regards, Jasa

cropBoxData issue

Hi, I am experiencing a problem with cropBoxData.

<ReactCropper cropBoxData={cropData} src={backgroundImage} style={styles.cropping} guides={false} ref={(c) => { this.cropper = c; }} />

In my code cropData is object example {left: 72, top: 88, width: 576, height: 324}

No warnings or errors, just doesn't work.

Unused property warning in React 15.2.0

With React 15.2.0, any unrecognized props assigned to DOM elements will throw a warning. In the case of this library, the following warning occurs:

Warning: 
Unknown props `aspectRatio`, `guides`, `zoomable`, `crop`, `build`, `built`, `dragMode`, `scaleX`, `scaleY`, `enable`, `zoomTo`, `rotateTo` on <div> tag. 
Remove these props from the element.
For details, see https://fb.me/react-unknown-prop
    in div (created by ReactCropper)

Let cropper height vary by image height

In my original non-react code. I let my cropper height vary by the height of the image instead of fixing it at one size.

However the display: none; stops cropper from inheriting the height of the image and it simply shrinks to the minimum size.

I don't want to just drop the display: none; from react-cropper and change things for everyone else. But I would like to find a way to make react-cropper or cropper explicitly opt-in to this behaviour.

React.createElement: type should not be null, undefined, boolean, or number.

When I upgraded to the 0.6.2 version of react-cropper. I kept getting the following error when React was trying to render it to the page.

warning.js:45Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components).

So I create a brand new project and used your example from the readme

var Cropper = require('react-cropper');
var Demo = React.createClass({
  _crop: function(){
    // image in dataUrl
    console.log(this.refs.cropper.getCroppedCanvas().toDataURL());
  },

  render: function() {
    return (
      <Cropper
        ref='cropper'
        src='http://fengyuanchen.github.io/cropper/img/picture.jpg'
        style={{height: 400, width: '100%'}}
        // Cropper.js options
        aspectRatio={16 / 9}
        guides={false}
        crop={this._crop} />
    );
  }
});

I still experienced the same issue. Changing the line
var Cropper = require('react-cropper'); to var Cropper = require('react-cropper').default;
cleared the problem.

It may be worth adding a note to the readme in case others experience the same problem.

Thanks for your work on react-cropper.

Upgrade to Cropper 2

Hi, do you have any plans to upgrade this component to use the latest Cropper library? If so, when do you think you will release it? If not, any tips on doing it myself and submitting a pull request?

there are a lot of react warnings

here are one of them.
warning.js?7533:36 Warning: You are manually calling a React.PropTypes validation function for the zoomOnTouch prop on ReactCropper. This is deprecated and will not work in the next major version. You may be seeing this warning due to a third-party PropTypes library. See https://fb.me/react-warning-dont-call-proptypes for details.

please fix this issue. thank you

Package initialization issues

Utilities.js is assuming a number of global properties are available at import time, rather than at initialization time which is inhibiting me from using this package all together. It operates making the assumption that window is already existing -- which if rendered by the server it does not exist. Could you import window into the module?

`crop` shouldn't be considered as unchangeable

It would be ideal if crop wasn't considered unchangeable as it makes it impossible to pass arguments with the callback.

In the following example, I have multiple croppers in a loop, and need to pass the item or index in with the callback crop. But this counts as a different function each time.

Handling it refs alone become messy with a series of items.

<div>
    { map(items, item => (
        <Cropper
            className="Uploader__cropper"
            src={item.original}
            style={{height: 400, width: '100%'}}
            aspectRatio={16 / 9}
            checkCrossOrigin={false}
            background={false}
            guides={true}
            crop={(e) => this.onCrop(e, item)} />
        />
    ))}
</div>

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.