fengyuanchen / cropperjs

JavaScript image cropper.
https://fengyuanchen.github.io/cropperjs/
MIT License
13.16k stars 2.42k forks source link

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

Closed zhi114 closed 3 months ago

zhi114 commented 9 months ago

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!

marcopixel commented 6 months ago

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.

fengyuanchen commented 5 months ago

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