I'm trying to implement cropping images in my webapp. What I am trying to achieve is crop an image to have a 3/4 ratio, and crop that cropped image to have an avatar (ratio 1). Basically I am cropping twice the same image. When I upload an image for the first time it works fine. When I upload a second time (swapping the image for another one), I have the following error:
Uncaught TypeError: Cannot read properties of null (reading 'toDataURL')
Which is weird because is not null (is a base64 image). And not just that, I am also creating the file of the image as well. I know this because I am printing the values. What am I doing wrong?
This is my code:
let croppedImage
let croppedImageUrl
let croppedAvatar
$( "#profile_picture_upload" ).change( function() {
const input = document.getElementById( "profile_picture_upload" )
const imageFile = input.files[ 0 ]
const image = $( ".crop-image" )
let cropper
if( imageFile ) {
const reader = new FileReader()
reader.onload = function( e ) {
if( cropper ) cropper.destroy()
const imageDataUrl = e.target.result
$( ".crop-image" ).attr( "src", imageDataUrl )
$( "#cropModalLabel" ).text( "Profile photo" )
$( "#cropModal" ).modal( "show" )
// Initialize the cropper after the modal shown completely.
// Otherwise, we will not get a correct cropper.
$( "#cropModal" ).on( "shown.bs.modal", function() {
// eslint-disable-next-line no-undef
cropper = new Cropper( image[ 0 ], {
aspectRatio: 3 / 4,
viewMode: 1,
autoCropArea: 1,
ready: function() {
$( ".crop-button-image" ).on( "click", function() {
croppedImage = cropper.getCroppedCanvas( {
width: 375,
height: 500
} ).toDataURL( "image/jpeg" )
console.log( "1. image (dataurl)", croppedImage )
croppedImageUrl = croppedImage
croppedImage = dataURLtoFile( croppedImage, "croppedImage.png" )
console.log( "2. image (file)", croppedImage )
// Now crop the cropped image to have an avatar
$( ".crop-image" ).attr( "src", croppedImageUrl )
cropper.replace( croppedImageUrl )
cropper.setAspectRatio( 1 )
$( ".crop-button-avatar" ).on( "click", function() {
croppedAvatar = cropper.getCroppedCanvas( {
width: 200,
height: 200
} ).toDataURL( "image/jpeg" )
console.log( "1. avatar (dataurl)", croppedAvatar )
croppedAvatar = dataURLtoFile( croppedAvatar, "croppedAvatar.png" )
console.log( "2. avatar (file)", croppedAvatar )
cropper.destroy()
$( "#cropModal" ).modal( "hide" )
} )
} )
}
} )
} )
}
reader.readAsDataURL( imageFile )
}
} )