前端业务开发中使用原生js和elementui两种方式实现头像裁切上传的功能

本文详细介绍了如何在日常业务开发中,利用原生JavaScript和Vue框架结合cropperjs库实现图片裁剪功能,包括上传、预览、尺寸调整和保存等操作。同时展示了Vue2+ElementUI的实现方式和组件配置选项。
摘要由CSDN通过智能技术生成

日常业务开发中,无论是后台管理系统还是前台界面,都会遇到图片裁剪的业务需求,选择合适的尺寸或者图片的关键部分,满足我们的功能需求!!

效果预览

效果一:

请添加图片描述效果二:请添加图片描述

实现过程

1.原生js实现方式

引入cropperjs的库文件和样式

<script src="https://cdn.jsdelivr.net/npm/cropperjs/dist/cropper.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/cropperjs/dist/cropper.css" rel="external nofollow" >
*{
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: "Poppins",sans-serif;
}
body{
  background-color: #025bee;
}
.wrapper{
  width: min(90%,800px);
  position: absolute;
  transform: translateX(-50%);
  left:50%;
  top:1em;
  background-color: #fff;
  padding: 2em 3em;
  border-radius: .5em;
}
.container{
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap:1em;
}
.container .image-container,.container .preview-container{
   width: 100%;
   /* background-color: aquamarine; */
}

input[type="file"]{
  display: none;
}

label{
  display: block;
  position: relative;
  background-color: #025bee;
  font-size: 16px;
  text-align: center;
  width: 250px;
  color:#fff;
  padding: 16px 0;
  margin: 16px auto;
  cursor: pointer;
  border-radius: 5px;
}

img{
  display: block;
  /**is key to cropper.js**/
  max-width: 100%;
}

.image-container{
  width: 60%;
  margin: 0 auto;
}

.options{
  display: flex;
  justify-content: center;
  gap:1em;
}
input[type="number"]{
  width: 100px;
  padding: 16px 5px;
  border-radius: .3em;
  border: 2px solid #000;
}

button{
  padding: 1em;
  border-radius: .3em;
  border: 2px solid #025bee;
  background-color: #fff;
  color: #025bee;
}

.btns{
  display: flex;
  justify-content: center;
  gap: 1em;
  margin-top: 1em;

}
.btns button{
  font-size: 1em;
}
.btns a {
  border: 2px solid #025bee;
  background-color: #025bee;
  color: #fff;
  text-decoration: none;
  padding: 1em;
  font-size: 1em;
  border-radius: .3em;
}
.hide{
  display: none;
}
<div class="wrapper">
      <div class="container">
        <div class="image-container">
          <img src="" alt="" id="image">
        </div>
        <div class="preview-container">
           <img src="" alt="" id="preview-image">
        </div>
      </div>
      <input type="file" name="" id="file" accept="image/*">
      <label for="file">选择一张图片</label>
      <div class="options hide">
        <input type="number" name="" id="height-input" placeholder="输入高度" max="780" min="0">
        <input type="number" name="" id="width-input" placeholder="输入宽度" max="780" min="0">
        <button class="aspect-ration-button">16:9</button>
        <button class="aspect-ration-button">4:3</button>
        <button class="aspect-ration-button">1:1</button>
        <button class="aspect-ration-button">2:3</button>
        <button class="aspect-ration-button">自由高度</button>
      </div>
      <div class="btns">
         <button id="preview" class="hide">
          预览
         </button>
         <a href="" id="download" class="hide">下载</a>
      </div>
   </div>

核心步骤:

