3

I'm using the latest cropper.js react package react-cropper in my current project and I'am just lost. The problem is, that the crop area can go outside of the image, which should not. I have tried everything I can think of.

Here is the _crop method which is called on every change in cropper.

componentDidMount = () => {
    sessionStorage.setItem('shouldMove', false)
  }

_crop = ( e ) => {
    var canvasData = document.getElementsByClassName('cropper-hidden') 
    [0].cropper.canvasData
    var cropBoxData = this.refs.cropper.getCropBoxData();

    if ( sessionStorage.getItem('shouldMove') === 'false' ) {
      sessionStorage.setItem( 'currentLeft', cropBoxData.left )
      sessionStorage.setItem( 'currentTop', cropBoxData.top )
      sessionStorage.setItem('shouldMove', true)
    }else {
      if (
        cropBoxData.left <= canvasData.left ||
        cropBoxData.top  <= canvasData.top  ||
        cropBoxData.left + cropBoxData.width > canvasData.width + 
        canvasData.left ||
        cropBoxData.top + cropBoxData.height > canvasData.height + 
        canvasData.top
      ) {
        cropBoxData.left = sessionStorage.getItem( 'currentLeft' )
        cropBoxData.top = sessionStorage.getItem( 'currentTop' )
      }
    }}

//render

    <Cropper
      ref='cropper'
      src={URL.createObjectURL(this.props.image)}
      aspectRatio={this.props.template.aspect_ratio}
      guides={true}
      zoomTo={ this.state.zoomValue }
      dragMode="move"
      crop={this._crop}
    />

I know it's a sessionStorage nightmare, but I can't use state because it would reset whole cropper. I'm also getting the canvasData from the image tag, because the cropper.canvasData() function is not working in this react package.

In my code above, react is able to detect that crop area is outside of the image, but I don't know what I should do there. I tried to set the position of the crop area to the first position where it's outside of the image. But the data is not changing.

halfer
  • 19,824
  • 17
  • 99
  • 186
Jan Jiráň
  • 349
  • 5
  • 14
  • Please read [Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers?](//meta.stackoverflow.com/q/326569) - the summary is that this is not an ideal way to address volunteers, and is probably counterproductive to obtaining answers. Please refrain from adding this to your questions. – halfer Nov 16 '18 at 22:10

1 Answers1

8

Wow. ok, if anybody will struggle with the same issue, the answer is pretty simple but I really couldn't find it anywhere. Just set the viewMode to "2" like so:

<Cropper
      ref='cropper'
      src={this.props.image}
      aspectRatio={ar}
      guides={true}
      zoomTo={ this.state.zoomValue }
      dragMode="move"
      crop={this._crop}
      viewMode = {2} <-----
    />

and it will work.

Jan Jiráň
  • 349
  • 5
  • 14