cropper.js could not be initialized not showing any error

1k Views Asked by At

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.

1

There are 1 best solutions below

0
Emiel Zuurbier On

The reader has to take time before it has read the file you've uploaded. That means that new Cropper is called before the reader.onload function has run.

If you want cropper to run after the file is read, then move initialization of Cropper inside the onload callback, after you assign the src of the preview holder image.

let cropper;
const previewHolder = document.getElementById("previewHolder");

function temp(input) {
  if (input.files.length) {
    const reader = new FileReader();
    reader.onload = function (e) {
      // Here the image is loaded. 
      // Set it to the preview holder.
      previewHolder.src = e.target.result;

      // Now the cropper should be able to use the loaded image.
      cropper = new Cropper(previewHolder, {
        zoomable: true,
        scalable: true,
        rotatable: true,
        autoCropArea: 0.5,
        background: false,
        modal: true,
        autoCrop: true,
        viewMode: 0,
        cropBoxResizable: true,
        setDragMode: true,
      });
    };
    reader.readAsDataURL(input.files[0]);
  }
}