I am using cropper.js to upload an image in a form. Sometimes it works fine, but sometimes when I upload the image and I use cropper.getValue it displays an error: Uncaught TypeError: Cannot read property 'naturalWidth' of undefined. How can i fix this?
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);
When you create an instance of Cropper you must destroy previuous instance. Calling .destroy() method. This unbind Cropper and you must start it over again. A short example: