Cropper.js的getValue并不是每次我上传照片时都有效



我使用cropper.js上传表单中的图像。有时它很好,但有时当我上传图像并使用cropper.getValue时,它会显示一个错误:Unaught TypeError:无法读取undefined的属性'naturalWidth'。我该怎么解决这个问题?

var imageForm = document.querySelector(".userImage");
var fileInput = document.querySelector("input[name=user_photo]");
fileInput.addEventListener("change", function(event){
var reader = new FileReader();
reader.onload = function(){
var output          = document.querySelector('.croppr-image');
var submitImageCont = document.querySelector('#submitImage');
output.src = reader.result;
imageForm.insertBefore(output, submitImageCont);
var overlay = document.querySelector(".overlay")
overlay.classList.remove("displayNone");
var publicProfileForm = document.querySelector("form.publicProfile");
var cropper = new Croppr('#cropper', {
onInitialize: (instance) => { console.log(instance); },
onCropStart: (data) => { console.log('start', data); },
onCropEnd: (data) => { console.log('end', data); },
onCropMove: (data) => { console.log('move', data); }
});
var value = cropper.getValue();
publicProfileForm.querySelector("input[name=cropped_image_x]").value = value.x;
publicProfileForm.querySelector("input[name=cropped_image_y]").value = value.y;
publicProfileForm.querySelector("input[name=cropped_image_width]").value = value.width;
publicProfileForm.querySelector("input[name=cropped_image_height]").value = value.height;
}
}, false);

创建Cropper实例时,必须销毁前一个实例。正在调用.destroy((方法。这解除了Cropper的绑定,您必须重新启动它。一个简短的例子:

var cropper = null;
fileInput.addEventListener("change", function(event){

// a lot of stuffs

if(cropper){
cropper.destroy();
}

cropper = new Croppr('#cropper', {
onInitialize: (instance) => { console.log(instance); },
onCropStart: (data) => { console.log('start', data); },
onCropEnd: (data) => { console.log('end', data); },
onCropMove: (data) => { console.log('move', data); }
});

// another stuffs
}, false);

相关内容

  • 没有找到相关文章

最新更新