vue-cropper 图片剪裁

在这里插入图片描述
vue-cropper官网
链接:https://github.com/xyxiao001/vue-cropper

安装:npm install vue-cropper 或者 yarn add vue-cropper

图片上传的格式我用的是base64格式的,剪裁完的图片格式也同样转成了base64

<template>
  <a-modal :visible="visible" title="修改头像" :maskClosable="false" :confirmLoading="confirmLoading" :width="800"
           @cancel="cancelHandel">
    <a-row>
      <a-col :xs="24" :md="12" :style="{height: '350px'}">

        <vue-cropper
            ref="cropper"
            :img="imgUrl"
            :info="true"
            :autoCrop="options.autoCrop"
            :autoCropWidth="options.autoCropWidth"
            :autoCropHeight="options.autoCropHeight"
            :fixedBox="options.fixedBox"
            @realTime="realTime"
        >
        </vue-cropper>
      </a-col>
      <a-col :xs="24" :md="12" :style="{height: '350px'}">
        <div class="avatar-upload-preview">
          <img :src="previews.url" :style="previews.img"/>
        </div>
      </a-col>
    </a-row>
    <template slot="footer">
      <a-button key="back" @click="cancelHandel">取消</a-button>
      <a-button key="submit" type="primary" :loading="confirmLoading" @click="okHandel">保存</a-button>
    </template>
  </a-modal>
   </template>
<script>
import { VueCropper } from 'vue-cropper'
export default {
  name:'ImgCropperModal',
  components: {
    VueCropper
  },
data() {
  return {
    visible: false,
    confirmLoading: false,
    options: {
      img: '',
      autoCrop: true,
      autoCropWidth: 200,
      autoCropHeight: 200,
      fixedBox: true
    },
    previews: {},
  };
},
//这里是父组件传过来的base64格式的图片
  props: {
    imgUrl: {
      type: String,
      default: undefined
    },
  },
  methods: {
    show(){
      this.visible = true;
    },
    close() {
      this.visible = false;
    },
    cancelHandel() {
      this.close();
    },
    okHandel() {
      this.$refs.cropper.getCropBlob(async (data) => {
            this.blobToDataURL(data,imageUrl => {
              this.$emit('uploadImg',imageUrl)//反显回去
              this.visible =false
            })
      })
    },
    //blob 格式转 base64
    blobToDataURL(blob, callback) {
      let a = new FileReader();
      a.onload = function (e) { callback(e.target.result); }
      a.readAsDataURL(blob);
    },
    realTime(data) {
      this.previews = data
    }
  },
};

</script>
<style scoped>

.avatar-upload-preview {
  position: absolute;
  top: 50%;
  transform: translate(50%, -50%);
  width: 180px;
  height: 180px;
  border-radius: 50%;
  box-shadow: 0 0 4px #ccc;
  overflow: hidden;
}
img {
  width: 100%;
  height: 100%;

}
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值