Hi guys i am stuck with javascript library cropper.js. I want to initialize cropper when image is uploaded. I made a function named temp, that trigger when input type file is changed have a look at code html
<input
type="file"
name="cropableImage"
id="cropableImageId"
onchange="temp(this)"
/>
javascript
function temp(input) {
if(input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#previewHolder').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
$("#main_image_section").show();
$("#choose_file").hide();
$("#tools_section").show();
const image=document.getElementById('previewHolder');
cropper = new Cropper(image, {
zoomable: true,
scalable:true,
rotatable:true,
autoCropArea:0.5,
background:false,
modal:true,
autoCrop: true,
viewMode: 0,
cropBoxResizable:true,
setDragMode:true,
});
} else {
alert('select a file to see preview');
$('#previewHolder').attr('src', '');
}
}
function is running and image loads when i select image. No error shows in console. but the cropper do not initialized.
it works when i perform this action in another way. Like i made a button and when clicks the button, function runs and cropper is initialized.
but i need it initialized when image is loaded.
The
readerhas to take time before it has read the file you've uploaded. That means thatnew Cropperis called before thereader.onloadfunction has run.If you want cropper to run after the file is read, then move initialization of
Cropperinside theonloadcallback, after you assign thesrcof the preview holder image.