cropperjs icon indicating copy to clipboard operation
cropperjs copied to clipboard

How to get selection's original x,y after canvas scale?

Open zhi114 opened this issue 11 months ago • 2 comments

I want to get the selection's original x,y after the canvas scale.   I have viewed the source code and googled a lot ,but I can not find a way to get it or calculte it. Any suggestions? Thanks a lot!

zhi114 avatar Feb 26 '24 01:02 zhi114

If you want real image dimensions from the canvas selection you can use the following function:

setTransform() {
  const cropperImage = this.$refs.cropperImage as CropperImage;
  const cropperSelection = this.$refs.cropperSelection as CropperSelection;

  // convert image matrix to image crop data (x,y,scale,rotate)
  const matrix = cropperImage.$getTransform();
  const imageActualWidth = cropperImage.$image.width * matrix[0];
  const imageActualHeight = cropperImage.$image.height * matrix[3];
  const imageActualX = matrix[4] + (cropperImage.$image.width - imageActualWidth) / 2;
  const imageActualY = matrix[5] + (cropperImage.$image.height - imageActualHeight) / 2;
  const rotate = Math.round(Math.atan2(matrix[1], matrix[0]) * (180 / Math.PI));

  // convert selection to actual image dimensions
  const scaleX = imageActualWidth / cropperImage.$image.width;
  const scaleY = imageActualHeight / cropperImage.$image.height;
  const x = (cropperSelection.x - imageActualX) / scaleX;
  const y = (cropperSelection.y - imageActualY) / scaleY;
  const width = Math.ceil(cropperSelection.width / scaleX);
  const height = Math.ceil(cropperSelection.height / scaleY);

  return { x, y, width, height, rotate };
}

EDIT: Just noticed, this snippet is for V2.

marcopixel avatar May 28 '24 07:05 marcopixel

@zhi114 Cropper.js v1 or v2? What do you mean by the canvas scale? <cropper-canvas style="transform: scale(0.5)" />?

fengyuanchen avatar Jun 22 '24 10:06 fengyuanchen