vue-cropper插件的官网的地址:

https://github.com/xyxiao001/vue-cropper

在线的demo展示:

http://github.xyxiao.cn/vue-cropper/example/

安装

npm install vue-cropper

使用

在需要的组件中直接引用,或者在main.js中

import VueCropper from 'vue-cropper'
Vue.use(VueCropper)

组件内

1.设置出一个点击展示裁剪组件的按钮

el-button icon="el-icon-plus" style="padding:15px !important" @click="handleChangeImage"></el-button>
<image-cropper :key="imagecropperKey" :width="300" :height="300" lang-type="zh" @close="close" />
<img :src="imgUrl2" alt="" style="display:inline-block;width:45px;vertical-align: middle;"/>

 

2.vue-cropper组件弹出层:

<dialog-comp :is-show.sync="dialogFormVisible" :dialog-title="$t('common.direction')" :dialog-width="600" :dialog-height="450" dialog-unit="px" :iconWindow="'icon-ico_minglingxiafa_xuanzhong'">
    <label class="btn" for="uploads">选择图片</label>
    <input type="file" id="uploads" :value="imgFile" style="position:absolute; clip:rect(0 0 0 0);" accept="image/png, image/jpeg, image/gif, image/jpg" @change="uploadImg($event, 1)" />
    <div style="padding:10px;display:flex">
      <div class="cut">
        <vueCropper
          ref="cropper"
          :img="option.img"
          :outputSize="option.size"
          :outputType="option.outputType"
          :info="option.info"
          :full="option.full"
          :canMove="option.canMove"
          :canMoveBox="option.canMoveBox"
          :original="option.original"
          :autoCrop="option.autoCrop"
          :autoCropWidth="option.autoCropWidth"
          :autoCropHeight="option.autoCropHeight"
          :fixedBox="option.fixedBox"
          :canScale="option.canScale"
          :fixed="option.fixed"
          :centerBox="option.centerBox"
          :high="option.high"
          :mode="option.mode"
          :fixedNumber="option.fixedNumber"
          @realTime="realTime"
          @imgLoad="imgLoad"
        ></vueCropper>
      </div>
      <div class="show-preview" :style="{ overflow: 'hidden', margin: '5px' }">
        <div :style="previews.div" class="preview">
          <img :src="previews.url" :style="previews.img" />
        </div>
      </div>
    </div>

    <div class="dialog-footer" style="text-align:right">
      <el-button @click="closeCropper" size="small">取 消</el-button>
      <el-button type="primary" @click="finish('blob')" size="small">确 定</el-button>
    </div>
  </dialog-comp>

 3.js部分

