简体   繁体   中英

Issue with setCropBoxData in cropper js

I have created a function which resizes the size of the crop box. The user enters height and width, clicks "set" and job is done.

$('body').on('click', '#cropImageModal .set_box_size', function () { 
    var width = $(this).parents('.panel-body').find('.width').val();
    var height = $(this).parents('.panel-body').find('.height').val();
    document.getElementById('imageToCrop').cropper.setCropBoxData({width: parseInt(width), height: parseInt(height)});
});

Except we have a problem when, which is when resize is performed for some reason crop box is scaled down depending on the size of the image.

ie I have an image 700x385 and I set the box to be 700x300 and click "set"... result? the result is 510x219

I have narrowed down to the issue within cropperJS and it is to do with a code on lines 2662-2667:

if (self.ready && self.cropped) {
  data = {
    x: cropBoxData.left - canvasData.left,
    y: cropBoxData.top - canvasData.top,
    width: cropBoxData.width,
    height: cropBoxData.height
  };

  // issue is below
  ratio = imageData.width / imageData.naturalWidth;

  each(data, function (n, i) {
    n /= ratio;
    data[i] = rounded ? Math.round(n) : n;
  });
}

If I remove "ratio" code above the problem is solved but now getCroppedCanvas doesn't work properly due to the added black background to the cropped image.


By the way, same can be seen when using http://fengyuanchen.github.io/cropperjs/ , if you are to:

  1. click "Get Crop Box Data"
  2. adjust the width/height in the box where result presented
  3. click "Set Crop Box Data"
  4. The Width / Height parameters to the right of the image do not match up

在此处输入图片说明

The solution was to figure out the ratio and then perform the calculation of adjusted width and height using calculated ratio:

var width = parseInt($(this).parents('.panel-body').find('.width').val());
var height = parseInt($(this).parents('.panel-body').find('.height').val());

var ratio = document.getElementById('imageToCrop').cropper.imageData.width /  document.getElementById('imageToCrop').cropper.imageData.naturalWidth; 

document.getElementById('imageToCrop').cropper.setCropBoxData({width: width*ratio, height: height*ratio});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM