I have a cropper.js plugin on my project, Where users can upload a profile picture.
I am planning on cropping the image and uploading the cropped base64Image image to the server on the fly without reloading the page, Then updating a user profile picture with ajax.
it works fine for the first profile picture the user chose to crop and submit. But then it fails if a user chooses another picture before the page reloads.
My code for loading an image to a cropper modal.
const changeLoader = event => {
let files = event.target.files;
var don = (url) => {
image.src = url;
$modal.modal("show");
}
if (files && files.length > 0) {
reader = new FileReader();
reader.onload = (event) => {
don(reader.result);
};
reader.readAsDataURL(files[0]);
// CroperModal.modal("show");
}
$modal.on('shown.bs.modal', function () {
cropper = new Cropper(image, {
aspectRatio: 1,
viewMode: 1,
preview: '.preview'
});
}).on('hidden.bs.modal', function () {
cropper.destroy();
cropper = null;
});
the line causing the exception
$("#crop").click(function () {
let canvas = cropper.getCroppedCanvas( //line 189
{
width: 600,
height: 600
}
);
}
the exception
Uncaught TypeError: Cannot read properties of null (reading 'toBlob')
at HTMLButtonElement.<anonymous> (index.js:189)
at HTMLButtonElement.dispatch (jquery-3.6.0.min.js:2)
at HTMLButtonElement.v.handle (jquery-3.6.0.min.js:2)