<script>
     const oFile = document.querySelector('#file')
     const oImage = document.querySelector('#image')
     const oDownload = document.querySelector('#download')
     const oAspectRation = document.querySelectorAll('.aspect-ration-button')
     const oOptions = document.querySelector('.options')
     const oPreview = document.querySelector('#preview-image')
     const oPreviewBtn = document.querySelector('#preview')
     const heightInput = document.querySelector('#height-input')
     const widthInput = document.querySelector('#width-input')
     let cropper = '',filename = ''
     /**
      * 上传事件
      * 
      * /
      */
    oFile.onchange = function(e){
      oPreview.src=""
      heightInput.value = 0
      widthInput.value = 0
      oDownload.classList.add('hide')


      const reader = new FileReader()
      reader.readAsDataURL(e.target.files[0])
      reader.onload = function(e){
        oImage.setAttribute('src',e.target.result)
        if(cropper){
          cropper.destory()
        }
        cropper = new Cropper(oImage)
        oOptions.classList.remove('hide')
        oPreviewBtn.classList.remove('hide')
      }
      filename = oFile.files[0].name.split(".")[0]
      oAspectRation.forEach(ele => {
        ele.addEventListener('click', () => {
          if(ele.innerText === '自由高度'){
            cropper.setAspectRatio(NaN)
          }else{
            cropper.setAspectRatio(eval(ele.innerText.replace(":",'/')))
          }
        }, false)
      })

      heightInput.addEventListener('input', () => {
        const {height} = cropper.getImageData()
        if(parseInt(heightInput.value) > Math.round(height)){
          heightInput.value = Math.round(height)
        }
        let newHeight = parseInt(heightInput.value)
        cropper.setCropBoxData({
          height:newHeight
        })
      }, false)

      widthInput.addEventListener('input', () => {
        const {width} = cropper.getImageData()
        if(parseInt(widthInput.value) > Math.round(width)){
          widthInput.value = Math.round(width)
        }
        let newWidth = parseInt(widthInput.value)
        cropper.setCropBoxData({
          width:newWidth
        })
      }, false)

      oPreviewBtn.addEventListener('click', (e) => {
        e.preventDefault();
        oDownload.classList.remove('hide');
        let imgSrc = cropper.getCroppedCanvas({}).toDataURL();
        oPreview.src = imgSrc;
        oDownload.download = `cropped_${filename}.png`;
        oDownload.setAttribute('href',imgSrc)
      }, false)
    }
   </script>
  1. vue2+elementui实现

安装vue-cropper库

npm i vue-cropper

静态页面

<template>
  <g-container>
    <div>
      <span>点击头像,更换头像:</span>
      <el-avatar @click.native="handleShowCropper" :src="avatarUrl"></el-avatar>
    </div>
    <el-dialog
      title="更换头像"
      :visible.sync="dialogVisible"
      width="800px"
      :before-close="dialogBeforeClose"
      v-if="dialogVisible"
      append-to-body
    >
      <el-row :gutter="10">
        <el-col :span="12" :style="{ height: '350px' }">
          <vueCropper
            ref="cropper"
            :img="option.img"
            :info="true"
            :auto-crop="option.autoCrop"
            :outputSize="option.size"
            :outputType="option.outputType"
            @realTime="realTime"
            centerBox
          ></vueCropper>
        </el-col>
        <el-col :span="12" class="preview-container">
          <div class="avatar-upload-preview">
            <div :style="previews.div">
              <img :src="previews.url" :style="previews.img" />
            </div>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="10" style="margin-top:20px;text-align:center" justify="center">
        <el-col :span="4">
          <el-upload
            action
            name="file"
            accept="image/*"
            :before-upload="beforeUpload"
            :show-upload-list="false"
          >
            <el-button icon="upload">选择图片</el-button>
          </el-upload>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="changeScale(1)">放大</el-button>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="changeScale(-1)">缩小</el-button>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="rotateLeft">左旋转</el-button>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="rotateRight">右旋转</el-button>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="saveHandle('blob')">保存</el-button>
        </el-col>
      </el-row>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </div>
    </el-dialog>
  </g-container>
</template>

在这里插入图片描述
在这里插入图片描述
关键的js代码实现

export default {
  components: {
    VueCropper,
  },
  data() {
    return {
      option: { img: "", size: 1, outputType: "", autoCrop: true },
      dialogVisible: false,
      previews: {},
      avatarUrl:
        "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png",
    };
  },
  methods: {
    handleShowCropper() {
      this.dialogVisible = true;
    },
    dialogBeforeClose() {
      this.dialogVisible = false;
    },
    changeScale(num) {
      this.$refs.cropper.changeScale(num);
    },
    // 左旋转
    rotateLeft() {
      this.$refs.cropper.rotateLeft();
    },
    // 右旋转
    rotateRight() {
      this.$refs.cropper.rotateRight();
    },
    beforeUpload(file) {
      console.log("🚀 ~ beforeUpload ~ file:", file);
      const reader = new FileReader();
      //转化为base64
      reader.readAsDataURL(file);
      reader.onload = () => {
        console.log(reader, "reader");
        // this.previews.url = reader.result;
        this.option.img = reader.result;
      };
    },
    // 裁剪之后的数据
    realTime(data) {
      console.log("🚀 ~ realTime ~ data:", data);
      this.previews = data;
    },
    // 上传图片(点击保存按钮)
    saveHandle(type) {
      this.$refs.cropper.getCropData((data) => {
        this.dialogVisible = false;
        console.log(data);
        // data为base64图片,供接口使用
        this.avatarUrl = data;
        this.$emit("save", data);
      });
    },
    beforeDestory() {
      this.previews = null;
      this.option = null;
    },
  },
};
</script>

