如何将图像设置为 canvas 并在点击时获得正确的坐标

How to set image into canvas and get proper coordinates on click

我尝试将不同设备(iphone 7,XR,ipad mini)的屏幕截图设置为 canvas 并在您点击屏幕截图的任何部分时获取坐标。 但是由于不同设备的高度和宽度不同,我无法为手机获取 coordinates.Somehow 我得到了正确的坐标,但它不适用于 tablets.I 尝试了不同的东西,但没有任何效果,因为我'我是 canvas 的新手,不太了解..请帮助.TIA.

我的HTML代码-

<canvas id="canvas" (click)="getOffset($event)" width="500" height="650"
    style="cursor: pointer;margin-top: 1em;"></canvas>

要绘制的Mt TS代码canvas-

let canvas = <HTMLCanvasElement>document.getElementById('canvas');
  let ctx = canvas.getContext('2d');
  let imageObj = new Image();
  let wrh = this.screenData.imageWidth / this.screenData.imageHeight;
  let newWidth = canvas.width;
  let newHeight = newWidth / wrh;
  if (newHeight > canvas.height) {
      newHeight = canvas.height;
      newWidth = newWidth * wrh;
  }  
  imageObj.onload = function() {
    ctx.drawImage(imageObj, 0, 0,newWidth,newHeight);
  };
  imageObj.src =  'data:image/png;base64,'+this.screenData.screen_shot;

以及我正在执行的获取元素的计算-

getOffset(event){
      let x = event.pageX - event.target.offsetLeft;
      let y = event.pageY - event.target.offsetTop;
      let xRatio = this.screenData.imageWidth / document.getElementById('canvas').offsetWidth;
      let yRatio = this.screenData.imageHeight / document.getElementById('canvas').offsetHeight;
      x = Math.round(x * xRatio); //calculated: width of the screenshot 
      y = Math.round(y * yRatio);
    }

我在canvas中设置的高度和宽度是我感觉的问题。

您需要使用 canvas 元素的边界矩形作为偏移量。

此外,不要使用 pageX/pageY。这些不完全支持。

例如

const rect = canvas.getBoundingClientRect();
const mouseX = event.clientX - rect.left;
const mouseY = event.clientY - rect.top;