福永做网站的公司,专业建站网网站运营推广,本网站正在建设中,西安做网站科技有限公司本文主要实现#xff0c;h5通过input上传图片后#xff0c;利用cropperjs进行裁剪#xff0c;获取指定尺寸
1 安装cropperjs
npm install cropperjs 2 具体实现
home.jsx 代码中的result模块用来展示最终的裁剪结果#xff1b;mask用作页面最上层蒙层#xff0c;用来裁…本文主要实现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.scsslet 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() // 销毁croppermyCropper 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}inputclassName{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}裁剪/divimg 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;}
}