背景:我有一个 HTML5 画布并在上面绘制了一张图片。当图片第一次加载时,它以 100% 的比例加载。该图片为 5000 x 5000 像素,而画布大小为 600 x 600 像素。因此,在加载时,我只能看到前 600 x 像素和 600 y 像素的部分。我可以对画布上的图片进行缩放和平移。
我的问题:我正在尝试找出一个算法,可以返回相对于图片而不是画布的鼠标点击像素坐标,同时考虑了缩放和平移。我知道已经有很多关于这个问题的讨论,但我看到的都没有解决我的问题。我的问题是当我有多个平移和缩放时。我可以进行一次缩放并获得正确的坐标,然后我可以再次缩放并再次获得正确的坐标,但是一旦我进行多次缩放或平移,坐标就会偏差。
以下是我目前所拥有的内容:
//get pixel coordinates from canvas mousePos.x, mousePos.y
(mousePos.x - x_translation)/scale //same for mousePos.y
annotationCanvas.addEventListener('mouseup',function(evt){
dragStart = null;
if (!dragged) {
var mousePos = getMousePos(canvas, evt);
var message1 = " mouse x: " + (mousePos.x) + ' ' + "mouse y: " + (mousePos.y);
var message = " x: " + ((mousePos.x + accX)/currentZoom*currentZoom) + ' ' + "y: " + ((mousePos.y + accY)/currentZoom);
console.log(message);
console.log(message1);
console.log("zoomAcc = " + zoomAcc);
console.log("currentZoom = " + currentZoom);
ctx.fillStyle="#FF0000";
ctx.fillRect((mousePos.x + accX)/currentZoom, (mousePos.y + accY)/currentZoom, -5, -5);
}
},true);
//accX and accY are the cumulative shift for x and y respectively, and xShift and xShift yShift are the incremental shifts of x and y respectively
当前缩放比例为累积缩放比例,zoomAcc是该点的单次迭代缩放比例。因此,在这种情况下,当我放大时,zoomAcc始终为1.1,currentZoom = currentZoom * zoomAcc。
为什么这是错误的?如果有人能够向我展示如何跟踪这些变换,然后将它们应用于mousePos.x和mousePos.y,我将不胜感激。
谢谢。
更新:
在图像中,绿点是我点击的位置,红点是使用markE方法计算该点的位置。 m值是您的markE方法中的矩阵值。