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

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

效果预览

效果一:

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

实现过程

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官网

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/584762.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

在Linux操作系统中的文件系统及挂载介绍

磁盘存储数据的最小单位是数据块。 数据块只是一个概念&#xff0c;而不能查看&#xff0c;默认4kb是一个数据块。 块设备文件存储数据时是随机的数据块&#xff0c;而不是相邻的数据块。 无论一个数据块是否被占满&#xff0c;当一个数据块存储数据时&#xff0c;这个数据块…

哪个牌子的骨传导耳机好用?盘点五款高热度爆款骨传导耳机推荐!

近年来&#xff0c;骨传导耳机在潮流的推动下销量节节攀升&#xff0c;逐渐成为运动爱好者和音乐迷们的必备装备。但热度增长的同时也带来了一些品质上的忧患&#xff0c;目前市面上的部分产品&#xff0c;存在佩戴不舒适、音质不佳等问题&#xff0c;甚至可能对听力造成潜在损…

hdfs balancer -policy

hdfs balancer -policy当前有两种&#xff0c;datanode&#xff08;默认&#xff09;&#xff1a;如果每个数据节点是平衡的&#xff0c;则集群是平衡的。blockpool&#xff1a;如果每个datanode中的每个块池都是平衡的&#xff0c;则集群是平衡的。 代码区别&#xff1a;计算…

字段选择器

&#x1f4d5;作者简介&#xff1a; 过去日记&#xff0c;致力于Java、GoLang,Rust等多种编程语言&#xff0c;热爱技术&#xff0c;喜欢游戏的博主。 &#x1f4d8;相关专栏Rust初阶教程、go语言基础系列、spring教程等&#xff0c;大家有兴趣的可以看一看 &#x1f4d9;Jav…

Linux中ssh登录协议

目录 一.ssh基础 1.ssh协议介绍 2.ssh协议的优点 3.ssh文件位置 二.ssh原理 1.公钥传输原理&#xff08;首次连接&#xff09; 2.ssh加密通讯原理 &#xff08;1&#xff09;对称加密 &#xff08;2&#xff09;非对称加密 3.远程登录 三.服务端的配置 常用的配置项…

JENKINS 安装,学习运维从这里开始

Download and deployJenkins – an open source automation server which enables developers around the world to reliably build, test, and deploy their softwarehttps://www.jenkins.io/download/首先点击上面。下载Jenkins 为了学习&#xff0c;从windows开始&#x…

mysql面试题九(SQL优化)

目录 1.一条 SQL 是如何执行的 2.索引失效的几种情况 3.EXPLAIN 4.Where 子句如何优化 5.超大分页或深度分页如何处理 6.大表查询如何优化 7.分库分表 基本概念 分库分表方法 水平拆分 垂直拆分 分库分表后的注意事项 1.一条 SQL 是如何执行的 在MySQL中&#xff0…

Linux下软硬链接和动静态库制作详解

目录 前言 软硬链接 概念 软链接的创建 硬链接的创建 软硬链接的本质区别 理解软链接 理解硬链接 小结 动静态库 概念 动静态库的制作 静态库的制作 动态库的制作 前言 本文涉及到inode和地址空间等相关概念&#xff0c;不知道的小伙伴可以先阅读以下两篇文章…

vue 设置输入框只能输入数字且只能输入小数点后两位,并且不能输入减号

<el-input v-model.trim"sb.price" placeholder"现价" class"input_w3" oninput"valuevalue.replace(/[^0-9.]/g,).replace(/\.{2,}/g,.).replace(/^(\-)*(\d)\.(\d\d).*$/,$1$2.$3)"/> 嘎嘎简单、、、、、、、、、

RAPTOR:索引树状 RAG,使用树结构来捕捉文本的高级和低级细节

RAPTOR&#xff1a;索引树状 RAG&#xff0c;使用树结构来捕捉文本的高级和低级细节 提出背景使用树结构来捕捉文本的高级和低级细节递归摘要RAPTOR 递归树结构的构建 树遍历或压缩树检索 语义关联性检索对比 RAG、知识图谱树遍历检索和压缩树检索 提出背景 论文&#xff1…

