vue移动端裁剪图片结合插件Cropper的使用实例代码

前端之家收集整理的这篇文章主要介绍了vue移动端裁剪图片结合插件Cropper的使用实例代码前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

之前写了一个上传头像的功能模块,以下的内容是描述上传头像过程中裁剪图片插件结合vue的一个使用。

当然,使用就安装 npm install cropperjs

接着再引入 import Cropper from 'cropperjs'

下面是源码

Picture

<button type="button" id="button" @click="crop">确定

<div style="padding:20px;">
<div class="show">
<div class="picture" :style="'backgroundImage:url('+headerImage+')'">

@H_404_25@
import Cropper from 'cropperjs'
export default {
components: {

},data () {
return {
headerImage:'',picValue:'',cropper:'',croppable:false,panel:false,url:''
}
},mounted () {
//初始化这个裁剪框
var self = this;
var image = document.getElementById('image');
this.cropper = new Cropper(image,{
aspectRatio: 1,viewmode: 1,background:false,zoomable:false,ready: function () {
self.croppable = true;
}
});
},methods: {
getObjectURL (file) {
var url = null ;
if (window.createObjectURL!=undefined) { // basic
url = window.createObjectURL(file) ;
} else if (window.URL!=undefined) { // mozilla(firefox)
url = window.URL.createObjectURL(file) ;
} else if (window.webkitURL!=undefined) { // webkit or chrome
url = window.webkitURL.createObjectURL(file) ;
}
return url ;
},change (e) {
let files = e.target.files || e.dataTransfer.files;
if (!files.length) return;
this.panel = true;
this.picValue = files[0];

this.url = this.getObjectURL(this.picValue);
//每次替换图片要重新得到新的url
if(this.cropper){
this.cropper.replace(this.url);
}
this.panel = true;

},crop () {
this.panel = false;
var croppedCanvas;
var roundedCanvas;

if (!this.croppable) {
return;
}
// Crop
croppedCanvas = this.cropper.getCroppedCanvas();
console.log(this.cropper)
// Round
roundedCanvas = this.getRoundedCanvas(croppedCanvas);

this.headerImage = roundedCanvas.toDataURL();
this.postImg()

},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 () {
//这边写图片上传
}
}
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程之家。

猜你在找的Vue相关文章