If you're looking to showcase a preview image, consider utilizing a canvas
element for editing the original image by cropping and repositioning it.
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'));
For a demonstration of this in action, check out this link:
https://stackblitz.com/edit/react-easy-crop-with-preview
Alternatively, explore the use of background-position
as another method instead of relying solely on the canvas
.
https://stackblitz.com/edit/react-easy-crop-with-preview-with-bg-position