react-cropper结合Antd|react-cropper结合Antd Upload实现图片裁剪并上传
cropper文档
cropperjs
react-cropper
cropperjs翻译文档:cropper.js 裁剪图片并上传(文档翻译+demo)
install
yarn add react-cropper
import Cropper from 'react-cropper'
import 'cropperjs/dist/cropper.css'
主要配置说明 viewMode 配置视图模式
https://github.com/fengyuanch...
- 0:无限制
- 1:限制裁剪框不能超出图片的范围
- 2:限制裁剪框不能超出图片的范围,且图片填充模式为最长边填充
- 3:限制裁剪框不能超出图片的范围,且图片填充模式为最短边填充
https://github.com/fengyuanch...
- crop:拖拽形成新的裁剪框
- move:拖拽只能移动图片
- none:不做处理
https://github.com/react-crop...
onInitialized={(instance) => {cropper.current = instance}}
zoom 缩放事件
【react-cropper结合Antd|react-cropper结合Antd Upload实现图片裁剪并上传】https://github.com/fengyuanch...
在
zoom
监听事件中限制最大最小缩放比例:const zoom = (e) => {
const { ratio, oldRatio } = e.detail
// zoom in
if (ratio > oldRatio) {
if (ratio > maxRatio) {
e.preventDefault()
cropper.current.zoomTo(maxRatio)
}
// zoom out
} else if (ratio < oldRatio) {
if (ratio < minRatio) {
e.preventDefault()
cropper.current.zoomTo(minRatio)
}
}
}
getCanvasData 获取裁剪的图片数据
https://github.com/fengyuanch...
toBlob
toBlob
第二个参数默认是image/png
。const getCroppedData = https://www.it610.com/article/() => {
return new Promise((resolve, reject) => {
try {
cropper.current.getCroppedCanvas({
// ...
imageSmoothingQuality: 'high',
}).toBlob((blob) => {
resolve(blob)
}, 'image/jpeg')
} catch (e) {
reject()
}
})
}
toDataURL
cropper.current.getCroppedCanvas().toDataURL('image/jpeg')
实践
结合Antd Upload裁剪并上传图片
beforeUpload
返回Promise
。在beforeUpload
方法中,将得到的图片文件转成DataURL传给裁剪组件。设置定时器,每隔一段时间查询裁剪是否完成,若裁剪完成则resolve(croppedFile)
。const beforeUpload = (file) => {
return new Promise((resolve, reject) => {
imageBlob.current = null let reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = (e) => {
setCropImage(e.target.result)
}// 定时器
timer.current = window.setInterval(() => {
// 裁剪完成
if (imageBlob.current) {
window.clearInterval(timer.current)
// blob转file
const croppedFile = new File([avatarBlob.current], file.name, {
type: 'image/jpeg',
uid: file.uid,
lastModified: Date.now(),
})
resolve(croppedFile)
}
}, 100)
})
}
Demo
https://stackblitz.com/edit/r...
推荐阅读
- 基于|基于 antd 风格的 element-table + pagination 的二次封装
- 【38】“劳逸结合”的重要性
- springboot结合redis实现搜索栏热搜功能及文字过滤
- 产融结合—黄生
- 囚徒健身与传统中医健身结合
- RxJava结合Retrofit使用
- React|React antd 学习随笔
- nlp|Keras(十一)梯度带(GradientTape)的基本使用方法,与tf.keras结合使用
- 浅谈产品思维
- 16.vue中Js动画与Velocity.js库结合