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.

4

1 回答 1

8

哇。好的,如果有人会遇到同样的问题,答案很简单,但我真的无法在任何地方找到它。只需将 viewMode 设置为“2”,如下所示:

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

它会起作用。

于 2018-11-16T22:32:04.867 回答