本文主要实现,h5通过input上传图片后,利用cropperjs进行裁剪,获取指定尺寸
1 安装cropperjs
npm install cropperjs
2 具体实现
home.jsx
代码中的result模块用来展示最终的裁剪结果;mask用作页面最上层蒙层,用来裁剪上传的图片
import React, { memo, useEffect, useState, useRef } from 'react'
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import cn from './home.module.scss'
let myCropper = null // 创建cropper全局对象
function Home() {
const [uploadImg, setUploadImg] = useState('') // 上传图像的地址
const [cropperImg, setCropperImg] = useState('') // 裁剪后的图像地址
const imgRef = useRef()
const initCrop = () => { // 初始化
myCropper = new Cropper(imgRef.current, {
viewMode: 1, // 视图控制
dragMode: 'none', // 拖拽图片模式
aspectRatio: 1, // 裁剪框为固定的宽高比
autoCropArea: 0.6, // 设置裁剪区域占图片的大小 值为 0-1 默认 0.8 表示 80%的区域
zoomOnWheel: false, // 是否可以通过鼠标滚轮缩放图片 默认true
})
}
const cancel = () => { // 销毁
myCropper.destroy() // 销毁cropper
myCropper = null
}
const handleCrop = async () => { // 裁剪
setUploadImg('')
myCropper.getCroppedCanvas({
imageSmoothingQuality: 'high'
}).toBlob(async (blob) => {
// 设置个文件名,不然文件名就是默认的“blob”
const file = new File([blob], 'result.png')
const img = window.URL.createObjectURL(file)
setCropperImg(img)
cancel()
})
}
const handleUpload = async (e) => { // 上传
const file = e.target.files[0]
const img = window.URL.createObjectURL(file) // 上传图片的blob地址
setUploadImg(img)
setTimeout(() => {
initCrop() // 开始裁剪
}, 0)
}
return <div className={cn.main}>
<input
className={cn.item_input}
type={'file'}
accept={'image/*'}
onChange={handleUpload}
/>
<div className={cn.result}>
{
cropperImg && <img src={cropperImg} alt='' className={cn.result_cropper} />
}
</div>
{
uploadImg && <div className={cn.mask}>
<div className={cn.mask_btn} onClick={handleCrop}>裁剪</div>
<img ref={imgRef} className={cn.mask_cropper} src={uploadImg} alt='' />
</div>
}
</div>
}
home.module.scss
.input {
margin: auto;
height: 50px;
}
.result {
position: relative;
margin: auto;
height: 300px;
width: 100%;
&_cropper {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
max-width: 100%;
max-height: 100%;
object-fit: contain;
}
}
.mask {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.7);
&_btn {
position: absolute;
z-index: 10;
right: 0;
top: 0;
width: 100px;
height: 100px;
font-size: 28px;
font-weight: 450;
line-height: 100px;
color: #FFFFFF;
}
&_cropper {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
max-width: 100%;
max-height: 100%;
object-fit: contain;
}
}