Skip to content

图片裁剪

版本说明

时间修改人备注
2023-01-05Gw上传选择直传和base64接口上传、裁剪旋转
2022-12-05Gw初始化文档

文档地址:https://www.npmjs.com/package/vue-picture-cropper

props

props类型默认值备注
cropperShowBooleanfalse控制裁剪组件显隐
cropperTypeNumber1裁剪成功后上传的方式 1为base64 2为oss直传
cropperUrlString''裁剪图片的源地址
cropperConfObject{ viewMode: 1, // 裁剪框活动区域为图片区域 dragMode: 'crop', aspectRatio: 1 / 1, // 裁剪比例 } 附配置文档地址:https://github.com/fengyuanchen/cropperjs#options裁剪插件的配置项

event

事件返回值备注
closeCropper关闭裁剪弹窗的事件
getCropper{ filename: "202212/05/16702201986022.jpg", filename_id: "68", filename_url: "https://pro-mixedtest.babycdn.com/base/digi/uploads/202212/05/16702201986022.jpg" }确认裁剪结果的事件

示例

HTML:
<a-upload list-type="picture-card" accept="image/*" v-model:file-list="formState.bg_img" :max-count="1" :customRequest="unImage" @click="changeImage('bg')">
    <div>
        <plus-outlined />
    </div>
</a-upload>


<n-cropper :cropperShow="cropperShow" :cropper-url="picUrl" :cropper-conf="cropperConf" @closeCropper="cropperCancel" @getCropper="getCropper"></n-cropper>
JS:
import nCropper from "@/components/cropper.vue"


components: {
    nCropper
},
// 先使用antd的upload组件选择一个图片,然后将拿到的文件转为base64地址,传入裁剪组件中,同时显示裁剪弹窗
const unImage = (options) => {
    console.log(options)
    let file = options.file;
    upBase64Image(file)
}
const upBase64Image = (img) => {
    return new Promise((resolve, reject) => {
        let reader = new FileReader();
        reader.readAsDataURL(img);
        reader.onload = () => {
            cropperConf.picUrl = String(reader.result)
            // 显示裁切弹窗
            cropperConf.cropperShow = true
        }
    })
}
const cropperConf = reactive({
    // 裁剪配置
    cropperConf: {
        viewMode: 1, dragMode: 'crop', aspectRatio: 1 / 1
    },
    cropperShow: false,
    picUrl: '',
    cropperCancel: () => { // 裁剪取消时清空已选择的文件
        cropperConf.cropperShow = false
        if (!formState.bg_img) return
        formState.bg_img = []
    },
    getCropper: (res) => { // 裁剪成功后获取返回值进行赋值
        formState.page_logo = [{
            url: res.filename_url, // 全路径作展示
            status: "done",
            path: res.filename // 短路径作接口传入
        }]


        // 隐藏裁切弹窗
        cropperConf.cropperShow = false
    }
})