Wednesday, 19 September 2018

Coordinates from getBoundingClientRect() are off on Ionic 3 app

I am writing an Ionic 3 application to take small pictures.

I am using the Camera Preview plugin to do this:

camera preview

Then I get the coordinates of the green box using this:

<div id="mask" style="width:100%;height:100px;border:10px solid rgb(125, 255, 0);" *ngIf="!picture"> </div>

var box = document.getElementById("mask");
var rect = box.getBoundingClientRect();
console.log("MASK: "+rect.left+" "+rect.top+" "+rect.width+" "+rect.height)

Then I crop the image using the coordinates I got from the box to get this:

cropped image

I am using the following code to crop the image:

generateFromImage(img, x, y, w, h, quality: number = 1, callback) {
   var canvas: any = document.createElement("canvas");
   var image = new Image();
   image.src = img;

   image.onload = () => {
     canvas.width = w;
     canvas.height = h;
     var ctx = canvas.getContext("2d");

     ctx.drawImage(image, x+this.offsetX, y+this.offsetY, w*this.scaleX, h*this.scaleY, 0, 0, w, h);

     var dataUrl = canvas.toDataURL('image/jpeg', quality);

     callback(dataUrl)
   }

}

Where x,y,w,h are the coordinates I got from box.getBoundingClientRect().

As you can see, I had to introduce an offsetX, offsetY, scaleX, scaleY to adjust the coordinates because it was not working.

drawImage() parameters are sx,sy,sw,sh (source box -> coordinates from the original image) and x,y,w,h (destination -> coordinate of the destination image). I do not understand why it is off.

After some trial and error, I found that the following configuration works for my iPhone 8:

  • offsetX=125
  • offsetY=48
  • scaleX=1.7
  • scaleY=1.4

The Y coordinate difference I suspect that has something to do with the application toolbar. I have no idea why x is off and why using the same w and h on both source and destination does not keep the aspect ratio.

I did not test on another devices but it will most certainly fail because the offsets and scale factors will be different.

Why is it happening? Why do I need to fix the coordinates?

Thanks for your help!



from Coordinates from getBoundingClientRect() are off on Ionic 3 app

No comments:

Post a Comment