There are screenshot plug-ins in react, such as the react screenshot component "react-cropper", which can realize the image cropping function. The method of use is: first install "react-cropper"; then obtain it through getCroppedCanvas and other methods Cropped pictures are enough.
The operating environment of this tutorial: windows7 system, react17.0.1 version, Dell G3 computer.
Related recommendations: "react tutorial"
How to use the react screenshot component react-cropper
When using React During development, we often encounter the situation of uploading images. If we want the uploaded images to meet certain specifications, we must crop the uploaded images on the client. At this time, we can use react-cropper. This image cropping component can help us easily implement the image cropping function.
The usage steps are as follows:
1. Installation:
npm install --save-dev react-cropper
2. The usage method is as follows:
import React from 'react' import Cropper from 'react-cropper' import 'cropperjs/dist/cropper.css' import {Button} from 'antd' export default class Crop extends React.Component { constructor() { super(); this.cropImage = this.cropImage.bind(this); } cropImage() { if (this.cropper.getCroppedCanvas() === 'null') { return false } this.props.getCropData(this.cropper.getCroppedCanvas().toDataURL()) } render() { return ( <div> <div style={{width: '100%'}}> <Cropper src={this.props.src} ref={cropper => { this.cropper = cropper; }} style={{height: 400, width: '100%'}} aspectRatio={246/346} guides={false} /> </div> <div> <Button type="primary" size="large" onClick={this.cropImage} style={{marginTop: '10px'}}> 确认裁剪 </Button> </div> </div> ); } } import Cropper from 'react-cropper' import 'cropperjs/dist/cropper.css'
These two sentences introduce the Cropper component and its Style, Cropper component also has some commonly used attributes:
src: src is the src of the image to be cropped, usually the Base64 encoding of the image read by the upper component
aspectRatio: This is Control the proportion of the cropped image
There is also a button at the bottom of the cropping box to confirm whether to crop. From the above we can see its bound events:
cropImage() { if (this.cropper.getCroppedCanvas() === 'null') { return false } this.props.getCropData(this.cropper.getCroppedCanvas().toDataURL()) }
this.cropper allows us to use The ref attribute of react saves the reference of the DOM node of the Cropper component. If you are not sure, you can check the official React documentation. This component provides a getCroppedCanvas() method. This method returns the cropped image. We can use
The toDataURL() method converts it into Base64 encoding and uploads it to the upper-level component.
The above is the detailed content of Is there a screenshot plug-in implemented in react?. For more information, please follow other related articles on the PHP Chinese website!