antd4.0 的话,社区里是有相关的 Upload 裁剪插件可以使用的,如果是 antd3.0 则优先考虑用 cropperjs
一、安装
npm install cropperjs
二、引入
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
三、使用
constructor(props) {
this.image = React.createRef();
}
beforeUpload = async (file) => {
const { needCrop } = this.props;
...
if (needCrop) {
const url = URL.createObjectURL(file);
this.setState({ url, cropModalVisible: true });
return false;
}
return true;
};
createCropper = () => {
this.cropper = new Cropper(this.image.current, {
dragMode: "move", //设置拖拽模式
toggleDragModeOnDblclick: false, // 当点击两次时可以在“crop”和“move”之间切换拖拽模式
viewMode: 1, // 只能在裁剪的图片范围内移动
dragMode: 'move', // 画布和图片都可以移动
aspectRatio: 1, // 裁剪区默认正方形
autoCropArea: 1, // 自动调整裁剪图片
cropBoxMovable: false, // 禁止裁剪区移动
cropBoxResizable: false, // 禁止裁剪区缩放
background: false // 关闭默认背景
});
};
crop = () => {
if (this.cropper) {
const { fileList, fileDate } = this.state;
const cropped = this.cropper.getCroppedCanvas();
cropped.toBlob(async blob => {
const file = new File([blob], fileDate.name, {
type: fileDate.type,
uid: fileDate.uid,
});
requestUploadFile({ file })
.then((response) => {
const { code, data, message: mess } = response;
if (code === 0) {
const list = fileList.slice();
list.push({
uid: data.fileId,
name: data.fileId,
status: "done",
response: { code, data },
thumbUrl: URL.createObjectURL(blob),
});
this.setState({ cropModalVisible: false });
this.onChange({ fileList: list });
} else {
throw new Error(mess);
}
})
.catch((err) => {
message.error(err.message);
});
}, "image/png");
}
};
<div>
<Upload {...uploadProps}>{children}</Upload>
<Modal
title="图片裁剪"
visible={cropModalVisible}
onOk={this.crop}
onCancel={this.cancelCrop}
destroyOnClose
maskClosable={false}
centered
className={Style["crop-img-modal"]}
>
<div>
<img style={{ maxWidth: "60%" }} src={url} onLoad={this.createCropper} ref= {this.image} alt="图片" />
</div>
</Modal>
</div>
设置裁剪区域是个圆形
.crop-img-modal {
:global {
.cropper-view-box,
.cropper-face {
border-radius: 50%;
}
}
}
四、注意点
开发的过程发现裁剪后的图片背景会变成黑色,这是因为通过toDataUrl方式转图片时,在格式为jpg的情况下,原先的透明度属性会丢失,可以通过统一设置图片转换格式为png格式来解决的。
cropperjs 其他api的使用可在官网上查找