如何使用 react-easy-crop 来反映从 react-easy-crop 到另一个 div 中渲染的实时图像的位置变化?

IT技术 javascript html css reactjs
2021-05-04 01:43:28

选择图像后,我在两个地方渲染它,一个在 react-easy-crop(4:3 纵横比)中,另一个在单独的 div(960w*510h)中。所以当我在 react- 中更改裁剪位置时 - easy-crop.my 另一个 div 也应该移动它的位置。从 react-easy-crop 监听 onchangecrop 事件

onCropChange = (crop) => {
    //crop has x and y of translated value in px
    pageObj = `${crop.x * -1}% ${crop.y * -1}%`.toLowerCase();
    //pageObj will have x and y position in percentage.
}
1个回答

如果我理解正确,您想显示预览图像。如果是这样,您可以使用 acanvas来处理原始图像并对其进行剪切和重新定位。

import React, { Component } from 'react';
import { render } from 'react-dom';
import Cropper from 'react-easy-crop'

export class App extends Component {
  canvas = {}

  state = {
    image: 'https://www.gravatar.com/avatar/3d721f4c46282afc254f3ea0cd05df30?s=170&d=identicon&r=PG',
    crop: { x: 0, y: 0 },
    zoom: 1,
    aspect: 4 / 3,
    croppedAreaPixels: {}
  }

  onCropChange = crop => {
    this.setState({ crop })
  }

  onCropComplete = (croppedArea, croppedAreaPixels) => {
    console.log(croppedArea, croppedAreaPixels);
    const ctx = this.canvas.getContext('2d');
    const image = document.getElementById('source');

    this.canvas.setAttribute('width', croppedAreaPixels.width);
    this.canvas.setAttribute('height', croppedAreaPixels.height);
    ctx.drawImage(image, croppedAreaPixels.x, croppedAreaPixels.y, croppedAreaPixels.width, croppedAreaPixels.height, 0, 0, croppedAreaPixels.width, croppedAreaPixels.height);
    this.setState({
      croppedAreaPixels 
    })
  }

  onZoomChange = zoom => {
    this.setState({ zoom })
  }

  render() {
    const { image, croppedAreaPixels, crop, zoom, aspect } = this.state;
    return (
      <>
        <img id="source" style={{display: 'none'}} src={image} />
        <canvas ref={canvas => this.canvas = canvas} width={croppedAreaPixels.width} height={croppedAreaPixels.height}></canvas>
        <Cropper
          image={image}
          crop={crop}
          zoom={zoom}
          aspect={aspect}
          onCropChange={this.onCropChange}
          onCropComplete={this.onCropComplete}
          onZoomChange={this.onZoomChange}
        />
      </>
    )
  }
}

render(<App />, document.getElementById('root'));

和工作演示:

https://stackblitz.com/edit/react-easy-crop-with-preview

并使用background-position方法,而不是canvas.

https://stackblitz.com/edit/react-easy-crop-with-preview-with-bg-position