vue3项目中使用vue-cropper实现截图效果

前言:

        自用!!!

插件文档链接:

        https://www.npmjs.com/package/vue-cropper

使用步骤:

        1、安装

npm install vue-cropper

         2、项目中引入(全局引入);文档中有介绍如何局部引入

        3、使用

<!-- 权限管理 -->
<template>
  <el-container class="permission_con">
    <vueCropper
      style="width: 100%; height: 100%"
      ref="cropper"
      :img="option.img"
      :outputSize="option.outputSize"
      :outputType="option.outputType"
      :autoCrop="option.autoCrop"
      :autoCropWidth="option.autoCropWidth"
      :autoCropHeight="option.autoCropHeight"
    ></vueCropper>
  </el-container>
  <el-row style="width: 100%; height: 60px; margin-top: 10px">
    <el-upload
      v-model:file-list="fileList"
      action=""
      :auto-upload="false"
      :show-file-list="false"
      :on-change="handleChange"
    >
      <el-button type="primary">上传图片</el-button>
    </el-upload>
    <el-button type="primary" plain @click="rotateLeft">左旋转</el-button>
    <el-button type="primary" plain @click="rotateRight">右旋转</el-button>
    <el-button type="primary" @click="getCropDataBase64">确认截图</el-button>
  </el-row>
  <div>展示截图的图片</div>
  <div style="width: 300px; height: 500px">
    <img :src="imgUrl" style="width: 100%; height: 50%" />
  </div>
</template>
<script>
import { reactive, ref, toRefs } from 'vue'
export default {
  setup() {
    let data = reactive({
      option: {
        img: '', //裁剪图片的地址
        outputSize: 1, //outputSize 0~1
        outputType: 'jpg', //裁剪生成图片的格式
        autoCrop: true, //是否默认生成截图框
        autoCropWidth: "280px",//默认生成截图框宽度
        autoCropHeight: "240px",//默认生成截图框高度
      },
      cropper: ''
    })
    let imgUrl = ref()
    //向左旋转图片
    const rotateLeft = () => {
      data.cropper.rotateLeft()
    }
    //向右旋转图片
    const rotateRight = () => {
      data.cropper.rotateRight()
    }
    function handleChange(file) {
      data.option.img = URL.createObjectURL(file.raw)
    }
    function getCropDataBase64() {
      data.cropper.getCropData((data) => {
        imgUrl.value = data
      })
    }
    return {
      ...toRefs(data),
      imgUrl,
      rotateLeft,
      rotateRight,
      handleChange,
      getCropDataBase64
    }
  }
}
</script>
<style lang="scss">
.permission_con {
  width: 100%;
  height: 50%;
}
.el-button{
  margin:0 20px;
}
</style>

猜你喜欢

转载自blog.csdn.net/m0_73334325/article/details/134953843