最近在項目中用到上傳裁剪,看了一下代碼,覺得這插件可可以。梳理了一下代碼分享給大家
前端UI組件element-plus
如果你也用到了 ,快速幫你解決了問題,別忘記點贊收藏
1.首先看效果圖
- 因為版本
vue-cropper
眾多 ,雖然網上有各種寫法 為了保證能運行 直接copy代碼就能用 - 直接在
package.json
中添加依賴"vue-cropper": "^1.0.9",
然后安裝依賴npm install
5 創建一個公用組件
imgcropper.vue
<template><el-dialogv-model="isModel"title="裁剪圖片"width="1000px"destroy-on-closecenterdraggable><div class="main"><div class="tip"><div class="tip-text">上傳說明"vue-cropper": "^1.0.9"版本</div></div><el-row :gutter="20"><el-col span="14"><div class="mainbox"><vue-cropperref="cropper":img="option.img":outputSize="option.outputSize":outputType="option.outputType":info="option.info":canScale="option.canScale":autoCrop="option.autoCrop":autoCropWidth="option.autoCropWidth":autoCropHeight="option.autoCropHeight":fixed="option.fixed":fixedNumber="option.fixedNumber":full="option.full":fixedBox="option.fixedBox":canMove="option.canMove":canMoveBox="option.canMoveBox":original="option.original":centerBox="option.centerBox":height="option.height":infoTrue="option.infoTrue":maxImgSize="option.maxImgSize":enlarge="option.enlarge":mode="option.mode"@realTime="realTime"></vue-cropper><div class="main-btn"><el-button size="sm" @click="rotateLeft">? 向左旋轉15°</el-button><el-button size="sm" @click="rotateRight">? 向左旋轉15°</el-button><el-button size="sm" @click="changeScale(1)"><el-icon type="elui-icon-add-circle" color="#fff"></el-icon>+ 放大</el-button><el-button size="sm" @click="changeScale(-1)" >- 縮小</el-button ><el-button type="danger" size="sm" @click="changeReset" >重置</el-button ></div></div></el-col><el-col span="10"><div class="preview-model"><div class="preview" style="width: 200px; height: 200px" v-if="previews.url"><el-imagelazystyle="width: 100px; height: 100px":src="previews.url":zoom-rate="1.2":max-scale="7":min-scale="0.2":preview-src-list="srcList":initial-index="4"@load="lookImg"/></div><div class="upload-btn"><el-upload v-model="file" :on-change="selectImg"><el-button type="primary" size="sm">選擇圖片</el-button></el-upload><el-button type="success" style="margin-left: 10px;" size="sm" @click="uploadFile">確認上傳</el-button></div></div></el-col></el-row></div></el-dialog></template>
<script setup>
import { ref, reactive ,watch,defineExpose} from "vue";
import { VueCropper } from "vue-cropper";import "vue-cropper/dist/index.css";
const isModel = ref(false);
const name = ref();
const file = ref();
const previews = ref({});
const previewImg = ref();
const cropper = ref(null);
const emit = defineEmits([""]);const option = reactive({img: "",name: "",outputSize: 1, //裁剪生成圖片的質量(可選0.1 - 1)outputType: "png", //裁剪生成圖片的格式(jpeg || png || webp)info: true, //圖片大小信息canScale: true, //圖片是否允許滾輪縮放autoCrop: true, //是否默認生成截圖框autoCropWidth: 200, //默認生成截圖框寬度autoCropHeight: 200, //默認生成截圖框高度fixed: false, //是否開啟截圖框寬高固定比例fixedNumber: [1.53, 1], //截圖框的寬高比例full: false, //false按原比例裁切圖片,不失真fixedBox: false, //固定截圖框大小,不允許改變canMove: true, //上傳圖片是否可以移動canMoveBox: true, //截圖框能否拖動original: false, //上傳圖片按照原始比例渲染centerBox: true, //截圖框是否被限制在圖片里面height: false, //是否按照設備的dpr 輸出等比例圖片infoTrue: false, //true為展示真實輸出圖片寬高,false展示看到的截圖框寬高maxImgSize: 3000, //限制圖片最大寬度和高度enlarge: 1, //圖片根據截圖框輸出比例倍數mode: "100% 100%", //圖片默認渲染方式
});//預覽
const srcList = ref([])//當再次打開時 清空圖片
watch(isModel, (val) => {if (!val) {previews.value = {};option.img = ''srcList.value = []}
});//實時預覽
const realTime = (data) => {previews.value = data;option.autoCropWidth = data.img.width;option.autoCropHeight = data.img.height;
};//圖片縮放
const changeScale = (num) => {num = num || 1;cropper.value.changeScale(num);
};// 向左旋轉
const rotateLeft = () => {cropper.value.rotate = cropper.value.rotate - 15 / 90;//直接旋轉90度cropper.value.rotateLeft()
};//向右旋轉
const rotateRight = () => {cropper.value.rotate = cropper.value.rotate + 15 / 90;//直接旋轉90度// cropper.value.rotateRight()
};// 重置
const changeReset = () => {cropper.value.refresh();
};//圖片預覽圖片
const lookImg = () => {cropper.value.getCropBlob((data) => {file.value = data;let img = window.URL.createObjectURL(data);srcList.value.push(img)});
};//選擇圖片
const selectImg = (e) => {//這里需要注意 每個UI組件 返回的數據格式不一樣 需要什么取什么srcList.value = [];option.img = URL.createObjectURL(e.raw);option.name = e.raw.name;};/*** @function 確認上傳** */
const uploadFile = () => {cropper.value.getCropBlob((data) => {if (data) {data.fileName = option.name;}emit("uploadImgSuccess", data);});
};/*** @function 開啟彈窗* */
const open = () => {isModel.value = true;
};/*** @function 關閉* */
const close = () => {isModel.value = false;
};defineExpose({open,close,
});
</script>
<style lang="scss" scoped>
.main {box-sizing: border-box;min-height: 450px;padding: 20px;.tip {display: flex;align-items: center;margin-bottom: 20px;.tip-text {color: red;}}.mainbox {width: 100%;height: 300px;}.preview-model {display: flex;flex-direction: column;justify-content: flex-start;align-items: center;.preview {overflow: hidden;}.upload-btn {display: flex;width: 100%;justify-content: space-evenly;margin-top: 20px;}}.main-btn {display: flex;justify-content: center;margin-top: 20px;}
}</style>
直接在頁面中使用 例如index.vue
index.vue
<template><div class='content'><el-button type="danger" @click="addimg">上傳圖片 </el-button><img v-if="imgurl" :src="imgurl" alt="" width='200' height="100"><comCutimgcropper ref="imgref" @uploadImgSuccess="uploadImgSuccess" ></comCutimgcropper></div>
</template><script setup>
import comCutimgcropper from '../components/imgcropper.vue'
import { ref ,watch} from 'vue'
import {useRoute, useRouter} from 'vue-router'
const router = useRouter();
const imgref = ref(null);
const imgurl = ref("");const addimg = () => {imgref.value.open();
}const uploadImgSuccess = data => {//調用接口// uploadImage(data)//這里為了展示 直接 寫死一張圖片 關閉彈框imgurl.value = "https://img2.baidu.com/it/u=3354585195,1512541150&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1700845200&t=636a3f6d0f2d46b6753a203f48801a98"imgref.value.close()}
const uploadImage = async data => {console.log(data)//這里就是跟后臺約定好需要傳遞什么參數const params = {file: data,fileName: data.fileName, }//上傳接口const res = await uploads(params);if (res && res.code === 200) {//頁面上顯示圖片 后端返回的圖片地址imgurl.value = res.data.url;//關閉彈窗imgref.value.close()}
}/*** axiso 封裝一般這么寫 都是采用 FormData的形式 注意請求頭 headers 'Content-Type': 'multipart/form-data'* * export const uploads = params => {const data = new FormData()data.append('file', params.file, params.fileName)return request({headers: {'Content-Type': 'multipart/form-data'},url: '/,method: 'post',data,})
}*/</script>