微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

前些日子做了一个项目关于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的图片裁剪上传功能。编程之家 jb51.cc 收集整理的教程希望能对你有所帮助,如果觉得编程之家不错,可分享给好友!感谢支持

原文地址:https://www.jb51.cc/vue/33462.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