首页 > 解决方案 > 如何将图像设置到画布中并在点击时获得正确的坐标

问题描述

我尝试将不同设备(iphone 7、XR、ipad mini)的屏幕截图设置到画布中,并在您单击屏幕截图的任何部分时获取坐标。但是由于不同设备的高度,宽度不同,我无法获取坐标。不知何故,对于手机,我得到了正确的坐标,但它不适用于平板电脑。我尝试了不同的东西,但没有任何效果,因为我是画布的新手没有太多想法..请帮助.TIA。

我的 HTML 代码 -

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

Mt TS 代码绘制画布-

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;

和我正在做的计算 fetch element-

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);
    }

我在画布中设置的高度和宽度是我觉得的问题。

标签: angularcanvashtml5-canvascoordinatesoffset

解决方案


您需要使用画布元素的边界矩形进行偏移。

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

例如

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

推荐阅读