西门子PCU50.3数控面板维修6FC5220-0AA31-2AA0

西门子数控面板维修&#xff0c;西门子工控机触摸屏维修6FC5247-0AA00-0AA3 西门子数控机床维修包括&#xff1a;840C/CE、840Di/DSL、840Di SL、802C S、802D SL、810D/DE、820D SL、S120数控电路板、数控伺服驱动模块、控制模块修、电源模块&#xff0c;西门子数控机床控制面…

SQL Sever无法连接服务器

SQL Sever无法连接服务器&#xff0c;报错证书链是由不受信任的颁发机构颁发的 解决方法&#xff1a;不用ssl方式连接 1、点击弹框中按钮“选项” 2、连接安全加密选择可选 3、不勾选“信任服务器证书” 4、点击“连接”&#xff0c;可连接成功

国内各种免费AI聊天机器人(ChatGPT)推荐(上)

作者主页&#xff1a;点击&#xff01; 国内免费AI推荐专栏&#xff1a;点击&#xff01; 创作时间&#xff1a;2024年4月27日11点25分 欢迎来到AI聊天机器人推荐系列的第一篇文章&#xff01; 在这个系列中&#xff0c;我将引领您探索国内各种AI聊天机器人的精彩世界。 从…

西瓜书学习——决策树形状、熵和决策树的本质

文章目录 决策树形状监督学习算法分类与回归 熵信息熵香农熵 (Shannon Entropy) - H(X)联合熵 (Joint Entropy) - H(X, Y)条件熵 (Conditional Entropy) - H(Y|X)互信息 (Mutual Information) - I(X; Y)相对熵 (Relative Entropy) / KL散度 (Kullback-Leibler Divergence) - DK…

[SpringBoot] JWT令牌——登录校验

JWT&#xff08;JSON Web Token&#xff09;是一种用于在网络应用之间传递信息的开放标准&#xff08;RFC 7519&#xff09;。它由三部分组成&#xff1a;头部&#xff08;header&#xff09;、载荷&#xff08;payload&#xff09;和签名&#xff08;signature&#xff09;。J…

【redis】初始redis和分布式系统的基本知识

˃͈꒵˂͈꒱ write in front ꒰˃͈꒵˂͈꒱ ʕ̯•͡˔•̯᷅ʔ大家好&#xff0c;我是xiaoxie.希望你看完之后,有不足之处请多多谅解&#xff0c;让我们一起共同进步૮₍❀ᴗ͈ . ᴗ͈ აxiaoxieʕ̯•͡˔•̯᷅ʔ—CSDN博客 本文由xiaoxieʕ̯•͡˔•̯᷅ʔ 原创 CSDN 如…

iOS ------ Method Swizzling (动态方法交换)

一&#xff0c;Method Swizzling 简介 Method&#xff08;方法&#xff09;对应的是objc_method结构体&#xff1b;而objc_method结构体中包含了SEL method_name(方法名&#xff09;&#xff0c;IMP method_imp&#xff08;方法实现&#xff09; // objc_method 结构体 typed…

Hadoop概述

大数据处理技术 对大数据技术的基本概念进行简单介绍&#xff0c;包括分布式计算、服务器集群和 Google 的 3 个大数据技术。 分布式计算 对于如何处理大数据&#xff0c;计算机科学界有两大方向。 第一个方向是集中式计算&#xff0c;就是通过不断增加处理器的数量来增强单…

开源项目介绍-01:AAMED-master 圆和椭圆检测

前言: AAMED: Arc Adjacency Matrix based Fast Ellipse Detection :基于弧邻接矩阵的快速椭圆检测 1 下载 GitHub - Li-Zhaoxi/AAMED: Arc Adjacency Matrix based Fast Ellipse Detection 开源项目,支持windows 和 Linux的,然后,有C++,Python,Matlab的几个版本。 Git…

SQL底层执行过程

MySQL 的查询流程 客户端请求连接器 负责与客户端的通信,是半双工模式&#xff08;半双工(Half Duplex)数据传输指数据可以在一个信号载体的两个方向上传输,但是不能同时传输。&#xff09;&#xff0c;验证请求用户的账户和密码是否正确&#xff0c;③如果用户的账户和密码验…