【问题标题】:How to get Coordinate of Cropped Image by CropperJS?如何通过 CropperJS 获取裁剪图像的坐标?
【发布时间】:2016-11-29 18:56:57
【问题描述】:

我正在使用cropper JS 来裁剪我的图像。我能够获得画布的宽度和高度,但是,需要知道裁剪图像的坐标(X 和 Y)。

这是我的代码-

(function () {


  //getting ratio
  function getImageRatio(sourceCanvas) {
    var canvas = document.createElement('canvas');
    var context = canvas.getContext('2d');
    var width = sourceCanvas.width;
    var height = sourceCanvas.height;



    canvas.width = width;
    canvas.height = height;


    context.beginPath();
    context.arc(width / 2, height / 2, Math.min(width, height) / 2, 0, 2 * Math.PI);
    context.strokeStyle = 'rgba(0,0,0,0)';
    context.stroke();
    context.clip();
    context.drawImage(sourceCanvas, 0, 0, width, height);

    return canvas;
  }




  window.addEventListener('DOMContentLoaded', function () {
    var image = document.getElementById('image');
    var button = document.getElementById('button');
    var result = document.getElementById('result');
    var croppable = false;
    var cropper = new Cropper(image, {
      aspectRatio: 1,
      viewMode: 1,
      built: function () {
        croppable = true;
      }
    });

    button.onclick = function () {
      var croppedCanvas;
      var roundedCanvas;
      var roundedImage;

      if (!croppable) {
        return;
      }

      // Crop
      croppedCanvas = cropper.getCroppedCanvas();


      console.log(getImageRatio(croppedCanvas));

    };

  });

})();

任何想法,如何获取裁剪图像的坐标,以便我可以通过 PHP 裁剪该图像。

【问题讨论】:

  • 我不知道为什么有些人总是有消极的心态!在这里投反对票的原因是什么?

标签: javascript php image crop jcrop


【解决方案1】:

所以,如果我理解正确,您正在寻找 method getData

它将按照文档所述返回这些属性:

x: the offset left of the cropped area
y: the offset top of the cropped area
width: the width of the cropped area
height: the height of the cropped area
rotate: the rotated degrees of the image
scaleX: the scaling factor to apply on the abscissa of the image
scaleY: the scaling factor to apply on the ordinate of the image

虽然,我建议看一下文档的这一部分: https://github.com/fengyuanchen/cropper#getcroppedcanvasoptions

具体在这部分:

之后,您可以直接将画布显示为图像,或者使用 HTMLCanvasElement.toDataURL 获取数据 URL,或者使用 HTMLCanvasElement.toBlob 获取 blob 并使用 FormData 将其上传到服务器(如果浏览器支持这些 API)。

如果由于某些浏览器限制(您始终可以添加 polyfill)而无法使用 toBlob 方法,您可以在画布 (IE9+) 上使用 toDataUrl 获取图像。并将其发送到已经裁剪的后端服务。为此,您将需要执行以下操作:

var formData = new FormData();
formData.append('image', canvas.toDataURL());

您可以在caniuse中查看formData浏览器支持

希望对您有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-10
    • 2016-07-10
    • 2016-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多