【发布时间】:2014-03-10 03:11:53
【问题描述】:
背景:我有一个 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 方法中的矩阵值。
【问题讨论】:
-
:那么你最后是怎么解决你的问题的呢?...我被同样的问题困住了:(
标签: javascript html canvas