如何让 Cropper.js 处理来自 URL 的图像

How can I make Cropper.js work with images from URL

我正在尝试让 Cropper.js 处理来自网络的 URL 图片。

https://github.com/fengyuanchen/cropperjs

当我从我的设备上传图片时它工作正常但是当涉及到在线图片时..我有很多错误,包括:

From origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

裁剪器没有出现在图像上,我给出了 Cors 错误。

这是我的代码:

$(function($) {
  $("#submit").click(function() {
    var selectedFile = $("#imglink").val();
    $("#photo").attr("src", selectedFile);
    var image = document.getElementById("photo");
    console.log(image);
    const cropper = new Cropper(image, {
      aspectRatio: 16 / 9,
      cropBoxResizable: false
    });
    cropper.crop();
    $("#crop-button").on("click", function() {
      cropper.getCroppedCanvas().toBlob(function(blob) {
        const formData = new FormData();
        formData.append("croppedImage", blob);
        $.ajax({
          type: "POST",
          url: "img/index.php",
          data: formData,
          processData: false,
          contentType: false,
          success: function(data) {},
          error: function(err) {}
        });
      });
    });
  });
});

您可以使用canvas的toDataURL函数将图像转换为base64,然后再次加载到image.src

var canvas = cropper.getCroppedCanvas()

//replacing the image url with base64 data
image.src = canvas.toDataURL(); 

canvas.toBlob(function(blob) {
    const formData = new FormData();
    formData.append("croppedImage", blob);
    $.ajax({
      type: "POST",
      url: "img/index.php",
      data: formData,
      processData: false,
      contentType: false,
      success: function(data) {},
      error: function(err) {}
    });
}

希望有用!