【问题标题】:Cropper.js getValue is not working every time I upload a photo每次上传照片时 Cropper.js getValue 都不起作用
【发布时间】:2020-12-01 09:03:00
【问题描述】:

我正在使用cropper.js 上传表单中的图像。有时它可以正常工作,但有时当我上传图像并使用cropper.getValue 时会显示错误:未捕获的类型错误:无法读取未定义的属性“naturalWidth”。我该如何解决这个问题?

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);

【问题讨论】:

  • 请添加您的代码,以便我们查看问题所在。

标签: javascript getvalue cropper


【解决方案1】:

当您创建 Cropper 实例时,您必须销毁前一个实例。调用 .destroy() 方法。这个解绑 Cropper,你必须重新开始。一个简短的例子:

    var cropper = null;

    fileInput.addEventListener("change", function(event){
    
    // a lot of stuffs
    
    if(cropper){
        cropper.destroy();
    }
    
    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); }
    });
    
    // another stuffs
    }, false);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多