cropper github传送门
思路:
- 上传本地图片;
- 预览(因为cropperjs要对显示的块级元素操作);
- 本地图片出现后;
- 开始选择裁剪选取;
- 选定后裁剪;
- 代替预览的src;
- 最后销毁cropper。
代码如下:
// html部分
<input type="file" id="uploadImg" @change="uploadimage" accept="image/jpg,image/jpeg,image/png,image/PNG">
<img id="uploadImage" :src="uploadSrc" alt="">
// js
导入
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs';
在data中定义变量
data(){
return{
uploadSrc: null,
cropper:'',
}
}
methods:{
// 裁剪选取
changeImgSize(){
var image = document.getElementById('uploadImage');
console.log("触发开始裁剪功能:",image)
try{
this.cropper = new Cropper(image, {
aspectRatio: 1,
viewMode: 1,
background:false,
autoCrop: true,
center: true,
zoomable:true,
ready: function () {
self.croppable = true;
}
});
}catch(e){
console.log("裁剪选取异常",e)
}
},
// 裁剪
uploadImgs() {
this.afterImg = this.cropper
.getCroppedCanvas({
width: 150, //输出画布的目标宽度
height: 150, //输出画布的目标高度。
minWidth: 150, //输出画布的最小目标宽度,默认值为0。
minHeight: 150, //输出画布的最小目标高度,默认值为0。
maxWidth: 150, //输出画布的最大目标宽度,默认值为Infinity(无穷大)。
maxHeight: 150, //输出画布的最大目标高度,默认值为Infinity(无穷大)。
imageSmoothingEnabled: true,
imageSmoothingQuality: 'high'
})
.toDataURL('image/jpeg')
this.cropper.destroy() // 销毁前不能第二次显示裁剪选取
this.uploadSrc = this.afterImg; // 替换图片地址
// 这里结束只是前端操作,并没有上传到服务器
},
// 本地上传图片
uploadimage(e){
if(this.cropper)this.cropper.destroy();
let img = new FileReader();
img.readAsDataURL(e.target.files[0]);
img.onload = ({ target }) => {
this.uploadSrc = target.result; //将img转化为二进制数据
console.log("target:",target)
setTimeout(() => {
this.changeImgSize() // 等待目的是为了自动显示裁剪选取
}, 500);
// this.changeImgSize()
};
},
}
// 自动获取裁剪选取 => 自动裁剪
methods:{
// 裁剪选取
changeImgSize(){
var image = document.getElementById('uploadImage');
console.log("触发开始裁剪功能:",image)
try{
this.cropper = new Cropper(image, {
aspectRatio: 1,
viewMode: 1,
background:false,
autoCrop: true,
center: true,
zoomable:true,
ready: () => {
self.croppable = true;
this.afterImg = this.cropper
.getCroppedCanvas({
width: 150, //输出画布的目标宽度
height: 150, //输出画布的目标高度。
minWidth: 150, //输出画布的最小目标宽度,默认值为0。
minHeight: 150, //输出画布的最小目标高度,默认值为0。
maxWidth: 150, //输出画布的最大目标宽度,默认值为Infinity(无穷大)。
maxHeight: 150, //输出画布的最大目标高度,默认值为Infinity(无穷大)。
imageSmoothingEnabled: true,
imageSmoothingQuality: 'high'
})
.toDataURL('image/jpeg')
this.cropper.destroy() // 销毁前不能第二次显示裁剪选取
this.uploadSrc = this.afterImg; // 替换图片地址
// 这里结束只是前端操作,并没有上传到服务器
}
});
}catch(e){
console.log("裁剪选取异常",e)
}
},
// 本地上传图片
uploadimage(e){
if(this.cropper)this.cropper.destroy();
let img = new FileReader();
img.readAsDataURL(e.target.files[0]);
img.onload = ({ target }) => {
this.uploadSrc = target.result; //将img转化为二进制数据
console.log("target:",target)
setTimeout(() => {
this.changeImgSize() // 等待目的是为了自动显示裁剪选取
}, 500);
// this.changeImgSize()
};
},
}