Vue Cropper
实现上传图片预览,裁切上传效果
下载
pnpm add vue- cropper@next
使用
< template>
< input
ref= "inputRef"
class = "hidden"
accept= ".png,.jpeg,.jpg"
multiple
type= "file"
@change= "handleUploadChange"
/ >
< div @click= "submitUpload" > 上传< / div>
< div class = "flex mt-50px" >
< div class = "w-400px h-360px" >
< vue- cropper
ref= "cropperRef"
: img= "image"
: autoCrop= "option.autoCrop"
: autoCropWidth= "option.autoCropWidth"
: autoCropHeight= "option.autoCropHeight"
@real- time= "realTime"
> < / vue- cropper>
< / div>
< ! -- 实时预览 -- >
< div v- html= "preview.html" > < / div>
< div @click= "handleConfirm" > 确认< / div>
< / div>
< / template>
< script lang= "ts" setup>
import "vue-cropper/dist/index.css" ;
import { VueCropper } from "vue-cropper" ;
import { ref } from "vue" ;
const preview = ref< any> ( { } ) ;
const inputRef = ref ( ) ;
function submitUpload ( ) {
inputRef. value?. click ( ) ;
}
const image = ref ( ) ;
async function handleUploadChange ( e : Event) {
const { files } = e. target as HTMLInputElement;
if ( files && files. length >= 1 ) {
const file = files[ 0 ] ;
const reader = new FileReader ( ) ;
reader. onload = ( e ) => {
image. value = e. target?. result;
} ;
reader. readAsDataURL ( file) ;
if ( inputRef. value?. value) {
inputRef. value. value = "" ;
}
}
}
const cropperRef = ref ( ) ;
const option = ref ( {
outputSize : 1 ,
outputType : "jpeg || png || webp" ,
info : true ,
canScale : true ,
autoCrop : true ,
autoCropWidth : 120 ,
autoCropHeight : 120 ,
fixed : true ,
fixedBox : false ,
canMove : true ,
canMoveBox : true ,
original : false ,
centerBox : false ,
high : true ,
infoTrue : true ,
maxImgSize : 2000 ,
enlarge : 1 ,
mode : "100%" ,
} ) ;
function realTime ( data : any) {
console. log ( "data" , data) ;
preview. value = data;
}
function handleConfirm ( ) {
cropperRef. value?. getCropBlob ( ( data : Blob) => {
} ) ;
}
< / script>
< style scoped> < / style>