最近在做項(xiàng)目的時(shí)候,遇到了裁剪框不超出圖片的需求拢锹,只能自己設(shè)法去完成了锭部。代碼如下:
/**
* 計(jì)算新位置的函數(shù)
* @param {Object} scope -- cropper對(duì)象
*/
calData(scope){
const cropBoxData = $(scope).cropper('getCropBoxData');
const container = $('.cropper-container')[0].getBoundingClientRect(); // 容器
const image = $('.cropper-canvas')[0].getBoundingClientRect(); // 圖片
const box = $('.cropper-crop-box')[0].getBoundingClientRect(); // 裁剪框
const rightXLeft = image.left - container.left;
const rightXRight = image.left - container.left + (image.width - box.width);
const rightYTop = image.top - container.top;
const rightYBottom = image.top - container.top + (image.height - box.height);
let x = undefined;
let y = undefined;
let stop = false;
if(box.left<image.left){ // 到了左邊界
x = rightXLeft;
stop = true;
} else if (box.right>image.right){ // 到了右邊界
x = rightXRight;
stop = true;
}
if(box.top<image.top){ // 到了上邊界
y = rightYTop;
stop = true;
}else if(box.bottom>image.bottom){ // 到了下邊界
y = rightYBottom;
stop = true;
}
return {
cropBoxData:{
left:x||cropBoxData.left,
top:y||cropBoxData.top,
width:cropBoxData.width,
height:cropBoxData.height
},
stop:stop
}
}
handlerOver(scope){ // 溢出 裁剪框 超過圖片大小時(shí)候的操作。
const cropBoxData = $(scope).cropper('getCropBoxData');
const image = $('.cropper-canvas')[0].getBoundingClientRect(); // 圖片
const box = $('.cropper-crop-box')[0].getBoundingClientRect(); // 裁剪框
if(box.width>=image.width){
// debugger
$(scope).cropper('setCropBoxData',{
left:cropBoxData.left,
top:cropBoxData.top,
width:image.width - 1,
height: (image.width - 1) / 16 * 9
} );
}
}
cropper(){
const _this = this;
var cropper = this.$container.find(".realImg").cropper({
aspectRatio: _this.options.aspectRatio,
checkCrossOrigin: true,
checkOrientation: false,
cropmove:function(e){ // 只有這個(gè)才能阻止移動(dòng)面褐。。取胎。
let data = null;
data = this.newData;
const scope = this;
if(data.stop){ // 停止移動(dòng)
e.preventDefault();
$(scope).cropper('setCropBoxData', data.cropBoxData);
!clearTime && (function(data){
clearTime = setTimeout(()=>{
data.stop = false;
clearTime = undefined;
},500)
})(data)
}
},
crop:function(e){ // 記錄了位置
this.newData = _this.calData(this);
},
cropend:function(e){ // 最終還原位置 做個(gè)判斷
const scope = this;
const data = _this.calData(this);
$(this).cropper('setCropBoxData', data.cropBoxData);
_this.handlerOver(this);
setTimeout(function(){
const datafinal = _this.calData(this);
$(scope).cropper('setCropBoxData', datafinal.cropBoxData);
},300);
},
zoom: function (e) {
// console.log(e);
e.preventDefault();
}
});
}