angular - 如何将图像设置到画布中并在点击时获得正确的坐标
问题描述
我尝试将不同设备(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);
}
我在画布中设置的高度和宽度是我觉得的问题。
解决方案
您需要使用画布元素的边界矩形进行偏移。
另外,不要使用 pageX/pageY。这些不完全支持。
例如
const rect = canvas.getBoundingClientRect();
const mouseX = event.clientX - rect.left;
const mouseY = event.clientY - rect.top;
推荐阅读
- python - 通过从报纸上收集文本重新输入代码时,除了第一个链接之外,所有内容都被忽略了
- r - 在分隔符处拆分列,用拆分中的值填充新列
- reactjs - React redux + react-loadable ...如何使其工作?
- android - Android Google Drive REST API 离线缓存
- python-3.x - Luigi Pipeline in Dockerfile; unknown instruction PYTHONPATH
- c# - 悬停时如何更改按钮的边框颜色(c# | Visual Studio)
- node.js - 当尝试将变量传递给另一个模块时,将代码拆分到Nodejs中的自定义模块时,它会变得未定义
- c++ - 非法操作stringstream << stringstream与c ++ 11
- node.js - 如何在 Node.js 的 Handlbars 中检查数字的值?
- python - 从 Gunicorn/Nginx WSGI API 权限错误运行 Docker SDK