加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

cropper js基于vue的图片裁剪上传功能的实现代码

发布时间:2020-12-17 02:33:22 所属栏目:百科 来源:网络整理
导读:前些日子做了一个项目关于vue项目需要头像裁剪上传功能,看了一篇文章,在此基础上做的修改完成了这个功能,与大家分享一下。原文: 首先下载引入cropper js, 在需要的页面引入: import Cropper from "cropper js" html的代码如下: 主要是js代码,如下 1

前些日子做了一个项目关于vue项目需要头像裁剪上传功能,看了一篇文章,在此基础上做的修改完成了这个功能,与大家分享一下。原文:

首先下载引入cropper js,

在需要的页面引入:import Cropper from "cropper js"

html的代码如下:

Picture

主要是js代码,如下

1,data里面定好初始变量,绑定数据,imgCropperData是我定义的判断图片格式的。

2,在mounted里面初始换裁剪框

3.methods的方法比较多,包括创建URL路径,input框change事件,canvas画图,确定提交上传。我还加了取消事件函数,判断上传文件的类型和大小。

5242880) { alert("请选择5M以内的图片!"); return false; } this.picValue = files[0]; this.url = this.getObjectURL(this.picValue); //每次替换图片要重新得到新的url if (this.cropper) { this.cropper.replace(this.url); } this.panel = true; },//确定提交 commit() { this.panel = false; var croppedCanvas; var roundedCanvas; if (!this.croppable) { return; } // Crop croppedCanvas = this.cropper.getCroppedCanvas(); // Round roundedCanvas = this.getRoundedCanvas(croppedCanvas); this.headerImage = roundedCanvas.toDataURL(); //上传图片 this.postImg(); },//canvas画图 getRoundedCanvas(sourceCanvas) { var canvas = document.createElement("canvas"); var context = canvas.getContext("2d"); var width = sourceCanvas.width; var height = sourceCanvas.height; canvas.width = width; canvas.height = height; context.imageSmoothingEnabled = true; context.drawImage(sourceCanvas,width,height); context.globalCompositeOperation = "destination-in"; context.beginPath(); context.arc( width / 2,height / 2,Math.min(width,height) / 2,2 * Math.PI,true ); context.fill(); return canvas; },//提交上传函数 postImg() { alert("上传成功"); //这边写图片的上传 } }

css样式代码就不贴出来了,可以到GitHub上下载-。

总结

以上所述是小编给大家介绍的cropper js基于vue的图片裁剪上传功能。编程之家 52php.cn 收集整理的教程希望能对你有所帮助,如果觉得编程之家不错,可分享给好友!感谢支持。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读