import { VueCropper } from "vue-cropper";
// 官网地址https://github.com/xyxiao001/vue-cropper
export default {
  components: {
    VueCropper,
  },
  data() {
    return {
      previews: {},
      model: false,
      modelSrc: "",
      fileName: "",
      imgFile: "",
      dialogFormVisible: false,
      option: {
        img: "",
        outputSize: 1, //剪切后的图片质量(0.1-1)
        full: false, //输出原图比例截图 props名full
        outputType: "png", //裁剪生成图片的格式
        canMove: true, //上传图片是否可以移动
        original: false, //上传图片按照原始比例渲染
        canMoveBox: false, //截图框是否可以拖动
        autoCrop: true, //是否默认生成截图框
        autoCropWidth: 200, //默认截图框宽度
        autoCropHeight: 200, //默认生成截图框高度
        fixedBox: false, //固定截图框大小
        fixedNumber: [1, 1], //截图框的宽高比例
        mode: "auto 200px", //图片默认渲染方式
        info: true, //裁剪框的大小信息
        canScale: true, //图片是否允许滚轮缩放
        fixed: true, //是否开启截图框宽高固定比例
        centerBox: true, //截图框是否被限制在图片里面
        high: true, //是否按照设备的dpr 输出等比例图片
      },
      imgUrl2: "",
      originIcon: "",
    };
  },
  methods: {
    closeCropper() {
      console.log("chufa");
      this.dialogFormVisible = false;
    },
    //上传图片(点击上传按钮)
    finish(type) {
      console.log(type);
      let selft = this;
      let formData = new FormData();
      // 输出
      if (type === "blob") {
        selft.$refs.cropper.getCropData((data) => {
          // console.log(this.$refs.cropper);
          // let img = window.URL.createObjectURL(data);
          let img = data;
          selft.model = true;
          selft.modelSrc = img;
          this.imageToCircle(img).then((res) => {
            //截出来的图片画成圆形
            selft.originIcon = res;
          });
          // 以下是上传的动作
         
        });
      } else {
        this.$refs.cropper.getCropData((data) => {});
      }
    },
    //选择本地图片
    uploadImg(e, num) {
      console.log("uploadImg");
      var selft = this;
      //上传图片
      var file = e.target.files[0];
      selft.fileName = file.name;
      if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) {
        alert("图片类型必须是.gif,jpeg,jpg,png,bmp中的一种");
        return false;
      }
      var reader = new FileReader();
      reader.onload = (e) => {
        let data;
        if (typeof e.target.result === "object") {
          // 把Array Buffer转化为blob 如果是base64不需要
          data = window.URL.createObjectURL(new Blob([e.target.result]));
        } else {
          data = e.target.result;
        }
        if (num === 1) {
          selft.option.img = data;
        } else if (num === 2) {
          selft.example2.img = data;
        }
      };
      // 转化为base64
      reader.readAsDataURL(file);
      // 转化为blob
      // reader.readAsArrayBuffer(file);
    },
    imageToCircle(picUrl) {
      // 通过图片地址换出圆形的图片
      let radius, diameter, canvas, ctx;
      let img = new Image();
      img.setAttribute("crossOrigin", "anonymous"); // 解决图片跨域访问失败
      img.src = picUrl;
      return new Promise((reslove) => {
        img.addEventListener(
          "load",
          () => {
            let { width, height } = img;
            if (img.width > img.height) {
              radius = height / 2;
            } else {
              radius = width / 2;
            }
            diameter = radius * 2;

            canvas = document.createElement("canvas");
            if (!canvas.getContext) {
              // 判断浏览器是否支持canvas,如果不支持在此处做相应的提示
              console.log("您的浏览器版本过低,暂不支持。");
              return false;
            }
            canvas.width = diameter;
            canvas.height = diameter;

            ctx = canvas.getContext("2d");
            ctx.clearRect(0, 0, diameter, diameter);

            // 描边
            ctx.save(); //save和restore可以保证样式属性只运用于该段canvas元素
            ctx.strokeStyle = "#eee"; //设置边线的颜色
            ctx.lineWidth = 2;
            ctx.beginPath(); //开始路径
            ctx.arc(radius, radius, radius - 5, 0, Math.PI * 2); //画一个整圆.
            ctx.stroke(); //绘制边线

            // 截圆形图
            ctx.save();
            ctx.beginPath();
            ctx.arc(radius, radius, radius - 5, 0, Math.PI * 2);
            ctx.clip();

            let x = 0,
              y = 0,
              swidth = diameter,
              sheight = diameter;

            ctx.drawImage(img, x, y, swidth, sheight, 0, 0, diameter, diameter);
            ctx.restore();
            // toDataURL()是canvas对象的一种方法,用于将canvas对象转换为base64位编码
            let dataURL = canvas.toDataURL("image/png");
            reslove(dataURL);
          },
          false
        );
      });
    },
    show() {
      this.dialogFormVisible = true;
    },
    // 实时预览函数
    realTime(data) {
      // console.log("realTime");
      this.previews = data;
    },
    imgLoad(msg) {
      // console.log("imgLoad");
      console.log(msg);
    },
    listEvent() {
      this.app.$on("handle-change-image", this.show);
    },
    offEvent() {
      this.app.$off("handle-change-image", this.show);
    },
  },
  mounted() {
    this.listEvent();
  },
  beforeDestroy() {
    this.offEvent();
  },
};

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