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

本文主要是介绍前端业务开发中使用原生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 = 0widthInput.value = 0oDownload.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-dialogtitle="更换头像":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' }"><vueCropperref="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-uploadactionname="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();//转化为base64reader.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官网

这篇关于前端业务开发中使用原生js和elementui两种方式实现头像裁切上传的功能的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/948612

相关文章

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

Windows下C++使用SQLitede的操作过程

《Windows下C++使用SQLitede的操作过程》本文介绍了Windows下C++使用SQLite的安装配置、CppSQLite库封装优势、核心功能(如数据库连接、事务管理)、跨平台支持及性能优... 目录Windows下C++使用SQLite1、安装2、代码示例CppSQLite:C++轻松操作SQ

PostgreSQL中MVCC 机制的实现

《PostgreSQL中MVCC机制的实现》本文主要介绍了PostgreSQL中MVCC机制的实现,通过多版本数据存储、快照隔离和事务ID管理实现高并发读写,具有一定的参考价值,感兴趣的可以了解一下... 目录一 MVCC 基本原理python1.1 MVCC 核心概念1.2 与传统锁机制对比二 Postg

SpringBoot整合Flowable实现工作流的详细流程

《SpringBoot整合Flowable实现工作流的详细流程》Flowable是一个使用Java编写的轻量级业务流程引擎,Flowable流程引擎可用于部署BPMN2.0流程定义,创建这些流程定义的... 目录1、流程引擎介绍2、创建项目3、画流程图4、开发接口4.1 Java 类梳理4.2 查看流程图4

C++中零拷贝的多种实现方式

《C++中零拷贝的多种实现方式》本文主要介绍了C++中零拷贝的实现示例,旨在在减少数据在内存中的不必要复制,从而提高程序性能、降低内存使用并减少CPU消耗,零拷贝技术通过多种方式实现,下面就来了解一下... 目录一、C++中零拷贝技术的核心概念二、std::string_view 简介三、std::stri

Python常用命令提示符使用方法详解

《Python常用命令提示符使用方法详解》在学习python的过程中,我们需要用到命令提示符(CMD)进行环境的配置,:本文主要介绍Python常用命令提示符使用方法的相关资料,文中通过代码介绍的... 目录一、python环境基础命令【Windows】1、检查Python是否安装2、 查看Python的安

C++高效内存池实现减少动态分配开销的解决方案

《C++高效内存池实现减少动态分配开销的解决方案》C++动态内存分配存在系统调用开销、碎片化和锁竞争等性能问题,内存池通过预分配、分块管理和缓存复用解决这些问题,下面就来了解一下... 目录一、C++内存分配的性能挑战二、内存池技术的核心原理三、主流内存池实现:TCMalloc与Jemalloc1. TCM

OpenCV实现实时颜色检测的示例

《OpenCV实现实时颜色检测的示例》本文主要介绍了OpenCV实现实时颜色检测的示例,通过HSV色彩空间转换和色调范围判断实现红黄绿蓝颜色检测,包含视频捕捉、区域标记、颜色分析等功能,具有一定的参考... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间

苹果macOS 26 Tahoe主题功能大升级:可定制图标/高亮文本/文件夹颜色

《苹果macOS26Tahoe主题功能大升级:可定制图标/高亮文本/文件夹颜色》在整体系统设计方面,macOS26采用了全新的玻璃质感视觉风格,应用于Dock栏、应用图标以及桌面小部件等多个界面... 科技媒体 MACRumors 昨日(6 月 13 日)发布博文,报道称在 macOS 26 Tahoe 中

全面解析HTML5中Checkbox标签

《全面解析HTML5中Checkbox标签》Checkbox是HTML5中非常重要的表单元素之一,通过合理使用其属性和样式自定义方法,可以为用户提供丰富多样的交互体验,这篇文章给大家介绍HTML5中C... 在html5中,Checkbox(复选框)是一种常用的表单元素,允许用户在一组选项中选择多个项目。本