组件的option配置项,大家可以去逐个测试下,体验下效果!!
在这里插入图片描述
这样,我们就实现了两种不同的图像裁剪上传!!

附上参考资料:Cropperjs官网

  • 29
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 原生的 Vue.jsElementUI.js 可以使用以下方法来实现复用 header 组件: 1. 建立一个 header 组件文件,在文件创建一个 Vue 组件,包括 template、script 和 style 三个部分。 2. 在其他组件引用这个 header 组件,可以使用 Vue 的组件化机制来实现。 例如,建立一个名为 Header 的组件: ``` <template> <div class="header"> <!-- header 组件的内容 --> </div> </template> <script> export default { name: 'Header', // 组件的选项 } </script> <style> /* header 组件的样式 */ </style> ``` 在其他组件引用 Header 组件: ``` <template> <div class="other-component"> <Header /> <!-- 其他组件的内容 --> </div> </template> <script> import Header from './Header.vue' export default { name: 'OtherComponent', components: { Header } } </script> ``` 这样,你就可以在其他组件复用 Header 组件了。 注意:如果你使用的是 ElementUI.js,你还需要在 main.js 导入 ElementUI,并调用 Vue.use(ElementUI) 来使用 ElementUI 的组件。 ### 回答2: 在原生的vue.jselementui.js,即使不使用组件的情况下,也可以实现header的复用。下面是一个可能的实现方法: 1. 首先,在vue.js的实例,定义一个header组件的对象,用于存储header的相关数据和方法。例如: ```javascript var headerComponent = { data: function() { return { headerText: 'Page Header' }; }, methods: { handleClick: function() { console.log('Clicked on header'); } }, template: ` <header> <h1>{{ headerText }}</h1> <button @click="handleClick">Click Me</button> </header> ` }; ``` 2. 在需要使用header的vue实例,通过将header组件对象添加到该实例的`components`选项,即可在模板引用header组件。例如: ```javascript new Vue({ el: '#app', components: { 'app-header': headerComponent } }); ``` ```html <div id="app"> <app-header></app-header> <!-- 页面内容 --> </div> ``` 这样,header组件就可以在多个vue实例进行复用了。可以根据具体需求,修改header组件的数据和方法,以满足不同页面的需求。 需要注意的是,以上方法并没有直接使用elementui.js,而是只使用了vue.js原生功能。如果需要进一步修改样式,可以在相应的CSS文件添加样式规则。 ### 回答3: 如果不使用组件,即只使用原生的vue.jselementui.js实现header的复用,可以按照以下步骤进行操作: 1. 在项目创建一个单独的vue组件,命名为Header.vue,该组件负责展示header的内容和样式。 2. 在Header.vue组件,可以使用elementui.js提供的组件或样式来实现header的布局和样式设计。比如可以使用el-row和el-col来进行栅格布局,使用el-menu和el-menu-item来实现菜单导航等功能。 3. 在Header.vue组件,通过vue的数据绑定和事件监听机制,可以实现header的动态展示和交互功能。比如可以通过定义data属性来动态显示登录用户信息,通过定义methods方法来响应用户点击事件。 4. 在需要使用header的页面,可以通过引入Header.vue组件来复用header。可以使用vue.js的import语句导入Header.vue组件,然后在页面使用<Header></Header>标签进行调用。 5. 在实际使用,可以通过修改Header.vue组件的props属性来实现不同页面header的差异化展示。比如可以通过props接收不同页面传递的参数,从而动态展示不同的内容和样式。 通过上述步骤,即可在原生的vue.jselementui.js实现header的复用功能。虽然没有使用组件,但是仍然可以通过vue的特性和elementui.js提供的样式和组件来实现header的灵活动态展示。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值